blob: 1be98d7fabc234346a48885c7e32da9af58731f0 [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 Hackborn9ec6cdd2012-05-31 10:57:54 -0700497 protected BroadcastFilter[] newArray(int size) {
498 return new BroadcastFilter[size];
499 }
500
501 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700502 protected String packageForFilter(BroadcastFilter filter) {
503 return filter.packageName;
504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 };
506
507 /**
508 * State of all active sticky broadcasts. Keys are the action of the
509 * sticky Intent, values are an ArrayList of all broadcasted intents with
510 * that action (which should usually be one).
511 */
512 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
513 new HashMap<String, ArrayList<Intent>>();
514
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700515 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516
517 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700518 * Backup/restore process management
519 */
520 String mBackupAppName = null;
521 BackupRecord mBackupTarget = null;
522
523 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 * List of PendingThumbnailsRecord objects of clients who are still
525 * waiting to receive all of the thumbnails for a task.
526 */
527 final ArrayList mPendingThumbnails = new ArrayList();
528
529 /**
530 * List of HistoryRecord objects that have been finished and must
531 * still report back to a pending thumbnail receiver.
532 */
533 final ArrayList mCancelledThumbnails = new ArrayList();
534
Amith Yamasani742a6712011-05-04 14:49:28 -0700535 final ProviderMap mProviderMap = new ProviderMap();
536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 /**
538 * List of content providers who have clients waiting for them. The
539 * application is currently being launched and the provider will be
540 * removed from this list once it is published.
541 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700542 final ArrayList<ContentProviderRecord> mLaunchingProviders
543 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544
545 /**
546 * Global set of specific Uri permissions that have been granted.
547 */
548 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
549 = new SparseArray<HashMap<Uri, UriPermission>>();
550
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800551 CoreSettingsObserver mCoreSettingsObserver;
552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 /**
554 * Thread-local storage used to carry caller permissions over through
555 * indirect content-provider access.
556 * @see #ActivityManagerService.openContentUri()
557 */
558 private class Identity {
559 public int pid;
560 public int uid;
561
562 Identity(int _pid, int _uid) {
563 pid = _pid;
564 uid = _uid;
565 }
566 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
569
570 /**
571 * All information we have collected about the runtime performance of
572 * any user id that can impact battery performance.
573 */
574 final BatteryStatsService mBatteryStatsService;
575
576 /**
577 * information about component usage
578 */
579 final UsageStatsService mUsageStatsService;
580
581 /**
582 * Current configuration information. HistoryRecord objects are given
583 * a reference to this object to indicate which configuration they are
584 * currently running in, so this object must be kept immutable.
585 */
586 Configuration mConfiguration = new Configuration();
587
588 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800589 * Current sequencing integer of the configuration, for skipping old
590 * configurations.
591 */
592 int mConfigurationSeq = 0;
593
594 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700595 * Hardware-reported OpenGLES version.
596 */
597 final int GL_ES_VERSION;
598
599 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 * List of initialization arguments to pass to all processes when binding applications to them.
601 * For example, references to the commonly used services.
602 */
603 HashMap<String, IBinder> mAppBindArgs;
604
605 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700606 * Temporary to avoid allocations. Protected by main lock.
607 */
608 final StringBuilder mStringBuilder = new StringBuilder(256);
609
610 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 * Used to control how we initialize the service.
612 */
613 boolean mStartRunning = false;
614 ComponentName mTopComponent;
615 String mTopAction;
616 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700617 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 boolean mSystemReady = false;
619 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700620 boolean mWaitingUpdate = false;
621 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700622 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700623 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624
625 Context mContext;
626
627 int mFactoryTest;
628
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700629 boolean mCheckedForSetup;
630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700632 * The time at which we will allow normal application switches again,
633 * after a call to {@link #stopAppSwitches()}.
634 */
635 long mAppSwitchesAllowedTime;
636
637 /**
638 * This is set to true after the first switch after mAppSwitchesAllowedTime
639 * is set; any switches after that will clear the time.
640 */
641 boolean mDidAppSwitch;
642
643 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700644 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700645 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700646 long mLastPowerCheckRealtime;
647
648 /**
649 * Last time (in uptime) at which we checked for power usage.
650 */
651 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700652
653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 * Set while we are wanting to sleep, to prevent any
655 * activities from being started/resumed.
656 */
657 boolean mSleeping = false;
658
659 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700660 * State of external calls telling us if the device is asleep.
661 */
662 boolean mWentToSleep = false;
663
664 /**
665 * State of external call telling us if the lock screen is shown.
666 */
667 boolean mLockScreenShown = false;
668
669 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700670 * Set if we are shutting down the system, similar to sleeping.
671 */
672 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673
674 /**
675 * Task identifier that activities are currently being started
676 * in. Incremented each time a new task is created.
677 * todo: Replace this with a TokenSpace class that generates non-repeating
678 * integers that won't wrap.
679 */
680 int mCurTask = 1;
681
682 /**
683 * Current sequence id for oom_adj computation traversal.
684 */
685 int mAdjSeq = 0;
686
687 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700688 * Current sequence id for process LRU updating.
689 */
690 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691
692 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700693 * Keep track of the non-hidden/empty process we last found, to help
694 * determine how to distribute hidden/empty processes next time.
695 */
696 int mNumNonHiddenProcs = 0;
697
698 /**
699 * Keep track of the number of hidden procs, to balance oom adj
700 * distribution between those and empty procs.
701 */
702 int mNumHiddenProcs = 0;
703
704 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700705 * Keep track of the number of service processes we last found, to
706 * determine on the next iteration which should be B services.
707 */
708 int mNumServiceProcs = 0;
709 int mNewNumServiceProcs = 0;
710
711 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 * System monitoring: number of processes that died since the last
713 * N procs were started.
714 */
715 int[] mProcDeaths = new int[20];
716
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700717 /**
718 * This is set if we had to do a delayed dexopt of an app before launching
719 * it, to increasing the ANR timeouts in that case.
720 */
721 boolean mDidDexOpt;
722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 String mDebugApp = null;
724 boolean mWaitForDebugger = false;
725 boolean mDebugTransient = false;
726 String mOrigDebugApp = null;
727 boolean mOrigWaitForDebugger = false;
728 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700729 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700730 String mProfileApp = null;
731 ProcessRecord mProfileProc = null;
732 String mProfileFile;
733 ParcelFileDescriptor mProfileFd;
734 int mProfileType = 0;
735 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800736 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700738 static class ProcessChangeItem {
739 static final int CHANGE_ACTIVITIES = 1<<0;
740 static final int CHANGE_IMPORTANCE= 1<<1;
741 int changes;
742 int uid;
743 int pid;
744 int importance;
745 boolean foregroundActivities;
746 }
747
Jeff Sharkeya4620792011-05-20 15:29:23 -0700748 final RemoteCallbackList<IProcessObserver> mProcessObservers
749 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700750 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
751
752 final ArrayList<ProcessChangeItem> mPendingProcessChanges
753 = new ArrayList<ProcessChangeItem>();
754 final ArrayList<ProcessChangeItem> mAvailProcessChanges
755 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 /**
758 * Callback of last caller to {@link #requestPss}.
759 */
760 Runnable mRequestPssCallback;
761
762 /**
763 * Remaining processes for which we are waiting results from the last
764 * call to {@link #requestPss}.
765 */
766 final ArrayList<ProcessRecord> mRequestPssList
767 = new ArrayList<ProcessRecord>();
768
769 /**
770 * Runtime statistics collection thread. This object's lock is used to
771 * protect all related state.
772 */
773 final Thread mProcessStatsThread;
774
775 /**
776 * Used to collect process stats when showing not responding dialog.
777 * Protected by mProcessStatsThread.
778 */
779 final ProcessStats mProcessStats = new ProcessStats(
780 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700781 final AtomicLong mLastCpuTime = new AtomicLong(0);
782 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 long mLastWriteTime = 0;
785
786 /**
787 * Set to true after the system has finished booting.
788 */
789 boolean mBooted = false;
790
Dianne Hackborn7d608422011-08-07 16:24:18 -0700791 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700792 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793
794 WindowManagerService mWindowManager;
795
796 static ActivityManagerService mSelf;
797 static ActivityThread mSystemThread;
798
Amith Yamasani258848d2012-08-10 17:06:33 -0700799 private int mCurrentUserId;
Amith Yamasani258848d2012-08-10 17:06:33 -0700800 private UserManager mUserManager;
801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 private final class AppDeathRecipient implements IBinder.DeathRecipient {
803 final ProcessRecord mApp;
804 final int mPid;
805 final IApplicationThread mAppThread;
806
807 AppDeathRecipient(ProcessRecord app, int pid,
808 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800809 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 TAG, "New death recipient " + this
811 + " for thread " + thread.asBinder());
812 mApp = app;
813 mPid = pid;
814 mAppThread = thread;
815 }
816
817 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800818 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 TAG, "Death received in " + this
820 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 synchronized(ActivityManagerService.this) {
822 appDiedLocked(mApp, mPid, mAppThread);
823 }
824 }
825 }
826
827 static final int SHOW_ERROR_MSG = 1;
828 static final int SHOW_NOT_RESPONDING_MSG = 2;
829 static final int SHOW_FACTORY_ERROR_MSG = 3;
830 static final int UPDATE_CONFIGURATION_MSG = 4;
831 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
832 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 static final int SERVICE_TIMEOUT_MSG = 12;
834 static final int UPDATE_TIME_ZONE = 13;
835 static final int SHOW_UID_ERROR_MSG = 14;
836 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700838 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700839 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800840 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700841 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
842 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700843 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700844 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700845 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700846 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700847 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700848 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700849 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700850 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800852 static final int FIRST_ACTIVITY_STACK_MSG = 100;
853 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
854 static final int FIRST_COMPAT_MODE_MSG = 300;
855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700857 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700858 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859
860 final Handler mHandler = new Handler() {
861 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 //}
864
865 public void handleMessage(Message msg) {
866 switch (msg.what) {
867 case SHOW_ERROR_MSG: {
868 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 synchronized (ActivityManagerService.this) {
870 ProcessRecord proc = (ProcessRecord)data.get("app");
871 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 return;
874 }
875 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700876 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800877 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 d.show();
879 proc.crashDialog = d;
880 } else {
881 // The device is asleep, so just pretend that the user
882 // saw a crash dialog and hit "force quit".
883 res.set(0);
884 }
885 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700886
887 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } break;
889 case SHOW_NOT_RESPONDING_MSG: {
890 synchronized (ActivityManagerService.this) {
891 HashMap data = (HashMap) msg.obj;
892 ProcessRecord proc = (ProcessRecord)data.get("app");
893 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800894 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 return;
896 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800897
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700898 Intent intent = new Intent("android.intent.action.ANR");
899 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800900 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
901 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700902 }
903 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800904 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700905 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800906
Justin Kohbc52ca22012-03-29 15:11:44 -0700907 if (mShowDialogs) {
908 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700909 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700910 d.show();
911 proc.anrDialog = d;
912 } else {
913 // Just kill the app if there is no dialog to be shown.
914 killAppAtUsersRequest(proc, null);
915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700917
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700918 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700920 case SHOW_STRICT_MODE_VIOLATION_MSG: {
921 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
922 synchronized (ActivityManagerService.this) {
923 ProcessRecord proc = (ProcessRecord) data.get("app");
924 if (proc == null) {
925 Slog.e(TAG, "App not found when showing strict mode dialog.");
926 break;
927 }
928 if (proc.crashDialog != null) {
929 Slog.e(TAG, "App already has strict mode dialog: " + proc);
930 return;
931 }
932 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700933 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700934 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
935 d.show();
936 proc.crashDialog = d;
937 } else {
938 // The device is asleep, so just pretend that the user
939 // saw a crash dialog and hit "force quit".
940 res.set(0);
941 }
942 }
943 ensureBootCompleted();
944 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 case SHOW_FACTORY_ERROR_MSG: {
946 Dialog d = new FactoryErrorDialog(
947 mContext, msg.getData().getCharSequence("msg"));
948 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700949 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 } break;
951 case UPDATE_CONFIGURATION_MSG: {
952 final ContentResolver resolver = mContext.getContentResolver();
953 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
954 } break;
955 case GC_BACKGROUND_PROCESSES_MSG: {
956 synchronized (ActivityManagerService.this) {
957 performAppGcsIfAppropriateLocked();
958 }
959 } break;
960 case WAIT_FOR_DEBUGGER_MSG: {
961 synchronized (ActivityManagerService.this) {
962 ProcessRecord app = (ProcessRecord)msg.obj;
963 if (msg.arg1 != 0) {
964 if (!app.waitedForDebugger) {
965 Dialog d = new AppWaitingForDebuggerDialog(
966 ActivityManagerService.this,
967 mContext, app);
968 app.waitDialog = d;
969 app.waitedForDebugger = true;
970 d.show();
971 }
972 } else {
973 if (app.waitDialog != null) {
974 app.waitDialog.dismiss();
975 app.waitDialog = null;
976 }
977 }
978 }
979 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700981 if (mDidDexOpt) {
982 mDidDexOpt = false;
983 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
984 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700985 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700986 return;
987 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700988 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 } break;
990 case UPDATE_TIME_ZONE: {
991 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800992 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
993 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 if (r.thread != null) {
995 try {
996 r.thread.updateTimeZone();
997 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800998 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000 }
1001 }
1002 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001003 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001004 case CLEAR_DNS_CACHE: {
1005 synchronized (ActivityManagerService.this) {
1006 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1007 ProcessRecord r = mLruProcesses.get(i);
1008 if (r.thread != null) {
1009 try {
1010 r.thread.clearDnsCache();
1011 } catch (RemoteException ex) {
1012 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1013 }
1014 }
1015 }
1016 }
1017 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001018 case UPDATE_HTTP_PROXY: {
1019 ProxyProperties proxy = (ProxyProperties)msg.obj;
1020 String host = "";
1021 String port = "";
1022 String exclList = "";
1023 if (proxy != null) {
1024 host = proxy.getHost();
1025 port = Integer.toString(proxy.getPort());
1026 exclList = proxy.getExclusionList();
1027 }
1028 synchronized (ActivityManagerService.this) {
1029 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1030 ProcessRecord r = mLruProcesses.get(i);
1031 if (r.thread != null) {
1032 try {
1033 r.thread.setHttpProxy(host, port, exclList);
1034 } catch (RemoteException ex) {
1035 Slog.w(TAG, "Failed to update http proxy for: " +
1036 r.info.processName);
1037 }
1038 }
1039 }
1040 }
1041 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001043 String title = "System UIDs Inconsistent";
1044 String text = "UIDs on the system are inconsistent, you need to wipe your"
1045 + " data partition or your device will be unstable.";
1046 Log.e(TAG, title + ": " + text);
1047 if (mShowDialogs) {
1048 // XXX This is a temporary dialog, no need to localize.
1049 AlertDialog d = new BaseErrorDialog(mContext);
1050 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1051 d.setCancelable(false);
1052 d.setTitle(title);
1053 d.setMessage(text);
1054 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1055 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1056 mUidAlert = d;
1057 d.show();
1058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 } break;
1060 case IM_FEELING_LUCKY_MSG: {
1061 if (mUidAlert != null) {
1062 mUidAlert.dismiss();
1063 mUidAlert = null;
1064 }
1065 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001067 if (mDidDexOpt) {
1068 mDidDexOpt = false;
1069 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1070 nmsg.obj = msg.obj;
1071 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1072 return;
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 ProcessRecord app = (ProcessRecord)msg.obj;
1075 synchronized (ActivityManagerService.this) {
1076 processStartTimedOutLocked(app);
1077 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001078 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001079 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1080 synchronized (ActivityManagerService.this) {
1081 doPendingActivityLaunchesLocked(true);
1082 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001083 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001084 case KILL_APPLICATION_MSG: {
1085 synchronized (ActivityManagerService.this) {
1086 int uid = msg.arg1;
1087 boolean restart = (msg.arg2 == 1);
1088 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001089 forceStopPackageLocked(pkg, uid, restart, false, true, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001090 UserHandle.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001091 }
1092 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001093 case FINALIZE_PENDING_INTENT_MSG: {
1094 ((PendingIntentRecord)msg.obj).completeFinalize();
1095 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001096 case POST_HEAVY_NOTIFICATION_MSG: {
1097 INotificationManager inm = NotificationManager.getService();
1098 if (inm == null) {
1099 return;
1100 }
1101
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001102 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001103 ProcessRecord process = root.app;
1104 if (process == null) {
1105 return;
1106 }
1107
1108 try {
1109 Context context = mContext.createPackageContext(process.info.packageName, 0);
1110 String text = mContext.getString(R.string.heavy_weight_notification,
1111 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1112 Notification notification = new Notification();
1113 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1114 notification.when = 0;
1115 notification.flags = Notification.FLAG_ONGOING_EVENT;
1116 notification.tickerText = text;
1117 notification.defaults = 0; // please be quiet
1118 notification.sound = null;
1119 notification.vibrate = null;
1120 notification.setLatestEventInfo(context, text,
1121 mContext.getText(R.string.heavy_weight_notification_detail),
1122 PendingIntent.getActivity(mContext, 0, root.intent,
1123 PendingIntent.FLAG_CANCEL_CURRENT));
1124
1125 try {
1126 int[] outId = new int[1];
1127 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1128 notification, outId);
1129 } catch (RuntimeException e) {
1130 Slog.w(ActivityManagerService.TAG,
1131 "Error showing notification for heavy-weight app", e);
1132 } catch (RemoteException e) {
1133 }
1134 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001135 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001136 }
1137 } break;
1138 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1139 INotificationManager inm = NotificationManager.getService();
1140 if (inm == null) {
1141 return;
1142 }
1143 try {
1144 inm.cancelNotification("android",
1145 R.string.heavy_weight_notification);
1146 } catch (RuntimeException e) {
1147 Slog.w(ActivityManagerService.TAG,
1148 "Error canceling notification for service", e);
1149 } catch (RemoteException e) {
1150 }
1151 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001152 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1153 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001154 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001155 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001156 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1157 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001158 }
1159 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001160 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1161 synchronized (ActivityManagerService.this) {
1162 ActivityRecord ar = (ActivityRecord)msg.obj;
1163 if (mCompatModeDialog != null) {
1164 if (mCompatModeDialog.mAppInfo.packageName.equals(
1165 ar.info.applicationInfo.packageName)) {
1166 return;
1167 }
1168 mCompatModeDialog.dismiss();
1169 mCompatModeDialog = null;
1170 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001171 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001172 if (mCompatModePackages.getPackageAskCompatModeLocked(
1173 ar.packageName)) {
1174 int mode = mCompatModePackages.computeCompatModeLocked(
1175 ar.info.applicationInfo);
1176 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1177 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1178 mCompatModeDialog = new CompatModeDialog(
1179 ActivityManagerService.this, mContext,
1180 ar.info.applicationInfo);
1181 mCompatModeDialog.show();
1182 }
1183 }
1184 }
1185 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001186 break;
1187 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001188 case DISPATCH_PROCESSES_CHANGED: {
1189 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001190 break;
1191 }
1192 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001193 final int pid = msg.arg1;
1194 final int uid = msg.arg2;
1195 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001196 break;
1197 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001198 case REPORT_MEM_USAGE: {
1199 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1200 if (!isDebuggable) {
1201 return;
1202 }
1203 synchronized (ActivityManagerService.this) {
1204 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001205 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1206 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001207 // avoid spamming.
1208 return;
1209 }
1210 mLastMemUsageReportTime = now;
1211 }
1212 Thread thread = new Thread() {
1213 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001214 StringBuilder dropBuilder = new StringBuilder(1024);
1215 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001216 StringWriter oomSw = new StringWriter();
1217 PrintWriter oomPw = new PrintWriter(oomSw);
1218 StringWriter catSw = new StringWriter();
1219 PrintWriter catPw = new PrintWriter(catSw);
1220 String[] emptyArgs = new String[] { };
1221 StringBuilder tag = new StringBuilder(128);
1222 StringBuilder stack = new StringBuilder(128);
1223 tag.append("Low on memory -- ");
1224 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1225 tag, stack);
1226 dropBuilder.append(stack);
1227 dropBuilder.append('\n');
1228 dropBuilder.append('\n');
1229 String oomString = oomSw.toString();
1230 dropBuilder.append(oomString);
1231 dropBuilder.append('\n');
1232 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001233 try {
1234 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1235 "procrank", });
1236 final InputStreamReader converter = new InputStreamReader(
1237 proc.getInputStream());
1238 BufferedReader in = new BufferedReader(converter);
1239 String line;
1240 while (true) {
1241 line = in.readLine();
1242 if (line == null) {
1243 break;
1244 }
1245 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001246 logBuilder.append(line);
1247 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001248 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001249 dropBuilder.append(line);
1250 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001251 }
1252 converter.close();
1253 } catch (IOException e) {
1254 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001255 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001256 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001257 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001258 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001259 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1260 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001261 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001262 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001263 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001264 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001265 addErrorToDropBox("lowmem", null, "system_server", null,
1266 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001267 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001268 synchronized (ActivityManagerService.this) {
1269 long now = SystemClock.uptimeMillis();
1270 if (mLastMemUsageReportTime < now) {
1271 mLastMemUsageReportTime = now;
1272 }
1273 }
1274 }
1275 };
1276 thread.start();
1277 break;
1278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280 }
1281 };
1282
1283 public static void setSystemProcess() {
1284 try {
1285 ActivityManagerService m = mSelf;
1286
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001287 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001289 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001290 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 if (MONITOR_CPU_USAGE) {
1292 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 ServiceManager.addService("permission", new PermissionController(m));
1295
1296 ApplicationInfo info =
1297 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001298 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001299 mSystemThread.installSystemApplicationInfo(info);
1300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 synchronized (mSelf) {
1302 ProcessRecord app = mSelf.newProcessRecordLocked(
1303 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001304 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001306 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001307 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001308 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 synchronized (mSelf.mPidsSelfLocked) {
1310 mSelf.mPidsSelfLocked.put(app.pid, app);
1311 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001312 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 }
1314 } catch (PackageManager.NameNotFoundException e) {
1315 throw new RuntimeException(
1316 "Unable to find android system package", e);
1317 }
1318 }
1319
1320 public void setWindowManager(WindowManagerService wm) {
1321 mWindowManager = wm;
1322 }
1323
1324 public static final Context main(int factoryTest) {
1325 AThread thr = new AThread();
1326 thr.start();
1327
1328 synchronized (thr) {
1329 while (thr.mService == null) {
1330 try {
1331 thr.wait();
1332 } catch (InterruptedException e) {
1333 }
1334 }
1335 }
1336
1337 ActivityManagerService m = thr.mService;
1338 mSelf = m;
1339 ActivityThread at = ActivityThread.systemMain();
1340 mSystemThread = at;
1341 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001342 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 m.mContext = context;
1344 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001345 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346
1347 m.mBatteryStatsService.publish(context);
1348 m.mUsageStatsService.publish(context);
1349
1350 synchronized (thr) {
1351 thr.mReady = true;
1352 thr.notifyAll();
1353 }
1354
1355 m.startRunning(null, null, null, null);
1356
1357 return context;
1358 }
1359
1360 public static ActivityManagerService self() {
1361 return mSelf;
1362 }
1363
1364 static class AThread extends Thread {
1365 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001366 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 boolean mReady = false;
1368
1369 public AThread() {
1370 super("ActivityManager");
1371 }
1372
1373 public void run() {
1374 Looper.prepare();
1375
1376 android.os.Process.setThreadPriority(
1377 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001378 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
1380 ActivityManagerService m = new ActivityManagerService();
1381
1382 synchronized (this) {
1383 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001384 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 notifyAll();
1386 }
1387
1388 synchronized (this) {
1389 while (!mReady) {
1390 try {
1391 wait();
1392 } catch (InterruptedException e) {
1393 }
1394 }
1395 }
1396
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001397 // For debug builds, log event loop stalls to dropbox for analysis.
1398 if (StrictMode.conditionallyEnableDebugLogging()) {
1399 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1400 }
1401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 Looper.loop();
1403 }
1404 }
1405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 static class MemBinder extends Binder {
1407 ActivityManagerService mActivityManagerService;
1408 MemBinder(ActivityManagerService activityManagerService) {
1409 mActivityManagerService = activityManagerService;
1410 }
1411
1412 @Override
1413 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001414 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1415 != PackageManager.PERMISSION_GRANTED) {
1416 pw.println("Permission Denial: can't dump meminfo from from pid="
1417 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1418 + " without permission " + android.Manifest.permission.DUMP);
1419 return;
1420 }
1421
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001422 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001423 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426
Chet Haase9c1e23b2011-03-24 10:51:31 -07001427 static class GraphicsBinder extends Binder {
1428 ActivityManagerService mActivityManagerService;
1429 GraphicsBinder(ActivityManagerService activityManagerService) {
1430 mActivityManagerService = activityManagerService;
1431 }
1432
1433 @Override
1434 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001435 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1436 != PackageManager.PERMISSION_GRANTED) {
1437 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1438 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1439 + " without permission " + android.Manifest.permission.DUMP);
1440 return;
1441 }
1442
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001443 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001444 }
1445 }
1446
Jeff Brown6754ba22011-12-14 20:20:01 -08001447 static class DbBinder extends Binder {
1448 ActivityManagerService mActivityManagerService;
1449 DbBinder(ActivityManagerService activityManagerService) {
1450 mActivityManagerService = activityManagerService;
1451 }
1452
1453 @Override
1454 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1455 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1456 != PackageManager.PERMISSION_GRANTED) {
1457 pw.println("Permission Denial: can't dump dbinfo from from pid="
1458 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1459 + " without permission " + android.Manifest.permission.DUMP);
1460 return;
1461 }
1462
1463 mActivityManagerService.dumpDbInfo(fd, pw, args);
1464 }
1465 }
1466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 static class CpuBinder extends Binder {
1468 ActivityManagerService mActivityManagerService;
1469 CpuBinder(ActivityManagerService activityManagerService) {
1470 mActivityManagerService = activityManagerService;
1471 }
1472
1473 @Override
1474 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001475 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1476 != PackageManager.PERMISSION_GRANTED) {
1477 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1478 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1479 + " without permission " + android.Manifest.permission.DUMP);
1480 return;
1481 }
1482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001484 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1485 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1486 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 }
1489 }
1490
1491 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001492 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001493
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001494 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1495 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1496 mBroadcastQueues[0] = mFgBroadcastQueue;
1497 mBroadcastQueues[1] = mBgBroadcastQueue;
1498
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001499 mServices = new ActiveServices(this);
1500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 File dataDir = Environment.getDataDirectory();
1502 File systemDir = new File(dataDir, "system");
1503 systemDir.mkdirs();
1504 mBatteryStatsService = new BatteryStatsService(new File(
1505 systemDir, "batterystats.bin").toString());
1506 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001507 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001508 mOnBattery = DEBUG_POWER ? true
1509 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001510 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001512 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001513 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001514 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001516 // User 0 is the first and only user that runs at boot.
1517 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
1518
Jack Palevichb90d28c2009-07-22 15:35:24 -07001519 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1520 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1521
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001522 mConfiguration.setToDefaults();
1523 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001524 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 mProcessStats.init();
1526
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001527 mCompatModePackages = new CompatModePackages(this, systemDir);
1528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 // Add ourself to the Watchdog monitors.
1530 Watchdog.getInstance().addMonitor(this);
1531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 mProcessStatsThread = new Thread("ProcessStats") {
1533 public void run() {
1534 while (true) {
1535 try {
1536 try {
1537 synchronized(this) {
1538 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001539 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001541 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 // + ", write delay=" + nextWriteDelay);
1543 if (nextWriteDelay < nextCpuDelay) {
1544 nextCpuDelay = nextWriteDelay;
1545 }
1546 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001547 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 this.wait(nextCpuDelay);
1549 }
1550 }
1551 } catch (InterruptedException e) {
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 updateCpuStatsNow();
1554 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557 }
1558 }
1559 };
1560 mProcessStatsThread.start();
1561 }
1562
1563 @Override
1564 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1565 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001566 if (code == SYSPROPS_TRANSACTION) {
1567 // We need to tell all apps about the system property change.
1568 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1569 synchronized(this) {
1570 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1571 final int NA = apps.size();
1572 for (int ia=0; ia<NA; ia++) {
1573 ProcessRecord app = apps.valueAt(ia);
1574 if (app.thread != null) {
1575 procs.add(app.thread.asBinder());
1576 }
1577 }
1578 }
1579 }
1580
1581 int N = procs.size();
1582 for (int i=0; i<N; i++) {
1583 Parcel data2 = Parcel.obtain();
1584 try {
1585 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1586 } catch (RemoteException e) {
1587 }
1588 data2.recycle();
1589 }
1590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 try {
1592 return super.onTransact(code, data, reply, flags);
1593 } catch (RuntimeException e) {
1594 // The activity manager only throws security exceptions, so let's
1595 // log all others.
1596 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001597 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 throw e;
1600 }
1601 }
1602
1603 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001604 final long now = SystemClock.uptimeMillis();
1605 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1606 return;
1607 }
1608 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1609 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 mProcessStatsThread.notify();
1611 }
1612 }
1613 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 void updateCpuStatsNow() {
1616 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001617 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 final long now = SystemClock.uptimeMillis();
1619 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001622 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1623 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 haveNewCpuStats = true;
1625 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001626 //Slog.i(TAG, mProcessStats.printCurrentState());
1627 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 // + mProcessStats.getTotalCpuPercent() + "%");
1629
Joe Onorato8a9b2202010-02-26 18:56:32 -08001630 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if ("true".equals(SystemProperties.get("events.cpu"))) {
1632 int user = mProcessStats.getLastUserTime();
1633 int system = mProcessStats.getLastSystemTime();
1634 int iowait = mProcessStats.getLastIoWaitTime();
1635 int irq = mProcessStats.getLastIrqTime();
1636 int softIrq = mProcessStats.getLastSoftIrqTime();
1637 int idle = mProcessStats.getLastIdleTime();
1638
1639 int total = user + system + iowait + irq + softIrq + idle;
1640 if (total == 0) total = 1;
1641
Doug Zongker2bec3d42009-12-04 12:52:44 -08001642 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 ((user+system+iowait+irq+softIrq) * 100) / total,
1644 (user * 100) / total,
1645 (system * 100) / total,
1646 (iowait * 100) / total,
1647 (irq * 100) / total,
1648 (softIrq * 100) / total);
1649 }
1650 }
1651
Amith Yamasanie43530a2009-08-21 13:11:37 -07001652 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001653 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001654 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 synchronized(mPidsSelfLocked) {
1656 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001657 if (mOnBattery) {
1658 int perc = bstats.startAddingCpuLocked();
1659 int totalUTime = 0;
1660 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001661 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001663 ProcessStats.Stats st = mProcessStats.getStats(i);
1664 if (!st.working) {
1665 continue;
1666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001668 int otherUTime = (st.rel_utime*perc)/100;
1669 int otherSTime = (st.rel_stime*perc)/100;
1670 totalUTime += otherUTime;
1671 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 if (pr != null) {
1673 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001674 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1675 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001676 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001677 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001678 } else {
1679 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001680 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001681 if (ps != null) {
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);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001688 bstats.finishAddingCpuLocked(perc, totalUTime,
1689 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691 }
1692 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1695 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001696 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699 }
1700 }
1701
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001702 @Override
1703 public void batteryNeedsCpuUpdate() {
1704 updateCpuStatsNow();
1705 }
1706
1707 @Override
1708 public void batteryPowerChanged(boolean onBattery) {
1709 // When plugging in, update the CPU stats first before changing
1710 // the plug state.
1711 updateCpuStatsNow();
1712 synchronized (this) {
1713 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001714 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001715 }
1716 }
1717 }
1718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 /**
1720 * Initialize the application bind args. These are passed to each
1721 * process when the bindApplication() IPC is sent to the process. They're
1722 * lazily setup to make sure the services are running when they're asked for.
1723 */
1724 private HashMap<String, IBinder> getCommonServicesLocked() {
1725 if (mAppBindArgs == null) {
1726 mAppBindArgs = new HashMap<String, IBinder>();
1727
1728 // Setup the application init args
1729 mAppBindArgs.put("package", ServiceManager.getService("package"));
1730 mAppBindArgs.put("window", ServiceManager.getService("window"));
1731 mAppBindArgs.put(Context.ALARM_SERVICE,
1732 ServiceManager.getService(Context.ALARM_SERVICE));
1733 }
1734 return mAppBindArgs;
1735 }
1736
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001737 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (mFocusedActivity != r) {
1739 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001740 if (r != null) {
1741 mWindowManager.setFocusedApp(r.appToken, true);
1742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744 }
1745
Dianne Hackborn906497c2010-05-10 15:57:38 -07001746 private final void updateLruProcessInternalLocked(ProcessRecord app,
1747 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001749 int lrui = mLruProcesses.indexOf(app);
1750 if (lrui >= 0) mLruProcesses.remove(lrui);
1751
1752 int i = mLruProcesses.size()-1;
1753 int skipTop = 0;
1754
Dianne Hackborn906497c2010-05-10 15:57:38 -07001755 app.lruSeq = mLruSeq;
1756
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 // compute the new weight for this process.
1758 if (updateActivityTime) {
1759 app.lastActivityTime = SystemClock.uptimeMillis();
1760 }
1761 if (app.activities.size() > 0) {
1762 // If this process has activities, we more strongly want to keep
1763 // it around.
1764 app.lruWeight = app.lastActivityTime;
1765 } else if (app.pubProviders.size() > 0) {
1766 // If this process contains content providers, we want to keep
1767 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001768 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001769 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001770 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001771 } else {
1772 // If this process doesn't have activities, we less strongly
1773 // want to keep it around, and generally want to avoid getting
1774 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001775 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001776 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001777 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001778 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001779
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001780 while (i >= 0) {
1781 ProcessRecord p = mLruProcesses.get(i);
1782 // If this app shouldn't be in front of the first N background
1783 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001784 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001785 skipTop--;
1786 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001787 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 mLruProcesses.add(i+1, app);
1789 break;
1790 }
1791 i--;
1792 }
1793 if (i < 0) {
1794 mLruProcesses.add(0, app);
1795 }
1796
Dianne Hackborn906497c2010-05-10 15:57:38 -07001797 // If the app is currently using a content provider or service,
1798 // bump those processes as well.
1799 if (app.connections.size() > 0) {
1800 for (ConnectionRecord cr : app.connections) {
1801 if (cr.binding != null && cr.binding.service != null
1802 && cr.binding.service.app != null
1803 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001804 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001805 updateActivityTime, i+1);
1806 }
1807 }
1808 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001809 for (int j=app.conProviders.size()-1; j>=0; j--) {
1810 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1811 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001812 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001813 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001814 }
1815 }
1816
Joe Onorato8a9b2202010-02-26 18:56:32 -08001817 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 if (oomAdj) {
1819 updateOomAdjLocked();
1820 }
1821 }
1822
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001823 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001824 boolean oomAdj, boolean updateActivityTime) {
1825 mLruSeq++;
1826 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1827 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001828
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001829 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001831 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001832 // The system gets to run in any process. If there are multiple
1833 // processes with the same uid, just pick the first (this
1834 // should never happen).
1835 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1836 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001837 if (procs == null) return null;
1838 final int N = procs.size();
1839 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001840 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843 ProcessRecord proc = mProcessNames.get(processName, uid);
1844 return proc;
1845 }
1846
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001847 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001848 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001849 try {
1850 if (pm.performDexOpt(packageName)) {
1851 mDidDexOpt = true;
1852 }
1853 } catch (RemoteException e) {
1854 }
1855 }
1856
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001857 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 int transit = mWindowManager.getPendingAppTransition();
1859 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1860 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1861 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1862 }
1863
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001866 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1867 boolean isolated) {
1868 ProcessRecord app;
1869 if (!isolated) {
1870 app = getProcessRecordLocked(processName, info.uid);
1871 } else {
1872 // If this is an isolated process, it can't re-use an existing process.
1873 app = null;
1874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 // We don't have to do anything more if:
1876 // (1) There is an existing application record; and
1877 // (2) The caller doesn't think it is dead, OR there is no thread
1878 // object attached to it so we know it couldn't have crashed; and
1879 // (3) There is a pid assigned to it, so it is either starting or
1880 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001881 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 + " app=" + app + " knownToBeDead=" + knownToBeDead
1883 + " thread=" + (app != null ? app.thread : null)
1884 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001885 if (app != null && app.pid > 0) {
1886 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001887 // We already have the app running, or are waiting for it to
1888 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001889 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001890 // If this is a new package in the process, add the package to the list
1891 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001892 return app;
1893 } else {
1894 // An application record is attached to a previous process,
1895 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001896 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001897 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 String hostingNameStr = hostingName != null
1902 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001903
1904 if (!isolated) {
1905 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1906 // If we are in the background, then check to see if this process
1907 // is bad. If so, we will just silently fail.
1908 if (mBadProcesses.get(info.processName, info.uid) != null) {
1909 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1910 + "/" + info.processName);
1911 return null;
1912 }
1913 } else {
1914 // When the user is explicitly starting a process, then clear its
1915 // crash count so that we won't make it bad until they see at
1916 // least one crash dialog again, and make the process good again
1917 // if it had been bad.
1918 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001919 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001920 mProcessCrashTimes.remove(info.processName, info.uid);
1921 if (mBadProcesses.get(info.processName, info.uid) != null) {
1922 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1923 info.processName);
1924 mBadProcesses.remove(info.processName, info.uid);
1925 if (app != null) {
1926 app.bad = false;
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929 }
1930 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001933 app = newProcessRecordLocked(null, info, processName, isolated);
1934 if (app == null) {
1935 Slog.w(TAG, "Failed making new process record for "
1936 + processName + "/" + info.uid + " isolated=" + isolated);
1937 return null;
1938 }
1939 mProcessNames.put(processName, app.uid, app);
1940 if (isolated) {
1941 mIsolatedProcesses.put(app.uid, app);
1942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 } else {
1944 // If this is a new package in the process, add the package to the list
1945 app.addPackage(info.packageName);
1946 }
1947
1948 // If the system is not ready yet, then hold off on starting this
1949 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001950 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001951 && !isAllowedWhileBooting(info)
1952 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 if (!mProcessesOnHold.contains(app)) {
1954 mProcessesOnHold.add(app);
1955 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001956 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 return app;
1958 }
1959
1960 startProcessLocked(app, hostingType, hostingNameStr);
1961 return (app.pid != 0) ? app : null;
1962 }
1963
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001964 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1965 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1966 }
1967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 private final void startProcessLocked(ProcessRecord app,
1969 String hostingType, String hostingNameStr) {
1970 if (app.pid > 0 && app.pid != MY_PID) {
1971 synchronized (mPidsSelfLocked) {
1972 mPidsSelfLocked.remove(app.pid);
1973 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1974 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001975 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001978 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1979 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 mProcessesOnHold.remove(app);
1981
1982 updateCpuStats();
1983
1984 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1985 mProcDeaths[0] = 0;
1986
1987 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001988 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07001991 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001992 if (!app.isolated) {
1993 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07001994 final PackageManager pm = mContext.getPackageManager();
1995 gids = pm.getPackageGids(app.info.packageName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 } catch (PackageManager.NameNotFoundException e) {
1997 Slog.w(TAG, "Unable to retrieve gids", e);
1998 }
Jeff Sharkey2bca8682012-08-22 13:59:58 -07001999
2000 if (Environment.isExternalStorageEmulated()) {
2001 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2005 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2006 && mTopComponent != null
2007 && app.processName.equals(mTopComponent.getPackageName())) {
2008 uid = 0;
2009 }
2010 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2011 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2012 uid = 0;
2013 }
2014 }
2015 int debugFlags = 0;
2016 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2017 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002018 // Also turn on CheckJNI for debuggable apps. It's quite
2019 // awkward to turn on otherwise.
2020 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002022 // Run the app in safe mode if its manifest requests so or the
2023 // system is booted in safe mode.
2024 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2025 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002026 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2029 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2030 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002031 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2032 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 if ("1".equals(SystemProperties.get("debug.assert"))) {
2035 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2036 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002037
2038 // Start the process. It will either succeed and return a result containing
2039 // the PID of the new process, or else throw a RuntimeException.
2040 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002041 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002042 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2045 synchronized (bs) {
2046 if (bs.isOnBattery()) {
2047 app.batteryStats.incStartsLocked();
2048 }
2049 }
2050
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 app.processName, hostingType,
2053 hostingNameStr != null ? hostingNameStr : "");
2054
2055 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002056 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002059 StringBuilder buf = mStringBuilder;
2060 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 buf.append("Start proc ");
2062 buf.append(app.processName);
2063 buf.append(" for ");
2064 buf.append(hostingType);
2065 if (hostingNameStr != null) {
2066 buf.append(" ");
2067 buf.append(hostingNameStr);
2068 }
2069 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 buf.append(" uid=");
2072 buf.append(uid);
2073 buf.append(" gids={");
2074 if (gids != null) {
2075 for (int gi=0; gi<gids.length; gi++) {
2076 if (gi != 0) buf.append(", ");
2077 buf.append(gids[gi]);
2078
2079 }
2080 }
2081 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002082 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002083 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002084 app.usingWrapper = startResult.usingWrapper;
2085 app.removed = false;
2086 synchronized (mPidsSelfLocked) {
2087 this.mPidsSelfLocked.put(startResult.pid, app);
2088 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2089 msg.obj = app;
2090 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2091 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093 } catch (RuntimeException e) {
2094 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002095 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (resumed) {
2102 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2103 } else {
2104 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2105 }
2106 }
2107
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002108 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002109 if (mHeadless) {
2110 // Added because none of the other calls to ensureBootCompleted seem to fire
2111 // when running headless.
2112 ensureBootCompleted();
2113 return false;
2114 }
2115
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002116 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2117 && mTopAction == null) {
2118 // We are running in factory test mode, but unable to find
2119 // the factory test app, so just sit around displaying the
2120 // error message and don't try to start anything.
2121 return false;
2122 }
2123 Intent intent = new Intent(
2124 mTopAction,
2125 mTopData != null ? Uri.parse(mTopData) : null);
2126 intent.setComponent(mTopComponent);
2127 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2128 intent.addCategory(Intent.CATEGORY_HOME);
2129 }
2130 ActivityInfo aInfo =
2131 intent.resolveActivityInfo(mContext.getPackageManager(),
2132 STOCK_PM_FLAGS);
2133 if (aInfo != null) {
2134 intent.setComponent(new ComponentName(
2135 aInfo.applicationInfo.packageName, aInfo.name));
2136 // Don't do this if the home app is currently being
2137 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002138 aInfo = new ActivityInfo(aInfo);
2139 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002140 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2141 aInfo.applicationInfo.uid);
2142 if (app == null || app.instrumentationClass == null) {
2143 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002144 mMainStack.startActivityLocked(null, intent, null, aInfo,
2145 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002146 }
2147 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002148 if (startingUser != null) {
2149 mMainStack.addStartingUserLocked(startingUser);
2150 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002151
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 return true;
2153 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002154
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002155 /**
2156 * Starts the "new version setup screen" if appropriate.
2157 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002158 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002159 // Only do this once per boot.
2160 if (mCheckedForSetup) {
2161 return;
2162 }
2163
2164 // We will show this screen if the current one is a different
2165 // version than the last one shown, and we are not running in
2166 // low-level factory test mode.
2167 final ContentResolver resolver = mContext.getContentResolver();
2168 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2169 Settings.Secure.getInt(resolver,
2170 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2171 mCheckedForSetup = true;
2172
2173 // See if we should be showing the platform update setup UI.
2174 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2175 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2176 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2177
2178 // We don't allow third party apps to replace this.
2179 ResolveInfo ri = null;
2180 for (int i=0; ris != null && i<ris.size(); i++) {
2181 if ((ris.get(i).activityInfo.applicationInfo.flags
2182 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2183 ri = ris.get(i);
2184 break;
2185 }
2186 }
2187
2188 if (ri != null) {
2189 String vers = ri.activityInfo.metaData != null
2190 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2191 : null;
2192 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2193 vers = ri.activityInfo.applicationInfo.metaData.getString(
2194 Intent.METADATA_SETUP_VERSION);
2195 }
2196 String lastVers = Settings.Secure.getString(
2197 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2198 if (vers != null && !vers.equals(lastVers)) {
2199 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2200 intent.setComponent(new ComponentName(
2201 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002202 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2203 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002204 }
2205 }
2206 }
2207 }
2208
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002209 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002210 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002211 }
2212
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002213 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002214 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002215 throw new SecurityException("Isolated process not allowed to call " + caller);
2216 }
2217 }
2218
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002219 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002220 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002221 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002222 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2223 }
2224 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002225
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002227 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2228 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002229 synchronized (this) {
2230 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2231 }
2232 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002233
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002234 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002235 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002236 synchronized (this) {
2237 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2238 }
2239 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002240
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002241 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002242 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2243 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002244 synchronized (this) {
2245 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002246 }
2247 }
2248
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002249 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002250 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002251 synchronized (this) {
2252 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2253 }
2254 }
2255
2256 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002257 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2258 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002259 synchronized (this) {
2260 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2261 }
2262 }
2263
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002264 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002265 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002266 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002269 private void dispatchProcessesChanged() {
2270 int N;
2271 synchronized (this) {
2272 N = mPendingProcessChanges.size();
2273 if (mActiveProcessChanges.length < N) {
2274 mActiveProcessChanges = new ProcessChangeItem[N];
2275 }
2276 mPendingProcessChanges.toArray(mActiveProcessChanges);
2277 mAvailProcessChanges.addAll(mPendingProcessChanges);
2278 mPendingProcessChanges.clear();
2279 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2280 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002281 int i = mProcessObservers.beginBroadcast();
2282 while (i > 0) {
2283 i--;
2284 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2285 if (observer != null) {
2286 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002287 for (int j=0; j<N; j++) {
2288 ProcessChangeItem item = mActiveProcessChanges[j];
2289 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2290 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2291 + item.pid + " uid=" + item.uid + ": "
2292 + item.foregroundActivities);
2293 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2294 item.foregroundActivities);
2295 }
2296 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2297 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2298 + item.pid + " uid=" + item.uid + ": " + item.importance);
2299 observer.onImportanceChanged(item.pid, item.uid,
2300 item.importance);
2301 }
2302 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002303 } catch (RemoteException e) {
2304 }
2305 }
2306 }
2307 mProcessObservers.finishBroadcast();
2308 }
2309
2310 private void dispatchProcessDied(int pid, int uid) {
2311 int i = mProcessObservers.beginBroadcast();
2312 while (i > 0) {
2313 i--;
2314 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2315 if (observer != null) {
2316 try {
2317 observer.onProcessDied(pid, uid);
2318 } catch (RemoteException e) {
2319 }
2320 }
2321 }
2322 mProcessObservers.finishBroadcast();
2323 }
2324
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002325 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002326 final int N = mPendingActivityLaunches.size();
2327 if (N <= 0) {
2328 return;
2329 }
2330 for (int i=0; i<N; i++) {
2331 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002332 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002333 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002334 }
2335 mPendingActivityLaunches.clear();
2336 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002337
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002338 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002339 Intent intent, String resolvedType, IBinder resultTo,
2340 String resultWho, int requestCode, int startFlags,
2341 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002342 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002343 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002344 }
2345
2346 public final int startActivityAsUser(IApplicationThread caller,
2347 Intent intent, String resolvedType, IBinder resultTo,
2348 String resultWho, int requestCode, int startFlags,
2349 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002350 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002351 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07002352 // Requesting a different user, make sure that they have the permission
2353 if (checkComponentPermission(
2354 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2355 Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
2356 == PackageManager.PERMISSION_GRANTED) {
2357 // Translate to the current user id, if caller wasn't aware
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002358 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07002359 userId = mCurrentUserId;
2360 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002361 } else {
Amith Yamasani82644082012-08-03 13:09:11 -07002362 String msg = "Permission Denial: "
2363 + "Request to startActivity as user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002364 + " but is calling from user " + UserHandle.getCallingUserId()
Amith Yamasani82644082012-08-03 13:09:11 -07002365 + "; this requires "
2366 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
2367 Slog.w(TAG, msg);
2368 throw new SecurityException(msg);
2369 }
2370 } else {
2371 if (intent.getCategories() != null
2372 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2373 // Requesting home, set the identity to the current user
2374 // HACK!
2375 userId = mCurrentUserId;
2376 } else {
2377 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2378 // the current user's userId
2379 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2380 userId = 0;
2381 } else {
2382 userId = Binder.getOrigCallingUser();
2383 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002384 }
2385 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002386 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002387 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2388 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002389 }
2390
2391 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 Intent intent, String resolvedType, IBinder resultTo,
2393 String resultWho, int requestCode, int startFlags, String profileFile,
2394 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002395 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002396 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002397 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002398 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002399 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2400 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002401 return res;
2402 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002403
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002404 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002405 Intent intent, String resolvedType, IBinder resultTo,
2406 String resultWho, int requestCode, int startFlags, Configuration config,
2407 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002408 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002409 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002410 resultTo, resultWho, requestCode, startFlags,
2411 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002412 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002413 }
2414
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002415 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002416 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002417 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002418 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002419 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002420 // Refuse possible leaked file descriptors
2421 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2422 throw new IllegalArgumentException("File descriptors passed in Intent");
2423 }
2424
2425 IIntentSender sender = intent.getTarget();
2426 if (!(sender instanceof PendingIntentRecord)) {
2427 throw new IllegalArgumentException("Bad PendingIntent object");
2428 }
2429
2430 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002431
2432 synchronized (this) {
2433 // If this is coming from the currently resumed activity, it is
2434 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 if (mMainStack.mResumedActivity != null
2436 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002437 Binder.getCallingUid()) {
2438 mAppSwitchesAllowedTime = 0;
2439 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002440 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002441 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2442 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002443 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002444 }
2445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002447 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 // Refuse possible leaked file descriptors
2449 if (intent != null && intent.hasFileDescriptors() == true) {
2450 throw new IllegalArgumentException("File descriptors passed in Intent");
2451 }
2452
2453 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002454 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2455 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002456 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 return false;
2458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 if (r.app == null || r.app.thread == null) {
2460 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002461 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 return false;
2463 }
2464 intent = new Intent(intent);
2465 // The caller is not allowed to change the data.
2466 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2467 // And we are resetting to find the next component...
2468 intent.setComponent(null);
2469
2470 ActivityInfo aInfo = null;
2471 try {
2472 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002473 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002475 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002476 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477
2478 // Look for the original activity in the list...
2479 final int N = resolves != null ? resolves.size() : 0;
2480 for (int i=0; i<N; i++) {
2481 ResolveInfo rInfo = resolves.get(i);
2482 if (rInfo.activityInfo.packageName.equals(r.packageName)
2483 && rInfo.activityInfo.name.equals(r.info.name)) {
2484 // We found the current one... the next matching is
2485 // after it.
2486 i++;
2487 if (i<N) {
2488 aInfo = resolves.get(i).activityInfo;
2489 }
2490 break;
2491 }
2492 }
2493 } catch (RemoteException e) {
2494 }
2495
2496 if (aInfo == null) {
2497 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002498 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 return false;
2500 }
2501
2502 intent.setComponent(new ComponentName(
2503 aInfo.applicationInfo.packageName, aInfo.name));
2504 intent.setFlags(intent.getFlags()&~(
2505 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2506 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2507 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2508 Intent.FLAG_ACTIVITY_NEW_TASK));
2509
2510 // Okay now we need to start the new activity, replacing the
2511 // currently running activity. This is a little tricky because
2512 // we want to start the new one as if the current one is finished,
2513 // but not finish the current one first so that there is no flicker.
2514 // And thus...
2515 final boolean wasFinishing = r.finishing;
2516 r.finishing = true;
2517
2518 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002519 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 final String resultWho = r.resultWho;
2521 final int requestCode = r.requestCode;
2522 r.resultTo = null;
2523 if (resultTo != null) {
2524 resultTo.removeResultsLocked(r, resultWho, requestCode);
2525 }
2526
2527 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002528 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002529 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2530 resultWho, requestCode, -1, r.launchedFromUid, 0,
2531 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 Binder.restoreCallingIdentity(origId);
2533
2534 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002535 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 return false;
2537 }
2538 return true;
2539 }
2540 }
2541
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002542 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002544 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002545
2546 // This is so super not safe, that only the system (or okay root)
2547 // can do it.
2548 final int callingUid = Binder.getCallingUid();
2549 if (callingUid != 0 && callingUid != Process.myUid()) {
2550 throw new SecurityException(
2551 "startActivityInPackage only available to the system");
2552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553
Amith Yamasani742a6712011-05-04 14:49:28 -07002554 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002555 resultTo, resultWho, requestCode, startFlags,
Amith Yamasani7300dbe2012-08-17 14:17:57 -07002556 null, null, null, null, options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002557 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002558 }
2559
2560 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002561 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002562 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002563 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002565 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002566 }
2567
2568 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002569 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2570 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002571
2572 // This is so super not safe, that only the system (or okay root)
2573 // can do it.
2574 final int callingUid = Binder.getCallingUid();
2575 if (callingUid != 0 && callingUid != Process.myUid()) {
2576 throw new SecurityException(
2577 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002579 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002580 options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002581 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 }
2583
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002584 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002586 // Quick case: check if the top-most recent task is the same.
2587 if (N > 0 && mRecentTasks.get(0) == task) {
2588 return;
2589 }
2590 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 for (int i=0; i<N; i++) {
2592 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002593 if (task.userId == tr.userId
2594 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2595 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 mRecentTasks.remove(i);
2597 i--;
2598 N--;
2599 if (task.intent == null) {
2600 // If the new recent task we are adding is not fully
2601 // specified, then replace it with the existing recent task.
2602 task = tr;
2603 }
2604 }
2605 }
2606 if (N >= MAX_RECENT_TASKS) {
2607 mRecentTasks.remove(N-1);
2608 }
2609 mRecentTasks.add(0, task);
2610 }
2611
2612 public void setRequestedOrientation(IBinder token,
2613 int requestedOrientation) {
2614 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002615 ActivityRecord r = mMainStack.isInStackLocked(token);
2616 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 return;
2618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002620 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002622 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002623 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 if (config != null) {
2625 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002626 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002627 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629 }
2630 Binder.restoreCallingIdentity(origId);
2631 }
2632 }
2633
2634 public int getRequestedOrientation(IBinder token) {
2635 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002636 ActivityRecord r = mMainStack.isInStackLocked(token);
2637 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2639 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002640 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
2642 }
2643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 /**
2645 * This is the internal entry point for handling Activity.finish().
2646 *
2647 * @param token The Binder token referencing the Activity we want to finish.
2648 * @param resultCode Result code, if any, from this Activity.
2649 * @param resultData Result data (Intent), if any, from this Activity.
2650 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002651 * @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 -08002652 */
2653 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2654 // Refuse possible leaked file descriptors
2655 if (resultData != null && resultData.hasFileDescriptors() == true) {
2656 throw new IllegalArgumentException("File descriptors passed in Intent");
2657 }
2658
2659 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002660 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002662 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 if (next != null) {
2664 // ask watcher if this is allowed
2665 boolean resumeOK = true;
2666 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002667 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002669 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 }
2671
2672 if (!resumeOK) {
2673 return false;
2674 }
2675 }
2676 }
2677 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002678 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 resultData, "app-request");
2680 Binder.restoreCallingIdentity(origId);
2681 return res;
2682 }
2683 }
2684
Dianne Hackborn860755f2010-06-03 18:47:52 -07002685 public final void finishHeavyWeightApp() {
2686 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2687 != PackageManager.PERMISSION_GRANTED) {
2688 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2689 + Binder.getCallingPid()
2690 + ", uid=" + Binder.getCallingUid()
2691 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2692 Slog.w(TAG, msg);
2693 throw new SecurityException(msg);
2694 }
2695
2696 synchronized(this) {
2697 if (mHeavyWeightProcess == null) {
2698 return;
2699 }
2700
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002701 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002702 mHeavyWeightProcess.activities);
2703 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002704 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002705 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002706 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002707 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002709 null, "finish-heavy");
2710 }
2711 }
2712 }
2713
2714 mHeavyWeightProcess = null;
2715 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2716 }
2717 }
2718
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002719 public void crashApplication(int uid, int initialPid, String packageName,
2720 String message) {
2721 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2722 != PackageManager.PERMISSION_GRANTED) {
2723 String msg = "Permission Denial: crashApplication() from pid="
2724 + Binder.getCallingPid()
2725 + ", uid=" + Binder.getCallingUid()
2726 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2727 Slog.w(TAG, msg);
2728 throw new SecurityException(msg);
2729 }
2730
2731 synchronized(this) {
2732 ProcessRecord proc = null;
2733
2734 // Figure out which process to kill. We don't trust that initialPid
2735 // still has any relation to current pids, so must scan through the
2736 // list.
2737 synchronized (mPidsSelfLocked) {
2738 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2739 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002740 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002741 continue;
2742 }
2743 if (p.pid == initialPid) {
2744 proc = p;
2745 break;
2746 }
2747 for (String str : p.pkgList) {
2748 if (str.equals(packageName)) {
2749 proc = p;
2750 }
2751 }
2752 }
2753 }
2754
2755 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002756 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002757 + " initialPid=" + initialPid
2758 + " packageName=" + packageName);
2759 return;
2760 }
2761
2762 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002763 if (proc.pid == Process.myPid()) {
2764 Log.w(TAG, "crashApplication: trying to crash self!");
2765 return;
2766 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002767 long ident = Binder.clearCallingIdentity();
2768 try {
2769 proc.thread.scheduleCrash(message);
2770 } catch (RemoteException e) {
2771 }
2772 Binder.restoreCallingIdentity(ident);
2773 }
2774 }
2775 }
2776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 public final void finishSubActivity(IBinder token, String resultWho,
2778 int requestCode) {
2779 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002781 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 Binder.restoreCallingIdentity(origId);
2783 }
2784 }
2785
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002786 public boolean finishActivityAffinity(IBinder token) {
2787 synchronized(this) {
2788 final long origId = Binder.clearCallingIdentity();
2789 boolean res = mMainStack.finishActivityAffinityLocked(token);
2790 Binder.restoreCallingIdentity(origId);
2791 return res;
2792 }
2793 }
2794
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002795 public boolean willActivityBeVisible(IBinder token) {
2796 synchronized(this) {
2797 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2799 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002800 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002801 return true;
2802 }
2803 if (r.fullscreen && !r.finishing) {
2804 return false;
2805 }
2806 }
2807 return true;
2808 }
2809 }
2810
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002811 public void overridePendingTransition(IBinder token, String packageName,
2812 int enterAnim, int exitAnim) {
2813 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002814 ActivityRecord self = mMainStack.isInStackLocked(token);
2815 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002816 return;
2817 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002818
2819 final long origId = Binder.clearCallingIdentity();
2820
2821 if (self.state == ActivityState.RESUMED
2822 || self.state == ActivityState.PAUSING) {
2823 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002824 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002825 }
2826
2827 Binder.restoreCallingIdentity(origId);
2828 }
2829 }
2830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 * Main function for removing an existing process from the activity manager
2833 * as a result of that process going away. Clears out all connections
2834 * to the process.
2835 */
2836 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002837 boolean restarting, boolean allowRestart) {
2838 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002840 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002843 if (mProfileProc == app) {
2844 clearProfilerLocked();
2845 }
2846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002848 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2849 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2850 mMainStack.mPausingActivity = null;
2851 }
2852 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2853 mMainStack.mLastPausedActivity = null;
2854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855
2856 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858
2859 boolean atTop = true;
2860 boolean hasVisibleActivities = false;
2861
2862 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002863 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002864 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 TAG, "Removing app " + app + " from history with " + i + " entries");
2866 while (i > 0) {
2867 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002869 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2871 if (r.app == app) {
2872 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002873 if (ActivityStack.DEBUG_ADD_REMOVE) {
2874 RuntimeException here = new RuntimeException("here");
2875 here.fillInStackTrace();
2876 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2877 + ": haveState=" + r.haveState
2878 + " stateNotNeeded=" + r.stateNotNeeded
2879 + " finishing=" + r.finishing
2880 + " state=" + r.state, here);
2881 }
2882 if (!r.finishing) {
2883 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002884 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2885 System.identityHashCode(r),
2886 r.task.taskId, r.shortComponentName,
2887 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002888 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002889 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890
2891 } else {
2892 // We have the current state for this activity, so
2893 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002894 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 TAG, "Keeping entry, setting app to null");
2896 if (r.visible) {
2897 hasVisibleActivities = true;
2898 }
2899 r.app = null;
2900 r.nowVisible = false;
2901 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002902 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2903 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 r.icicle = null;
2905 }
2906 }
2907
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002908 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
2910 atTop = false;
2911 }
2912
2913 app.activities.clear();
2914
2915 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002916 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 + " running instrumentation " + app.instrumentationClass);
2918 Bundle info = new Bundle();
2919 info.putString("shortMsg", "Process crashed.");
2920 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2921 }
2922
2923 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002924 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 // If there was nothing to resume, and we are not already
2926 // restarting this process, but there is a visible activity that
2927 // is hosted by the process... then make sure all visible
2928 // activities are running, taking care of restarting this
2929 // process.
2930 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002931 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
2933 }
2934 }
2935 }
2936
2937 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2938 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002940 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2941 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2943 return i;
2944 }
2945 }
2946 return -1;
2947 }
2948
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002949 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 IApplicationThread thread) {
2951 if (thread == null) {
2952 return null;
2953 }
2954
2955 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002956 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002959 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 IApplicationThread thread) {
2961
2962 mProcDeaths[0]++;
2963
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002964 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2965 synchronized (stats) {
2966 stats.noteProcessDiedLocked(app.info.uid, pid);
2967 }
2968
Magnus Edlund7bb25812010-02-24 15:45:06 +01002969 // Clean up already done if the process has been re-started.
2970 if (app.pid == pid && app.thread != null &&
2971 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002972 if (!app.killedBackground) {
2973 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2974 + ") has died.");
2975 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002976 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002977 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 TAG, "Dying app: " + app + ", pid: " + pid
2979 + ", thread: " + thread.asBinder());
2980 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002981 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982
2983 if (doLowMem) {
2984 // If there are no longer any background processes running,
2985 // and the app that died was not running instrumentation,
2986 // then tell everyone we are now low on memory.
2987 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002988 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2989 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002990 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 haveBg = true;
2992 break;
2993 }
2994 }
2995
2996 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002997 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002998 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002999 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3000 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003001 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003002 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3003 // The low memory report is overriding any current
3004 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003005 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003006 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003007 rec.lastRequestedGc = 0;
3008 } else {
3009 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003011 rec.reportLowMemory = true;
3012 rec.lastLowMemory = now;
3013 mProcessesToGc.remove(rec);
3014 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 }
3016 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003017 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003018 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 }
3020 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003021 } else if (app.pid != pid) {
3022 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003023 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003024 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003025 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003026 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003027 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 + thread.asBinder());
3029 }
3030 }
3031
Dan Egnor42471dd2010-01-07 17:25:22 -08003032 /**
3033 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003034 * @param clearTraces causes the dump file to be erased prior to the new
3035 * traces being written, if true; when false, the new traces will be
3036 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003037 * @param firstPids of dalvik VM processes to dump stack traces for first
3038 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003039 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003040 * @return file containing stack traces, or null if no dump file is configured
3041 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003042 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003043 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003044 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3045 if (tracesPath == null || tracesPath.length() == 0) {
3046 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003048
3049 File tracesFile = new File(tracesPath);
3050 try {
3051 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003052 if (!tracesDir.exists()) {
3053 tracesFile.mkdirs();
3054 if (!SELinux.restorecon(tracesDir)) {
3055 return null;
3056 }
3057 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003058 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3059
Christopher Tate6ee412d2010-05-28 12:01:56 -07003060 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003061 tracesFile.createNewFile();
3062 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3063 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003064 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003065 return null;
3066 }
3067
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003068 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003069 return tracesFile;
3070 }
3071
3072 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003073 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003074 // Use a FileObserver to detect when traces finish writing.
3075 // The order of traces is considered important to maintain for legibility.
3076 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3077 public synchronized void onEvent(int event, String path) { notify(); }
3078 };
3079
3080 try {
3081 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003082
3083 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003084 if (firstPids != null) {
3085 try {
3086 int num = firstPids.size();
3087 for (int i = 0; i < num; i++) {
3088 synchronized (observer) {
3089 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3090 observer.wait(200); // Wait for write-close, give up after 200msec
3091 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003092 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003093 } catch (InterruptedException e) {
3094 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003095 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003096 }
3097
3098 // Next measure CPU usage.
3099 if (processStats != null) {
3100 processStats.init();
3101 System.gc();
3102 processStats.update();
3103 try {
3104 synchronized (processStats) {
3105 processStats.wait(500); // measure over 1/2 second.
3106 }
3107 } catch (InterruptedException e) {
3108 }
3109 processStats.update();
3110
3111 // We'll take the stack crawls of just the top apps using CPU.
3112 final int N = processStats.countWorkingStats();
3113 int numProcs = 0;
3114 for (int i=0; i<N && numProcs<5; i++) {
3115 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3116 if (lastPids.indexOfKey(stats.pid) >= 0) {
3117 numProcs++;
3118 try {
3119 synchronized (observer) {
3120 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3121 observer.wait(200); // Wait for write-close, give up after 200msec
3122 }
3123 } catch (InterruptedException e) {
3124 Log.wtf(TAG, e);
3125 }
3126
3127 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003128 }
3129 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003130
Dan Egnor42471dd2010-01-07 17:25:22 -08003131 } finally {
3132 observer.stopWatching();
3133 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003134
3135 if (nativeProcs != null) {
3136 int[] pids = Process.getPidsForCommands(nativeProcs);
3137 if (pids != null) {
3138 for (int pid : pids) {
3139 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3140 }
3141 }
3142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 }
3144
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003145 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003146 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003147 return;
3148 }
3149 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3150 if (tracesPath == null || tracesPath.length() == 0) {
3151 return;
3152 }
3153
3154 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3155 StrictMode.allowThreadDiskWrites();
3156 try {
3157 final File tracesFile = new File(tracesPath);
3158 final File tracesDir = tracesFile.getParentFile();
3159 final File tracesTmp = new File(tracesDir, "__tmp__");
3160 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003161 if (!tracesDir.exists()) {
3162 tracesFile.mkdirs();
3163 if (!SELinux.restorecon(tracesDir.getPath())) {
3164 return;
3165 }
3166 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003167 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3168
3169 if (tracesFile.exists()) {
3170 tracesTmp.delete();
3171 tracesFile.renameTo(tracesTmp);
3172 }
3173 StringBuilder sb = new StringBuilder();
3174 Time tobj = new Time();
3175 tobj.set(System.currentTimeMillis());
3176 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3177 sb.append(": ");
3178 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3179 sb.append(" since ");
3180 sb.append(msg);
3181 FileOutputStream fos = new FileOutputStream(tracesFile);
3182 fos.write(sb.toString().getBytes());
3183 if (app == null) {
3184 fos.write("\n*** No application process!".getBytes());
3185 }
3186 fos.close();
3187 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3188 } catch (IOException e) {
3189 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3190 return;
3191 }
3192
3193 if (app != null) {
3194 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3195 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003196 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003197 }
3198
3199 File lastTracesFile = null;
3200 File curTracesFile = null;
3201 for (int i=9; i>=0; i--) {
3202 String name = String.format("slow%02d.txt", i);
3203 curTracesFile = new File(tracesDir, name);
3204 if (curTracesFile.exists()) {
3205 if (lastTracesFile != null) {
3206 curTracesFile.renameTo(lastTracesFile);
3207 } else {
3208 curTracesFile.delete();
3209 }
3210 }
3211 lastTracesFile = curTracesFile;
3212 }
3213 tracesFile.renameTo(curTracesFile);
3214 if (tracesTmp.exists()) {
3215 tracesTmp.renameTo(tracesFile);
3216 }
3217 } finally {
3218 StrictMode.setThreadPolicy(oldPolicy);
3219 }
3220 }
3221
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003222 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3223 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003224 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3225 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3226
Dianne Hackborn287952c2010-09-22 22:34:31 -07003227 if (mController != null) {
3228 try {
3229 // 0 == continue, -1 = kill process immediately
3230 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3231 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3232 } catch (RemoteException e) {
3233 mController = null;
3234 }
3235 }
3236
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003237 long anrTime = SystemClock.uptimeMillis();
3238 if (MONITOR_CPU_USAGE) {
3239 updateCpuStatsNow();
3240 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003241
3242 synchronized (this) {
3243 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3244 if (mShuttingDown) {
3245 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3246 return;
3247 } else if (app.notResponding) {
3248 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3249 return;
3250 } else if (app.crashing) {
3251 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3252 return;
3253 }
3254
3255 // In case we come through here for the same app before completing
3256 // this one, mark as anring now so we will bail out.
3257 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003258
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003259 // Log the ANR to the event log.
3260 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3261 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003262
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003263 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003264 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003265
3266 int parentPid = app.pid;
3267 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003268 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003269
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003270 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003271
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003272 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3273 ProcessRecord r = mLruProcesses.get(i);
3274 if (r != null && r.thread != null) {
3275 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003276 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3277 if (r.persistent) {
3278 firstPids.add(pid);
3279 } else {
3280 lastPids.put(pid, Boolean.TRUE);
3281 }
3282 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
3285 }
3286
Dan Egnor42471dd2010-01-07 17:25:22 -08003287 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003288 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003289 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003290 info.append("ANR in ").append(app.processName);
3291 if (activity != null && activity.shortComponentName != null) {
3292 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003293 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003294 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003296 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003298 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003299 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301
Dianne Hackborn287952c2010-09-22 22:34:31 -07003302 final ProcessStats processStats = new ProcessStats(true);
3303
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003304 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003305
Dan Egnor42471dd2010-01-07 17:25:22 -08003306 String cpuInfo = null;
3307 if (MONITOR_CPU_USAGE) {
3308 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003309 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003310 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003311 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003312 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003313 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 }
3315
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003316 info.append(processStats.printCurrentState(anrTime));
3317
Joe Onorato8a9b2202010-02-26 18:56:32 -08003318 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003319 if (tracesFile == null) {
3320 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3321 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3322 }
3323
Jeff Sharkeya353d262011-10-28 11:12:06 -07003324 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3325 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003326
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003327 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003329 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3330 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003332 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3333 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003336 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 }
3338 }
3339
Dan Egnor42471dd2010-01-07 17:25:22 -08003340 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3341 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3342 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003343
3344 synchronized (this) {
3345 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003346 Slog.w(TAG, "Killing " + app + ": background ANR");
3347 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3348 app.processName, app.setAdj, "background ANR");
3349 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003350 return;
3351 }
3352
3353 // Set the app's notResponding state, and look up the errorReportReceiver
3354 makeAppNotRespondingLocked(app,
3355 activity != null ? activity.shortComponentName : null,
3356 annotation != null ? "ANR " + annotation : "ANR",
3357 info.toString());
3358
3359 // Bring up the infamous App Not Responding dialog
3360 Message msg = Message.obtain();
3361 HashMap map = new HashMap();
3362 msg.what = SHOW_NOT_RESPONDING_MSG;
3363 msg.obj = map;
3364 map.put("app", app);
3365 if (activity != null) {
3366 map.put("activity", activity);
3367 }
3368
3369 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
3372
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003373 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3374 if (!mLaunchWarningShown) {
3375 mLaunchWarningShown = true;
3376 mHandler.post(new Runnable() {
3377 @Override
3378 public void run() {
3379 synchronized (ActivityManagerService.this) {
3380 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3381 d.show();
3382 mHandler.postDelayed(new Runnable() {
3383 @Override
3384 public void run() {
3385 synchronized (ActivityManagerService.this) {
3386 d.dismiss();
3387 mLaunchWarningShown = false;
3388 }
3389 }
3390 }, 4000);
3391 }
3392 }
3393 });
3394 }
3395 }
3396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003398 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003399 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 int uid = Binder.getCallingUid();
3401 int pid = Binder.getCallingPid();
3402 long callingId = Binder.clearCallingIdentity();
3403 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003404 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 int pkgUid = -1;
3406 synchronized(this) {
3407 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003408 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 } catch (RemoteException e) {
3410 }
3411 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003412 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 return false;
3414 }
3415 if (uid == pkgUid || checkComponentPermission(
3416 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003417 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003419 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 } else {
3421 throw new SecurityException(pid+" does not have permission:"+
3422 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3423 "for process:"+packageName);
3424 }
3425 }
3426
3427 try {
3428 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003429 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3431 Uri.fromParts("package", packageName, null));
3432 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003433 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003434 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 } catch (RemoteException e) {
3436 }
3437 } finally {
3438 Binder.restoreCallingIdentity(callingId);
3439 }
3440 return true;
3441 }
3442
Dianne Hackborn03abb812010-01-04 18:43:19 -08003443 public void killBackgroundProcesses(final String packageName) {
3444 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3445 != PackageManager.PERMISSION_GRANTED &&
3446 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3447 != PackageManager.PERMISSION_GRANTED) {
3448 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 + Binder.getCallingPid()
3450 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003451 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003452 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 throw new SecurityException(msg);
3454 }
3455
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003456 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 long callingId = Binder.clearCallingIdentity();
3458 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003459 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 int pkgUid = -1;
3461 synchronized(this) {
3462 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003463 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464 } catch (RemoteException e) {
3465 }
3466 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003467 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 return;
3469 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003470 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003471 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3472 }
3473 } finally {
3474 Binder.restoreCallingIdentity(callingId);
3475 }
3476 }
3477
3478 public void killAllBackgroundProcesses() {
3479 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3480 != PackageManager.PERMISSION_GRANTED) {
3481 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3482 + Binder.getCallingPid()
3483 + ", uid=" + Binder.getCallingUid()
3484 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3485 Slog.w(TAG, msg);
3486 throw new SecurityException(msg);
3487 }
3488
3489 long callingId = Binder.clearCallingIdentity();
3490 try {
3491 synchronized(this) {
3492 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3493 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3494 final int NA = apps.size();
3495 for (int ia=0; ia<NA; ia++) {
3496 ProcessRecord app = apps.valueAt(ia);
3497 if (app.persistent) {
3498 // we don't kill persistent processes
3499 continue;
3500 }
3501 if (app.removed) {
3502 procs.add(app);
3503 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3504 app.removed = true;
3505 procs.add(app);
3506 }
3507 }
3508 }
3509
3510 int N = procs.size();
3511 for (int i=0; i<N; i++) {
3512 removeProcessLocked(procs.get(i), false, true, "kill all background");
3513 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003514 }
3515 } finally {
3516 Binder.restoreCallingIdentity(callingId);
3517 }
3518 }
3519
3520 public void forceStopPackage(final String packageName) {
3521 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3522 != PackageManager.PERMISSION_GRANTED) {
3523 String msg = "Permission Denial: forceStopPackage() from pid="
3524 + Binder.getCallingPid()
3525 + ", uid=" + Binder.getCallingUid()
3526 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003527 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003528 throw new SecurityException(msg);
3529 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003530 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003531 long callingId = Binder.clearCallingIdentity();
3532 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003533 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003534 int pkgUid = -1;
3535 synchronized(this) {
3536 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003537 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003538 } catch (RemoteException e) {
3539 }
3540 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003541 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003542 return;
3543 }
3544 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003545 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003546 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003547 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003548 } catch (IllegalArgumentException e) {
3549 Slog.w(TAG, "Failed trying to unstop package "
3550 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 }
3553 } finally {
3554 Binder.restoreCallingIdentity(callingId);
3555 }
3556 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003557
3558 /*
3559 * The pkg name and uid have to be specified.
3560 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3561 */
3562 public void killApplicationWithUid(String pkg, int uid) {
3563 if (pkg == null) {
3564 return;
3565 }
3566 // Make sure the uid is valid.
3567 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003568 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003569 return;
3570 }
3571 int callerUid = Binder.getCallingUid();
3572 // Only the system server can kill an application
3573 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003574 // Post an aysnc message to kill the application
3575 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3576 msg.arg1 = uid;
3577 msg.arg2 = 0;
3578 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003579 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003580 } else {
3581 throw new SecurityException(callerUid + " cannot kill pkg: " +
3582 pkg);
3583 }
3584 }
3585
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003586 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003587 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003588
3589 final int uid = Binder.getCallingUid();
3590 final long origId = Binder.clearCallingIdentity();
3591 synchronized (this) {
3592 closeSystemDialogsLocked(uid, reason);
3593 }
3594 Binder.restoreCallingIdentity(origId);
3595 }
3596
3597 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003598 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003599 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003600 if (reason != null) {
3601 intent.putExtra("reason", reason);
3602 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003603 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003604
Dianne Hackborne302a162012-05-15 14:58:32 -07003605 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3606 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003607 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003608 r.stack.finishActivityLocked(r, i,
3609 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003610 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003611 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003612
3613 broadcastIntentLocked(null, null, intent, null,
3614 null, 0, null, null, null, false, false, -1,
3615 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003616 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003617
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003618 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003619 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003620 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003621 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3622 for (int i=pids.length-1; i>=0; i--) {
3623 infos[i] = new Debug.MemoryInfo();
3624 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003625 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003626 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003627 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003628
Dianne Hackbornb437e092011-08-05 17:50:29 -07003629 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003630 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003631 long[] pss = new long[pids.length];
3632 for (int i=pids.length-1; i>=0; i--) {
3633 pss[i] = Debug.getPss(pids[i]);
3634 }
3635 return pss;
3636 }
3637
Christopher Tate5e1ab332009-09-01 20:32:49 -07003638 public void killApplicationProcess(String processName, int uid) {
3639 if (processName == null) {
3640 return;
3641 }
3642
3643 int callerUid = Binder.getCallingUid();
3644 // Only the system server can kill an application
3645 if (callerUid == Process.SYSTEM_UID) {
3646 synchronized (this) {
3647 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003648 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003649 try {
3650 app.thread.scheduleSuicide();
3651 } catch (RemoteException e) {
3652 // If the other end already died, then our work here is done.
3653 }
3654 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003655 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003656 + processName + " / " + uid);
3657 }
3658 }
3659 } else {
3660 throw new SecurityException(callerUid + " cannot kill app process: " +
3661 processName);
3662 }
3663 }
3664
Dianne Hackborn03abb812010-01-04 18:43:19 -08003665 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003666 forceStopPackageLocked(packageName, uid, false, false, true, false,
3667 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3669 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003670 if (!mProcessesReady) {
3671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 intent.putExtra(Intent.EXTRA_UID, uid);
3674 broadcastIntentLocked(null, null, intent,
3675 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003676 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003677 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003679
3680 private void forceStopUserLocked(int userId) {
3681 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3682 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3683 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3684 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3685 broadcastIntentLocked(null, null, intent,
3686 null, null, 0, null, null, null,
3687 false, false,
3688 MY_PID, Process.SYSTEM_UID, userId);
3689 }
3690
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003691 private final boolean killPackageProcessesLocked(String packageName, int uid,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003692 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3693 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003694 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695
Dianne Hackborn03abb812010-01-04 18:43:19 -08003696 // Remove all processes this package may have touched: all with the
3697 // same UID (except for the system or root user), and all whose name
3698 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003699 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003700 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3701 final int NA = apps.size();
3702 for (int ia=0; ia<NA; ia++) {
3703 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003704 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003705 // we don't kill persistent processes
3706 continue;
3707 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003708 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003709 if (doit) {
3710 procs.add(app);
3711 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003712 // If no package is specified, we call all processes under the
3713 // give user id.
3714 } else if (packageName == null) {
3715 if (app.userId == userId) {
3716 if (app.setAdj >= minOomAdj) {
3717 if (!doit) {
3718 return true;
3719 }
3720 app.removed = true;
3721 procs.add(app);
3722 }
3723 }
Amith Yamasani13593602012-03-22 16:16:17 -07003724 // If uid is specified and the uid and process name match
3725 // Or, the uid is not specified and the process name matches
3726 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003727 || ((app.processName.equals(packageName)
3728 || app.processName.startsWith(procNamePrefix))
3729 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003730 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003731 if (!doit) {
3732 return true;
3733 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003734 app.removed = true;
3735 procs.add(app);
3736 }
3737 }
3738 }
3739 }
3740
3741 int N = procs.size();
3742 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003743 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003744 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003745 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003746 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003747
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003748 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003749 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003750 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003751 int i;
3752 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003754 if (uid < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003756 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 } catch (RemoteException e) {
3758 }
3759 }
3760
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003761 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003762 if (name != null) {
3763 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
3764 } else {
3765 Slog.i(TAG, "Force stopping user " + userId);
3766 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003767
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003768 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3769 while (badApps.hasNext()) {
3770 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003771 for (i=ba.size()-1; i>=0; i--) {
3772 boolean remove = false;
3773 final int entUid = ba.keyAt(i);
3774 if (name != null) {
3775 if (entUid == uid) {
3776 remove = true;
3777 }
3778 } else if (UserHandle.getUserId(entUid) == userId) {
3779 remove = true;
3780 }
3781 if (remove) {
3782 ba.removeAt(i);
3783 }
3784 }
3785 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003786 badApps.remove();
3787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 }
3789 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003790
3791 boolean didSomething = killPackageProcessesLocked(name, uid,
3792 name == null ? userId : -1 , -100, callerWillRestart, false,
3793 doit, evenPersistent,
3794 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003796 TaskRecord lastTask = null;
3797 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003798 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003799 final boolean samePackage = r.packageName.equals(name)
3800 || (name == null && r.userId == userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003801 if (r.userId == userId
3802 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003803 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003804 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003805 if (r.finishing) {
3806 // If this activity is just finishing, then it is not
3807 // interesting as far as something to stop.
3808 continue;
3809 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003810 return true;
3811 }
3812 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003813 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003814 if (samePackage) {
3815 if (r.app != null) {
3816 r.app.removed = true;
3817 }
3818 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003820 lastTask = r.task;
3821 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003822 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003823 i--;
3824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826 }
3827
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003828 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3829 if (!doit) {
3830 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003832 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003834
3835 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003836 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003837 if ((name == null || provider.info.packageName.equals(name))
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003838 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3839 if (!doit) {
3840 return true;
3841 }
3842 didSomething = true;
3843 providers.add(provider);
3844 }
3845 }
3846
3847 N = providers.size();
3848 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003849 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003850 }
3851
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003852 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003853 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003854 AttributeCache ac = AttributeCache.instance();
3855 if (ac != null) {
3856 ac.removePackage(name);
3857 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003858 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003859 if (mBooted) {
3860 mMainStack.resumeTopActivityLocked(null);
3861 mMainStack.scheduleIdleLocked();
3862 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003863 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003864
3865 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003868 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003869 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003871 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003872 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003873 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 + "/" + uid + ")");
3875
3876 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003877 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003878 if (mHeavyWeightProcess == app) {
3879 mHeavyWeightProcess = null;
3880 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 boolean needRestart = false;
3883 if (app.pid > 0 && app.pid != MY_PID) {
3884 int pid = app.pid;
3885 synchronized (mPidsSelfLocked) {
3886 mPidsSelfLocked.remove(pid);
3887 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3888 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003889 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003890 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003891 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003892 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003894 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003896 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 } else {
3898 needRestart = true;
3899 }
3900 }
3901 } else {
3902 mRemovedProcesses.add(app);
3903 }
3904
3905 return needRestart;
3906 }
3907
3908 private final void processStartTimedOutLocked(ProcessRecord app) {
3909 final int pid = app.pid;
3910 boolean gone = false;
3911 synchronized (mPidsSelfLocked) {
3912 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3913 if (knownApp != null && knownApp.thread == null) {
3914 mPidsSelfLocked.remove(pid);
3915 gone = true;
3916 }
3917 }
3918
3919 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003920 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003921 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003922 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003923 mProcessNames.remove(app.processName, app.uid);
3924 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003925 if (mHeavyWeightProcess == app) {
3926 mHeavyWeightProcess = null;
3927 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3928 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003929 // Take care of any launching providers waiting for this process.
3930 checkAppInLaunchingProvidersLocked(app, true);
3931 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003932 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003933 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3934 app.processName, app.setAdj, "start timeout");
3935 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003936 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003937 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003938 try {
3939 IBackupManager bm = IBackupManager.Stub.asInterface(
3940 ServiceManager.getService(Context.BACKUP_SERVICE));
3941 bm.agentDisconnected(app.info.packageName);
3942 } catch (RemoteException e) {
3943 // Can't happen; the backup manager is local
3944 }
3945 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003946 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003947 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003948 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003951 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 }
3953 }
3954
3955 private final boolean attachApplicationLocked(IApplicationThread thread,
3956 int pid) {
3957
3958 // Find the application record that is being attached... either via
3959 // the pid if we are running in multiple processes, or just pull the
3960 // next app record if we are emulating process with anonymous threads.
3961 ProcessRecord app;
3962 if (pid != MY_PID && pid >= 0) {
3963 synchronized (mPidsSelfLocked) {
3964 app = mPidsSelfLocked.get(pid);
3965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 } else {
3967 app = null;
3968 }
3969
3970 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003971 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003973 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003975 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 } else {
3977 try {
3978 thread.scheduleExit();
3979 } catch (Exception e) {
3980 // Ignore exceptions.
3981 }
3982 }
3983 return false;
3984 }
3985
3986 // If this application record is still attached to a previous
3987 // process, clean it up now.
3988 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003989 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 }
3991
3992 // Tell the process all about itself.
3993
Joe Onorato8a9b2202010-02-26 18:56:32 -08003994 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 TAG, "Binding process pid " + pid + " to record " + app);
3996
3997 String processName = app.processName;
3998 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003999 AppDeathRecipient adr = new AppDeathRecipient(
4000 app, pid, thread);
4001 thread.asBinder().linkToDeath(adr, 0);
4002 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 } catch (RemoteException e) {
4004 app.resetPackageList();
4005 startProcessLocked(app, "link fail", processName);
4006 return false;
4007 }
4008
Doug Zongker2bec3d42009-12-04 12:52:44 -08004009 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010
4011 app.thread = thread;
4012 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004013 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4014 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 app.forcingToForeground = null;
4016 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004017 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 app.debugging = false;
4019
4020 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4021
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004022 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004023 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004025 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004026 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004027 }
4028
Joe Onorato8a9b2202010-02-26 18:56:32 -08004029 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 TAG, "New app record " + app
4031 + " thread=" + thread.asBinder() + " pid=" + pid);
4032 try {
4033 int testMode = IApplicationThread.DEBUG_OFF;
4034 if (mDebugApp != null && mDebugApp.equals(processName)) {
4035 testMode = mWaitForDebugger
4036 ? IApplicationThread.DEBUG_WAIT
4037 : IApplicationThread.DEBUG_ON;
4038 app.debugging = true;
4039 if (mDebugTransient) {
4040 mDebugApp = mOrigDebugApp;
4041 mWaitForDebugger = mOrigWaitForDebugger;
4042 }
4043 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004044 String profileFile = app.instrumentationProfileFile;
4045 ParcelFileDescriptor profileFd = null;
4046 boolean profileAutoStop = false;
4047 if (mProfileApp != null && mProfileApp.equals(processName)) {
4048 mProfileProc = app;
4049 profileFile = mProfileFile;
4050 profileFd = mProfileFd;
4051 profileAutoStop = mAutoStopProfiler;
4052 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004053 boolean enableOpenGlTrace = false;
4054 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4055 enableOpenGlTrace = true;
4056 mOpenGlTraceApp = null;
4057 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004058
Christopher Tate181fafa2009-05-14 11:12:14 -07004059 // If the app is being launched for restore or full backup, set it up specially
4060 boolean isRestrictedBackupMode = false;
4061 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4062 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004063 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004064 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4065 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004066
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004067 ensurePackageDexOpt(app.instrumentationInfo != null
4068 ? app.instrumentationInfo.packageName
4069 : app.info.packageName);
4070 if (app.instrumentationClass != null) {
4071 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004072 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004074 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004075 ApplicationInfo appInfo = app.instrumentationInfo != null
4076 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004077 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004078 if (profileFd != null) {
4079 profileFd = profileFd.dup();
4080 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004081 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004082 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004083 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4084 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004085 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004086 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004087 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004088 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 } catch (Exception e) {
4090 // todo: Yikes! What should we do? For now we will try to
4091 // start another process, but that could easily get us in
4092 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004093 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094
4095 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004096 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 startProcessLocked(app, "bind fail", processName);
4098 return false;
4099 }
4100
4101 // Remove this record from the list of starting applications.
4102 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004103 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4104 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 mProcessesOnHold.remove(app);
4106
4107 boolean badApp = false;
4108 boolean didSomething = false;
4109
4110 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004111 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004112 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004113 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 && processName.equals(hr.processName)) {
4115 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004116 if (mHeadless) {
4117 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4118 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 didSomething = true;
4120 }
4121 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004122 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 + hr.intent.getComponent().flattenToShortString(), e);
4124 badApp = true;
4125 }
4126 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129 }
4130
4131 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004132 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004134 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 badApp = true;
4137 }
4138 }
4139
Christopher Tatef46723b2012-01-26 14:19:24 -08004140 // Check if a next-broadcast receiver is in this process...
4141 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004143 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004145 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 }
4148 }
4149
Christopher Tate181fafa2009-05-14 11:12:14 -07004150 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004151 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004152 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004153 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004154 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004155 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4156 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4157 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004158 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004159 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004160 e.printStackTrace();
4161 }
4162 }
4163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 if (badApp) {
4165 // todo: Also need to kill application to deal with all
4166 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004167 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 return false;
4169 }
4170
4171 if (!didSomething) {
4172 updateOomAdjLocked();
4173 }
4174
4175 return true;
4176 }
4177
4178 public final void attachApplication(IApplicationThread thread) {
4179 synchronized (this) {
4180 int callingPid = Binder.getCallingPid();
4181 final long origId = Binder.clearCallingIdentity();
4182 attachApplicationLocked(thread, callingPid);
4183 Binder.restoreCallingIdentity(origId);
4184 }
4185 }
4186
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004187 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004189 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4190 if (stopProfiling) {
4191 synchronized (this) {
4192 if (mProfileProc == r.app) {
4193 if (mProfileFd != null) {
4194 try {
4195 mProfileFd.close();
4196 } catch (IOException e) {
4197 }
4198 clearProfilerLocked();
4199 }
4200 }
4201 }
4202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 Binder.restoreCallingIdentity(origId);
4204 }
4205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004207 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004208 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004210
4211 synchronized (this) {
4212 updateEventDispatchingLocked();
4213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 }
4215
Dianne Hackborn661cd522011-08-22 00:26:20 -07004216 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004217 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004218 mWindowManager.showBootMessage(msg, always);
4219 }
4220
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004221 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004222 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004223 final long token = Binder.clearCallingIdentity();
4224 try {
4225 synchronized (this) {
4226 if (mLockScreenShown) {
4227 mLockScreenShown = false;
4228 comeOutOfSleepIfNeededLocked();
4229 }
4230 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004231 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004232 } finally {
4233 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004234 }
4235 }
4236
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004237 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004238 IntentFilter pkgFilter = new IntentFilter();
4239 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4240 pkgFilter.addDataScheme("package");
4241 mContext.registerReceiver(new BroadcastReceiver() {
4242 @Override
4243 public void onReceive(Context context, Intent intent) {
4244 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4245 if (pkgs != null) {
4246 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004247 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004248 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4249 setResultCode(Activity.RESULT_OK);
4250 return;
4251 }
4252 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004253 }
4254 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004255 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004256 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004257
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004258 synchronized (this) {
4259 // Ensure that any processes we had put on hold are now started
4260 // up.
4261 final int NP = mProcessesOnHold.size();
4262 if (NP > 0) {
4263 ArrayList<ProcessRecord> procs =
4264 new ArrayList<ProcessRecord>(mProcessesOnHold);
4265 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004266 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4267 + procs.get(ip));
4268 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004269 }
4270 }
4271
4272 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004273 // Start looking for apps that are abusing wake locks.
4274 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004275 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004276 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004277 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004278 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004279 for (int i=0; i<mStartedUsers.size(); i++) {
4280 UserStartedState uss = mStartedUsers.valueAt(i);
4281 if (uss.mState == UserStartedState.STATE_BOOTING) {
4282 uss.mState = UserStartedState.STATE_RUNNING;
4283 broadcastIntentLocked(null, null,
4284 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4285 null, null, 0, null, null,
4286 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
4287 false, false, MY_PID, Process.SYSTEM_UID,
4288 mStartedUsers.keyAt(i));
4289 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004290 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004291 }
4292 }
4293 }
4294
4295 final void ensureBootCompleted() {
4296 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004297 boolean enableScreen;
4298 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 booting = mBooting;
4300 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004301 enableScreen = !mBooted;
4302 mBooted = true;
4303 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004304
4305 if (booting) {
4306 finishBooting();
4307 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004308
4309 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004310 enableScreenAfterBoot();
4311 }
4312 }
4313
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004314 public final void activityPaused(IBinder token) {
4315 final long origId = Binder.clearCallingIdentity();
4316 mMainStack.activityPaused(token, false);
4317 Binder.restoreCallingIdentity(origId);
4318 }
4319
4320 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4321 CharSequence description) {
4322 if (localLOGV) Slog.v(
4323 TAG, "Activity stopped: token=" + token);
4324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 // Refuse possible leaked file descriptors
4326 if (icicle != null && icicle.hasFileDescriptors()) {
4327 throw new IllegalArgumentException("File descriptors passed in Bundle");
4328 }
4329
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004330 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331
4332 final long origId = Binder.clearCallingIdentity();
4333
4334 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004335 r = mMainStack.isInStackLocked(token);
4336 if (r != null) {
4337 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 }
4339 }
4340
4341 if (r != null) {
4342 sendPendingThumbnail(r, null, null, null, false);
4343 }
4344
4345 trimApplications();
4346
4347 Binder.restoreCallingIdentity(origId);
4348 }
4349
4350 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004351 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004352 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 }
4354
4355 public String getCallingPackage(IBinder token) {
4356 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004357 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004358 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 }
4360 }
4361
4362 public ComponentName getCallingActivity(IBinder token) {
4363 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004364 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 return r != null ? r.intent.getComponent() : null;
4366 }
4367 }
4368
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004369 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 ActivityRecord r = mMainStack.isInStackLocked(token);
4371 if (r == null) {
4372 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004374 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 }
4376
4377 public ComponentName getActivityClassForToken(IBinder token) {
4378 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004379 ActivityRecord r = mMainStack.isInStackLocked(token);
4380 if (r == null) {
4381 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004383 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
4385 }
4386
4387 public String getPackageForToken(IBinder token) {
4388 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004389 ActivityRecord r = mMainStack.isInStackLocked(token);
4390 if (r == null) {
4391 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004393 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 }
4395 }
4396
4397 public IIntentSender getIntentSender(int type,
4398 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004399 int requestCode, Intent[] intents, String[] resolvedTypes,
4400 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004401 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004403 if (intents != null) {
4404 if (intents.length < 1) {
4405 throw new IllegalArgumentException("Intents array length must be >= 1");
4406 }
4407 for (int i=0; i<intents.length; i++) {
4408 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004409 if (intent != null) {
4410 if (intent.hasFileDescriptors()) {
4411 throw new IllegalArgumentException("File descriptors passed in Intent");
4412 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004413 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004414 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4415 throw new IllegalArgumentException(
4416 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4417 }
4418 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004419 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004420 }
4421 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004422 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004423 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004424 }
4425 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004426 if (options != null) {
4427 if (options.hasFileDescriptors()) {
4428 throw new IllegalArgumentException("File descriptors passed in options");
4429 }
4430 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 synchronized(this) {
4433 int callingUid = Binder.getCallingUid();
4434 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004435 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004436 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004437 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4438 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 String msg = "Permission Denial: getIntentSender() from pid="
4440 + Binder.getCallingPid()
4441 + ", uid=" + Binder.getCallingUid()
4442 + ", (need uid=" + uid + ")"
4443 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004444 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 throw new SecurityException(msg);
4446 }
4447 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004448
Amith Yamasani742a6712011-05-04 14:49:28 -07004449 if (DEBUG_MU)
4450 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4451 + Binder.getOrigCallingUid());
4452 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004453 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 } catch (RemoteException e) {
4456 throw new SecurityException(e);
4457 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004458 }
4459 }
4460
4461 IIntentSender getIntentSenderLocked(int type,
4462 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004463 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4464 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004465 if (DEBUG_MU)
4466 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004467 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004468 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004469 activity = mMainStack.isInStackLocked(token);
4470 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004471 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004473 if (activity.finishing) {
4474 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004476 }
4477
4478 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4479 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4480 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4481 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4482 |PendingIntent.FLAG_UPDATE_CURRENT);
4483
4484 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4485 type, packageName, activity, resultWho,
Amith Yamasani4ea60692012-08-28 14:34:53 -07004486 requestCode, intents, resolvedTypes, flags, options,
4487 UserHandle.getUserId(callingUid));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004488 WeakReference<PendingIntentRecord> ref;
4489 ref = mIntentSenderRecords.get(key);
4490 PendingIntentRecord rec = ref != null ? ref.get() : null;
4491 if (rec != null) {
4492 if (!cancelCurrent) {
4493 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004494 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004495 rec.key.requestIntent.replaceExtras(intents != null ?
4496 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004497 }
4498 if (intents != null) {
4499 intents[intents.length-1] = rec.key.requestIntent;
4500 rec.key.allIntents = intents;
4501 rec.key.allResolvedTypes = resolvedTypes;
4502 } else {
4503 rec.key.allIntents = null;
4504 rec.key.allResolvedTypes = null;
4505 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 return rec;
4508 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004509 rec.canceled = true;
4510 mIntentSenderRecords.remove(key);
4511 }
4512 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 return rec;
4514 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004515 rec = new PendingIntentRecord(this, key, callingUid);
4516 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004517 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004518 if (activity.pendingResults == null) {
4519 activity.pendingResults
4520 = new HashSet<WeakReference<PendingIntentRecord>>();
4521 }
4522 activity.pendingResults.add(rec.ref);
4523 }
4524 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526
4527 public void cancelIntentSender(IIntentSender sender) {
4528 if (!(sender instanceof PendingIntentRecord)) {
4529 return;
4530 }
4531 synchronized(this) {
4532 PendingIntentRecord rec = (PendingIntentRecord)sender;
4533 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004534 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004535 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4536 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 String msg = "Permission Denial: cancelIntentSender() from pid="
4538 + Binder.getCallingPid()
4539 + ", uid=" + Binder.getCallingUid()
4540 + " is not allowed to cancel packges "
4541 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004542 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 throw new SecurityException(msg);
4544 }
4545 } catch (RemoteException e) {
4546 throw new SecurityException(e);
4547 }
4548 cancelIntentSenderLocked(rec, true);
4549 }
4550 }
4551
4552 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4553 rec.canceled = true;
4554 mIntentSenderRecords.remove(rec.key);
4555 if (cleanActivity && rec.key.activity != null) {
4556 rec.key.activity.pendingResults.remove(rec.ref);
4557 }
4558 }
4559
4560 public String getPackageForIntentSender(IIntentSender pendingResult) {
4561 if (!(pendingResult instanceof PendingIntentRecord)) {
4562 return null;
4563 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004564 try {
4565 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4566 return res.key.packageName;
4567 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 }
4569 return null;
4570 }
4571
Christopher Tatec4a07d12012-04-06 14:19:13 -07004572 public int getUidForIntentSender(IIntentSender sender) {
4573 if (sender instanceof PendingIntentRecord) {
4574 try {
4575 PendingIntentRecord res = (PendingIntentRecord)sender;
4576 return res.uid;
4577 } catch (ClassCastException e) {
4578 }
4579 }
4580 return -1;
4581 }
4582
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004583 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4584 if (!(pendingResult instanceof PendingIntentRecord)) {
4585 return false;
4586 }
4587 try {
4588 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4589 if (res.key.allIntents == null) {
4590 return false;
4591 }
4592 for (int i=0; i<res.key.allIntents.length; i++) {
4593 Intent intent = res.key.allIntents[i];
4594 if (intent.getPackage() != null && intent.getComponent() != null) {
4595 return false;
4596 }
4597 }
4598 return true;
4599 } catch (ClassCastException e) {
4600 }
4601 return false;
4602 }
4603
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004604 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4605 if (!(pendingResult instanceof PendingIntentRecord)) {
4606 return false;
4607 }
4608 try {
4609 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4610 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4611 return true;
4612 }
4613 return false;
4614 } catch (ClassCastException e) {
4615 }
4616 return false;
4617 }
4618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 public void setProcessLimit(int max) {
4620 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4621 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004622 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004623 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004624 mProcessLimitOverride = max;
4625 }
4626 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 }
4628
4629 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004630 synchronized (this) {
4631 return mProcessLimitOverride;
4632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 }
4634
4635 void foregroundTokenDied(ForegroundToken token) {
4636 synchronized (ActivityManagerService.this) {
4637 synchronized (mPidsSelfLocked) {
4638 ForegroundToken cur
4639 = mForegroundProcesses.get(token.pid);
4640 if (cur != token) {
4641 return;
4642 }
4643 mForegroundProcesses.remove(token.pid);
4644 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4645 if (pr == null) {
4646 return;
4647 }
4648 pr.forcingToForeground = null;
4649 pr.foregroundServices = false;
4650 }
4651 updateOomAdjLocked();
4652 }
4653 }
4654
4655 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4656 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4657 "setProcessForeground()");
4658 synchronized(this) {
4659 boolean changed = false;
4660
4661 synchronized (mPidsSelfLocked) {
4662 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004663 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004664 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 return;
4666 }
4667 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4668 if (oldToken != null) {
4669 oldToken.token.unlinkToDeath(oldToken, 0);
4670 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004671 if (pr != null) {
4672 pr.forcingToForeground = null;
4673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 changed = true;
4675 }
4676 if (isForeground && token != null) {
4677 ForegroundToken newToken = new ForegroundToken() {
4678 public void binderDied() {
4679 foregroundTokenDied(this);
4680 }
4681 };
4682 newToken.pid = pid;
4683 newToken.token = token;
4684 try {
4685 token.linkToDeath(newToken, 0);
4686 mForegroundProcesses.put(pid, newToken);
4687 pr.forcingToForeground = token;
4688 changed = true;
4689 } catch (RemoteException e) {
4690 // If the process died while doing this, we will later
4691 // do the cleanup with the process death link.
4692 }
4693 }
4694 }
4695
4696 if (changed) {
4697 updateOomAdjLocked();
4698 }
4699 }
4700 }
4701
4702 // =========================================================
4703 // PERMISSIONS
4704 // =========================================================
4705
4706 static class PermissionController extends IPermissionController.Stub {
4707 ActivityManagerService mActivityManagerService;
4708 PermissionController(ActivityManagerService activityManagerService) {
4709 mActivityManagerService = activityManagerService;
4710 }
4711
4712 public boolean checkPermission(String permission, int pid, int uid) {
4713 return mActivityManagerService.checkPermission(permission, pid,
4714 uid) == PackageManager.PERMISSION_GRANTED;
4715 }
4716 }
4717
4718 /**
4719 * This can be called with or without the global lock held.
4720 */
4721 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004722 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 // We might be performing an operation on behalf of an indirect binder
4724 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4725 // client identity accordingly before proceeding.
4726 Identity tlsIdentity = sCallerIdentity.get();
4727 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004728 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4730 uid = tlsIdentity.uid;
4731 pid = tlsIdentity.pid;
4732 }
4733
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004734 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 return PackageManager.PERMISSION_GRANTED;
4736 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004737
4738 return ActivityManager.checkComponentPermission(permission, uid,
4739 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 }
4741
4742 /**
4743 * As the only public entry point for permissions checking, this method
4744 * can enforce the semantic that requesting a check on a null global
4745 * permission is automatically denied. (Internally a null permission
4746 * string is used when calling {@link #checkComponentPermission} in cases
4747 * when only uid-based security is needed.)
4748 *
4749 * This can be called with or without the global lock held.
4750 */
4751 public int checkPermission(String permission, int pid, int uid) {
4752 if (permission == null) {
4753 return PackageManager.PERMISSION_DENIED;
4754 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004755 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 }
4757
4758 /**
4759 * Binder IPC calls go through the public entry point.
4760 * This can be called with or without the global lock held.
4761 */
4762 int checkCallingPermission(String permission) {
4763 return checkPermission(permission,
4764 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004765 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 }
4767
4768 /**
4769 * This can be called with or without the global lock held.
4770 */
4771 void enforceCallingPermission(String permission, String func) {
4772 if (checkCallingPermission(permission)
4773 == PackageManager.PERMISSION_GRANTED) {
4774 return;
4775 }
4776
4777 String msg = "Permission Denial: " + func + " from pid="
4778 + Binder.getCallingPid()
4779 + ", uid=" + Binder.getCallingUid()
4780 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004781 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782 throw new SecurityException(msg);
4783 }
4784
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004785 /**
4786 * Determine if UID is holding permissions required to access {@link Uri} in
4787 * the given {@link ProviderInfo}. Final permission checking is always done
4788 * in {@link ContentProvider}.
4789 */
4790 private final boolean checkHoldingPermissionsLocked(
4791 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004792 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4793 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004794
4795 if (pi.applicationInfo.uid == uid) {
4796 return true;
4797 } else if (!pi.exported) {
4798 return false;
4799 }
4800
4801 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4802 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004804 // check if target holds top-level <provider> permissions
4805 if (!readMet && pi.readPermission != null
4806 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4807 readMet = true;
4808 }
4809 if (!writeMet && pi.writePermission != null
4810 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4811 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004813
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004814 // track if unprotected read/write is allowed; any denied
4815 // <path-permission> below removes this ability
4816 boolean allowDefaultRead = pi.readPermission == null;
4817 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004818
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004819 // check if target holds any <path-permission> that match uri
4820 final PathPermission[] pps = pi.pathPermissions;
4821 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004822 final String path = uri.getPath();
4823 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004824 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004825 i--;
4826 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004827 if (pp.match(path)) {
4828 if (!readMet) {
4829 final String pprperm = pp.getReadPermission();
4830 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4831 + pprperm + " for " + pp.getPath()
4832 + ": match=" + pp.match(path)
4833 + " check=" + pm.checkUidPermission(pprperm, uid));
4834 if (pprperm != null) {
4835 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4836 readMet = true;
4837 } else {
4838 allowDefaultRead = false;
4839 }
4840 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004841 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004842 if (!writeMet) {
4843 final String ppwperm = pp.getWritePermission();
4844 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4845 + ppwperm + " for " + pp.getPath()
4846 + ": match=" + pp.match(path)
4847 + " check=" + pm.checkUidPermission(ppwperm, uid));
4848 if (ppwperm != null) {
4849 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4850 writeMet = true;
4851 } else {
4852 allowDefaultWrite = false;
4853 }
4854 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004855 }
4856 }
4857 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004858 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004859
4860 // grant unprotected <provider> read/write, if not blocked by
4861 // <path-permission> above
4862 if (allowDefaultRead) readMet = true;
4863 if (allowDefaultWrite) writeMet = true;
4864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 } catch (RemoteException e) {
4866 return false;
4867 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004868
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004869 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871
4872 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4873 int modeFlags) {
4874 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004875 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 return true;
4877 }
4878 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4879 if (perms == null) return false;
4880 UriPermission perm = perms.get(uri);
4881 if (perm == null) return false;
4882 return (modeFlags&perm.modeFlags) == modeFlags;
4883 }
4884
4885 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004886 enforceNotIsolatedCaller("checkUriPermission");
4887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 // Another redirected-binder-call permissions check as in
4889 // {@link checkComponentPermission}.
4890 Identity tlsIdentity = sCallerIdentity.get();
4891 if (tlsIdentity != null) {
4892 uid = tlsIdentity.uid;
4893 pid = tlsIdentity.pid;
4894 }
4895
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004896 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 // Our own process gets to do everything.
4898 if (pid == MY_PID) {
4899 return PackageManager.PERMISSION_GRANTED;
4900 }
4901 synchronized(this) {
4902 return checkUriPermissionLocked(uri, uid, modeFlags)
4903 ? PackageManager.PERMISSION_GRANTED
4904 : PackageManager.PERMISSION_DENIED;
4905 }
4906 }
4907
Dianne Hackborn39792d22010-08-19 18:01:52 -07004908 /**
4909 * Check if the targetPkg can be granted permission to access uri by
4910 * the callingUid using the given modeFlags. Throws a security exception
4911 * if callingUid is not allowed to do this. Returns the uid of the target
4912 * if the URI permission grant should be performed; returns -1 if it is not
4913 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004914 * If you already know the uid of the target, you can supply it in
4915 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004916 */
4917 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004918 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4920 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4921 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004922 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 }
4924
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004925 if (targetPkg != null) {
4926 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4927 "Checking grant " + targetPkg + " permission to " + uri);
4928 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004929
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004930 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931
4932 // If this is not a content: uri, we can't do anything with it.
4933 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004934 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004935 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004936 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004937 }
4938
4939 String name = uri.getAuthority();
4940 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004941 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004942 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 if (cpr != null) {
4944 pi = cpr.info;
4945 } else {
4946 try {
4947 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004948 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 } catch (RemoteException ex) {
4950 }
4951 }
4952 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004953 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004954 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 }
4956
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004957 int targetUid = lastTargetUid;
4958 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004959 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004960 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004961 if (targetUid < 0) {
4962 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4963 "Can't grant URI permission no uid for: " + targetPkg);
4964 return -1;
4965 }
4966 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004967 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 }
4970
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004971 if (targetUid >= 0) {
4972 // First... does the target actually need this permission?
4973 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4974 // No need to grant the target this permission.
4975 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4976 "Target " + targetPkg + " already has full permission to " + uri);
4977 return -1;
4978 }
4979 } else {
4980 // First... there is no target package, so can anyone access it?
4981 boolean allowed = pi.exported;
4982 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4983 if (pi.readPermission != null) {
4984 allowed = false;
4985 }
4986 }
4987 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4988 if (pi.writePermission != null) {
4989 allowed = false;
4990 }
4991 }
4992 if (allowed) {
4993 return -1;
4994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 }
4996
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004997 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 if (!pi.grantUriPermissions) {
4999 throw new SecurityException("Provider " + pi.packageName
5000 + "/" + pi.name
5001 + " does not allow granting of Uri permissions (uri "
5002 + uri + ")");
5003 }
5004 if (pi.uriPermissionPatterns != null) {
5005 final int N = pi.uriPermissionPatterns.length;
5006 boolean allowed = false;
5007 for (int i=0; i<N; i++) {
5008 if (pi.uriPermissionPatterns[i] != null
5009 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5010 allowed = true;
5011 break;
5012 }
5013 }
5014 if (!allowed) {
5015 throw new SecurityException("Provider " + pi.packageName
5016 + "/" + pi.name
5017 + " does not allow granting of permission to path of Uri "
5018 + uri);
5019 }
5020 }
5021
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005022 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005024 if (callingUid != Process.myUid()) {
5025 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5026 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5027 throw new SecurityException("Uid " + callingUid
5028 + " does not have permission to uri " + uri);
5029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 }
5031 }
5032
Dianne Hackborn39792d22010-08-19 18:01:52 -07005033 return targetUid;
5034 }
5035
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005036 public int checkGrantUriPermission(int callingUid, String targetPkg,
5037 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005038 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005039 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005040 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005041 }
5042 }
5043
Dianne Hackborn39792d22010-08-19 18:01:52 -07005044 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5045 Uri uri, int modeFlags, UriPermissionOwner owner) {
5046 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5047 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5048 if (modeFlags == 0) {
5049 return;
5050 }
5051
5052 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005053 // to the uri, and the target doesn't. Let's now give this to
5054 // the target.
5055
Joe Onorato8a9b2202010-02-26 18:56:32 -08005056 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005057 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 HashMap<Uri, UriPermission> targetUris
5060 = mGrantedUriPermissions.get(targetUid);
5061 if (targetUris == null) {
5062 targetUris = new HashMap<Uri, UriPermission>();
5063 mGrantedUriPermissions.put(targetUid, targetUris);
5064 }
5065
5066 UriPermission perm = targetUris.get(uri);
5067 if (perm == null) {
5068 perm = new UriPermission(targetUid, uri);
5069 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005073 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005075 } else {
5076 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5077 perm.readOwners.add(owner);
5078 owner.addReadPermission(perm);
5079 }
5080 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5081 perm.writeOwners.add(owner);
5082 owner.addWritePermission(perm);
5083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 }
5085 }
5086
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005087 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5088 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005089 if (targetPkg == null) {
5090 throw new NullPointerException("targetPkg");
5091 }
5092
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005093 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005094 if (targetUid < 0) {
5095 return;
5096 }
5097
5098 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5099 }
5100
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005101 static class NeededUriGrants extends ArrayList<Uri> {
5102 final String targetPkg;
5103 final int targetUid;
5104 final int flags;
5105
5106 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5107 targetPkg = _targetPkg;
5108 targetUid = _targetUid;
5109 flags = _flags;
5110 }
5111 }
5112
Dianne Hackborn39792d22010-08-19 18:01:52 -07005113 /**
5114 * Like checkGrantUriPermissionLocked, but takes an Intent.
5115 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005116 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5117 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005118 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005119 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5120 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005121 + " from " + intent + "; flags=0x"
5122 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5123
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005124 if (targetPkg == null) {
5125 throw new NullPointerException("targetPkg");
5126 }
5127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005129 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 }
5131 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005132 ClipData clip = intent.getClipData();
5133 if (data == null && clip == null) {
5134 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005135 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005136 if (data != null) {
5137 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5138 mode, needed != null ? needed.targetUid : -1);
5139 if (target > 0) {
5140 if (needed == null) {
5141 needed = new NeededUriGrants(targetPkg, target, mode);
5142 }
5143 needed.add(data);
5144 }
5145 }
5146 if (clip != null) {
5147 for (int i=0; i<clip.getItemCount(); i++) {
5148 Uri uri = clip.getItemAt(i).getUri();
5149 if (uri != null) {
5150 int target = -1;
5151 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5152 mode, needed != null ? needed.targetUid : -1);
5153 if (target > 0) {
5154 if (needed == null) {
5155 needed = new NeededUriGrants(targetPkg, target, mode);
5156 }
5157 needed.add(uri);
5158 }
5159 } else {
5160 Intent clipIntent = clip.getItemAt(i).getIntent();
5161 if (clipIntent != null) {
5162 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5163 callingUid, targetPkg, clipIntent, mode, needed);
5164 if (newNeeded != null) {
5165 needed = newNeeded;
5166 }
5167 }
5168 }
5169 }
5170 }
5171
5172 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005173 }
5174
5175 /**
5176 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5177 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005178 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5179 UriPermissionOwner owner) {
5180 if (needed != null) {
5181 for (int i=0; i<needed.size(); i++) {
5182 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5183 needed.get(i), needed.flags, owner);
5184 }
5185 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005186 }
5187
5188 void grantUriPermissionFromIntentLocked(int callingUid,
5189 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005190 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005191 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005192 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 return;
5194 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005195
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005196 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 }
5198
5199 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5200 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005201 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 synchronized(this) {
5203 final ProcessRecord r = getRecordForAppLocked(caller);
5204 if (r == null) {
5205 throw new SecurityException("Unable to find app for caller "
5206 + caller
5207 + " when granting permission to uri " + uri);
5208 }
5209 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005210 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 }
5212 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005213 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214 }
5215
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005216 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 null);
5218 }
5219 }
5220
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005221 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5223 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5224 HashMap<Uri, UriPermission> perms
5225 = mGrantedUriPermissions.get(perm.uid);
5226 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005227 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005228 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 perms.remove(perm.uri);
5230 if (perms.size() == 0) {
5231 mGrantedUriPermissions.remove(perm.uid);
5232 }
5233 }
5234 }
5235 }
5236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5238 int modeFlags) {
5239 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5240 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5241 if (modeFlags == 0) {
5242 return;
5243 }
5244
Joe Onorato8a9b2202010-02-26 18:56:32 -08005245 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005246 "Revoking all granted permissions to " + uri);
5247
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005248 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249
5250 final String authority = uri.getAuthority();
5251 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005252 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005253 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005254 if (cpr != null) {
5255 pi = cpr.info;
5256 } else {
5257 try {
5258 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005259 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 } catch (RemoteException ex) {
5261 }
5262 }
5263 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005264 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 return;
5266 }
5267
5268 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005269 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 // Right now, if you are not the original owner of the permission,
5271 // you are not allowed to revoke it.
5272 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5273 throw new SecurityException("Uid " + callingUid
5274 + " does not have permission to uri " + uri);
5275 //}
5276 }
5277
5278 // Go through all of the permissions and remove any that match.
5279 final List<String> SEGMENTS = uri.getPathSegments();
5280 if (SEGMENTS != null) {
5281 final int NS = SEGMENTS.size();
5282 int N = mGrantedUriPermissions.size();
5283 for (int i=0; i<N; i++) {
5284 HashMap<Uri, UriPermission> perms
5285 = mGrantedUriPermissions.valueAt(i);
5286 Iterator<UriPermission> it = perms.values().iterator();
5287 toploop:
5288 while (it.hasNext()) {
5289 UriPermission perm = it.next();
5290 Uri targetUri = perm.uri;
5291 if (!authority.equals(targetUri.getAuthority())) {
5292 continue;
5293 }
5294 List<String> targetSegments = targetUri.getPathSegments();
5295 if (targetSegments == null) {
5296 continue;
5297 }
5298 if (targetSegments.size() < NS) {
5299 continue;
5300 }
5301 for (int j=0; j<NS; j++) {
5302 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5303 continue toploop;
5304 }
5305 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005306 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005307 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 perm.clearModes(modeFlags);
5309 if (perm.modeFlags == 0) {
5310 it.remove();
5311 }
5312 }
5313 if (perms.size() == 0) {
5314 mGrantedUriPermissions.remove(
5315 mGrantedUriPermissions.keyAt(i));
5316 N--;
5317 i--;
5318 }
5319 }
5320 }
5321 }
5322
5323 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5324 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005325 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 synchronized(this) {
5327 final ProcessRecord r = getRecordForAppLocked(caller);
5328 if (r == null) {
5329 throw new SecurityException("Unable to find app for caller "
5330 + caller
5331 + " when revoking permission to uri " + uri);
5332 }
5333 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005334 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 return;
5336 }
5337
5338 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5339 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5340 if (modeFlags == 0) {
5341 return;
5342 }
5343
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005344 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345
5346 final String authority = uri.getAuthority();
5347 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005348 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 if (cpr != null) {
5350 pi = cpr.info;
5351 } else {
5352 try {
5353 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005354 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 } catch (RemoteException ex) {
5356 }
5357 }
5358 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005359 Slog.w(TAG, "No content provider found for permission revoke: "
5360 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 return;
5362 }
5363
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005364 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005365 }
5366 }
5367
Dianne Hackborn7e269642010-08-25 19:50:20 -07005368 @Override
5369 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005370 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005371 synchronized(this) {
5372 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5373 return owner.getExternalTokenLocked();
5374 }
5375 }
5376
5377 @Override
5378 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5379 Uri uri, int modeFlags) {
5380 synchronized(this) {
5381 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5382 if (owner == null) {
5383 throw new IllegalArgumentException("Unknown owner: " + token);
5384 }
5385 if (fromUid != Binder.getCallingUid()) {
5386 if (Binder.getCallingUid() != Process.myUid()) {
5387 // Only system code can grant URI permissions on behalf
5388 // of other users.
5389 throw new SecurityException("nice try");
5390 }
5391 }
5392 if (targetPkg == null) {
5393 throw new IllegalArgumentException("null target");
5394 }
5395 if (uri == null) {
5396 throw new IllegalArgumentException("null uri");
5397 }
5398
5399 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5400 }
5401 }
5402
5403 @Override
5404 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5405 synchronized(this) {
5406 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5407 if (owner == null) {
5408 throw new IllegalArgumentException("Unknown owner: " + token);
5409 }
5410
5411 if (uri == null) {
5412 owner.removeUriPermissionsLocked(mode);
5413 } else {
5414 owner.removeUriPermissionLocked(uri, mode);
5415 }
5416 }
5417 }
5418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5420 synchronized (this) {
5421 ProcessRecord app =
5422 who != null ? getRecordForAppLocked(who) : null;
5423 if (app == null) return;
5424
5425 Message msg = Message.obtain();
5426 msg.what = WAIT_FOR_DEBUGGER_MSG;
5427 msg.obj = app;
5428 msg.arg1 = waiting ? 1 : 0;
5429 mHandler.sendMessage(msg);
5430 }
5431 }
5432
5433 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005434 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5435 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005437 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005438 outInfo.threshold = homeAppMem;
5439 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5440 outInfo.hiddenAppThreshold = hiddenAppMem;
5441 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005442 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005443 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5444 ProcessList.VISIBLE_APP_ADJ);
5445 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5446 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 }
5448
5449 // =========================================================
5450 // TASK MANAGEMENT
5451 // =========================================================
5452
5453 public List getTasks(int maxNum, int flags,
5454 IThumbnailReceiver receiver) {
5455 ArrayList list = new ArrayList();
5456
5457 PendingThumbnailsRecord pending = null;
5458 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005459 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460
5461 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005462 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5464 + ", receiver=" + receiver);
5465
5466 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5467 != PackageManager.PERMISSION_GRANTED) {
5468 if (receiver != null) {
5469 // If the caller wants to wait for pending thumbnails,
5470 // it ain't gonna get them.
5471 try {
5472 receiver.finished();
5473 } catch (RemoteException ex) {
5474 }
5475 }
5476 String msg = "Permission Denial: getTasks() from pid="
5477 + Binder.getCallingPid()
5478 + ", uid=" + Binder.getCallingUid()
5479 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005480 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 throw new SecurityException(msg);
5482 }
5483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005484 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005485 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005486 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005487 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 TaskRecord curTask = null;
5489 int numActivities = 0;
5490 int numRunning = 0;
5491 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005492 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005494 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495
5496 // Initialize state for next task if needed.
5497 if (top == null ||
5498 (top.state == ActivityState.INITIALIZING
5499 && top.task == r.task)) {
5500 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 curTask = r.task;
5502 numActivities = numRunning = 0;
5503 }
5504
5505 // Add 'r' into the current task.
5506 numActivities++;
5507 if (r.app != null && r.app.thread != null) {
5508 numRunning++;
5509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510
Joe Onorato8a9b2202010-02-26 18:56:32 -08005511 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 TAG, r.intent.getComponent().flattenToShortString()
5513 + ": task=" + r.task);
5514
5515 // If the next one is a different task, generate a new
5516 // TaskInfo entry for what we have.
5517 if (next == null || next.task != curTask) {
5518 ActivityManager.RunningTaskInfo ci
5519 = new ActivityManager.RunningTaskInfo();
5520 ci.id = curTask.taskId;
5521 ci.baseActivity = r.intent.getComponent();
5522 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005523 if (top.thumbHolder != null) {
5524 ci.description = top.thumbHolder.lastDescription;
5525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 ci.numActivities = numActivities;
5527 ci.numRunning = numRunning;
5528 //System.out.println(
5529 // "#" + maxNum + ": " + " descr=" + ci.description);
5530 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005531 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 TAG, "State=" + top.state + "Idle=" + top.idle
5533 + " app=" + top.app
5534 + " thr=" + (top.app != null ? top.app.thread : null));
5535 if (top.state == ActivityState.RESUMED
5536 || top.state == ActivityState.PAUSING) {
5537 if (top.idle && top.app != null
5538 && top.app.thread != null) {
5539 topRecord = top;
5540 topThumbnail = top.app.thread;
5541 } else {
5542 top.thumbnailNeeded = true;
5543 }
5544 }
5545 if (pending == null) {
5546 pending = new PendingThumbnailsRecord(receiver);
5547 }
5548 pending.pendingRecords.add(top);
5549 }
5550 list.add(ci);
5551 maxNum--;
5552 top = null;
5553 }
5554 }
5555
5556 if (pending != null) {
5557 mPendingThumbnails.add(pending);
5558 }
5559 }
5560
Joe Onorato8a9b2202010-02-26 18:56:32 -08005561 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562
5563 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005564 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005566 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005568 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005569 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 }
5571 }
5572
5573 if (pending == null && receiver != null) {
5574 // In this case all thumbnails were available and the client
5575 // is being asked to be told when the remaining ones come in...
5576 // which is unusually, since the top-most currently running
5577 // activity should never have a canned thumbnail! Oh well.
5578 try {
5579 receiver.finished();
5580 } catch (RemoteException ex) {
5581 }
5582 }
5583
5584 return list;
5585 }
5586
5587 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005588 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005589 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005590 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005591 // Check if the caller is holding permissions for cross-user requests.
5592 if (checkComponentPermission(
5593 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5594 Binder.getCallingPid(), callingUid, -1, true)
5595 != PackageManager.PERMISSION_GRANTED) {
5596 String msg = "Permission Denial: "
5597 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005598 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005599 + "; this requires "
5600 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5601 Slog.w(TAG, msg);
5602 throw new SecurityException(msg);
5603 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005604 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005605 userId = mCurrentUserId;
5606 }
5607 }
5608 }
5609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 synchronized (this) {
5611 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5612 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005613 final boolean detailed = checkCallingPermission(
5614 android.Manifest.permission.GET_DETAILED_TASKS)
5615 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005617 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 final int N = mRecentTasks.size();
5620 ArrayList<ActivityManager.RecentTaskInfo> res
5621 = new ArrayList<ActivityManager.RecentTaskInfo>(
5622 maxNum < N ? maxNum : N);
5623 for (int i=0; i<N && maxNum > 0; i++) {
5624 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005625 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005626 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005627 // Return the entry if desired by the caller. We always return
5628 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005629 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005630 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5631 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005632
Dianne Hackborn905577f2011-09-07 18:31:28 -07005633 if (i == 0
5634 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 || (tr.intent == null)
5636 || ((tr.intent.getFlags()
5637 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5638 ActivityManager.RecentTaskInfo rti
5639 = new ActivityManager.RecentTaskInfo();
5640 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005641 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 rti.baseIntent = new Intent(
5643 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005644 if (!detailed) {
5645 rti.baseIntent.replaceExtras((Bundle)null);
5646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005648 rti.description = tr.lastDescription;
5649
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005650 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5651 // Check whether this activity is currently available.
5652 try {
5653 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005654 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005655 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005656 continue;
5657 }
5658 } else if (rti.baseIntent != null) {
5659 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005660 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005661 continue;
5662 }
5663 }
5664 } catch (RemoteException e) {
5665 // Will never happen.
5666 }
5667 }
5668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 res.add(rti);
5670 maxNum--;
5671 }
5672 }
5673 return res;
5674 }
5675 }
5676
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005677 private TaskRecord taskForIdLocked(int id) {
5678 final int N = mRecentTasks.size();
5679 for (int i=0; i<N; i++) {
5680 TaskRecord tr = mRecentTasks.get(i);
5681 if (tr.taskId == id) {
5682 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005683 }
5684 }
5685 return null;
5686 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005687
5688 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5689 synchronized (this) {
5690 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5691 "getTaskThumbnails()");
5692 TaskRecord tr = taskForIdLocked(id);
5693 if (tr != null) {
5694 return mMainStack.getTaskThumbnailsLocked(tr);
5695 }
5696 }
5697 return null;
5698 }
5699
5700 public boolean removeSubTask(int taskId, int subTaskIndex) {
5701 synchronized (this) {
5702 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5703 "removeSubTask()");
5704 long ident = Binder.clearCallingIdentity();
5705 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005706 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5707 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005708 } finally {
5709 Binder.restoreCallingIdentity(ident);
5710 }
5711 }
5712 }
5713
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005714 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5715 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005716 Intent baseIntent = new Intent(
5717 tr.intent != null ? tr.intent : tr.affinityIntent);
5718 ComponentName component = baseIntent.getComponent();
5719 if (component == null) {
5720 Slog.w(TAG, "Now component for base intent of task: " + tr);
5721 return;
5722 }
5723
5724 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005725 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005726
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005727 if (killProcesses) {
5728 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005729 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005730 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005731 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5732 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5733 for (int i=0; i<uids.size(); i++) {
5734 ProcessRecord proc = uids.valueAt(i);
5735 if (proc.userId != tr.userId) {
5736 continue;
5737 }
5738 if (!proc.pkgList.contains(pkg)) {
5739 continue;
5740 }
5741 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005742 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005743 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005744
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005745 // Kill the running processes.
5746 for (int i=0; i<procs.size(); i++) {
5747 ProcessRecord pr = procs.get(i);
5748 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5749 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5750 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5751 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005752 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005753 Process.killProcessQuiet(pr.pid);
5754 } else {
5755 pr.waitingToKill = "remove task";
5756 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005757 }
5758 }
5759 }
5760
5761 public boolean removeTask(int taskId, int flags) {
5762 synchronized (this) {
5763 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5764 "removeTask()");
5765 long ident = Binder.clearCallingIdentity();
5766 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005767 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5768 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005769 if (r != null) {
5770 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005771 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005772 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005773 } else {
5774 TaskRecord tr = null;
5775 int i=0;
5776 while (i < mRecentTasks.size()) {
5777 TaskRecord t = mRecentTasks.get(i);
5778 if (t.taskId == taskId) {
5779 tr = t;
5780 break;
5781 }
5782 i++;
5783 }
5784 if (tr != null) {
5785 if (tr.numActivities <= 0) {
5786 // Caller is just removing a recent task that is
5787 // not actively running. That is easy!
5788 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005789 cleanUpRemovedTaskLocked(tr, flags);
5790 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005791 } else {
5792 Slog.w(TAG, "removeTask: task " + taskId
5793 + " does not have activities to remove, "
5794 + " but numActivities=" + tr.numActivities
5795 + ": " + tr);
5796 }
5797 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005798 }
5799 } finally {
5800 Binder.restoreCallingIdentity(ident);
5801 }
5802 }
5803 return false;
5804 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5807 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005808 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 TaskRecord jt = startTask;
5810
5811 // First look backwards
5812 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005813 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 if (r.task != jt) {
5815 jt = r.task;
5816 if (affinity.equals(jt.affinity)) {
5817 return j;
5818 }
5819 }
5820 }
5821
5822 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 jt = startTask;
5825 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005826 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 if (r.task != jt) {
5828 if (affinity.equals(jt.affinity)) {
5829 return j;
5830 }
5831 jt = r.task;
5832 }
5833 }
5834
5835 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005836 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 return N-1;
5838 }
5839
5840 return -1;
5841 }
5842
5843 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005844 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005846 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5848 "moveTaskToFront()");
5849
5850 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005851 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5852 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005853 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005854 return;
5855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 final long origId = Binder.clearCallingIdentity();
5857 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858 TaskRecord tr = taskForIdLocked(task);
5859 if (tr != null) {
5860 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5861 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005863 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5864 // Caller wants the home activity moved with it. To accomplish this,
5865 // we'll just move the home task to the top first.
5866 mMainStack.moveHomeToFrontLocked();
5867 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005868 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005869 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005871 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5872 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005874 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5875 mMainStack.mUserLeaving = true;
5876 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005877 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5878 // Caller wants the home activity moved with it. To accomplish this,
5879 // we'll just move the home task to the top first.
5880 mMainStack.moveHomeToFrontLocked();
5881 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005882 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 return;
5884 }
5885 }
5886 } finally {
5887 Binder.restoreCallingIdentity(origId);
5888 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005889 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 }
5891 }
5892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 public void moveTaskToBack(int task) {
5894 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5895 "moveTaskToBack()");
5896
5897 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005898 if (mMainStack.mResumedActivity != null
5899 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005900 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5901 Binder.getCallingUid(), "Task to back")) {
5902 return;
5903 }
5904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005906 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 Binder.restoreCallingIdentity(origId);
5908 }
5909 }
5910
5911 /**
5912 * Moves an activity, and all of the other activities within the same task, to the bottom
5913 * of the history stack. The activity's order within the task is unchanged.
5914 *
5915 * @param token A reference to the activity we wish to move
5916 * @param nonRoot If false then this only works if the activity is the root
5917 * of a task; if true it will work for any activity in a task.
5918 * @return Returns true if the move completed, false if not.
5919 */
5920 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005921 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 synchronized(this) {
5923 final long origId = Binder.clearCallingIdentity();
5924 int taskId = getTaskForActivityLocked(token, !nonRoot);
5925 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005926 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 }
5928 Binder.restoreCallingIdentity(origId);
5929 }
5930 return false;
5931 }
5932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 public void moveTaskBackwards(int task) {
5934 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5935 "moveTaskBackwards()");
5936
5937 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005938 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5939 Binder.getCallingUid(), "Task backwards")) {
5940 return;
5941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 final long origId = Binder.clearCallingIdentity();
5943 moveTaskBackwardsLocked(task);
5944 Binder.restoreCallingIdentity(origId);
5945 }
5946 }
5947
5948 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005949 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 }
5951
5952 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5953 synchronized(this) {
5954 return getTaskForActivityLocked(token, onlyRoot);
5955 }
5956 }
5957
5958 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005959 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 TaskRecord lastTask = null;
5961 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005962 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005963 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 if (!onlyRoot || lastTask != r.task) {
5965 return r.task.taskId;
5966 }
5967 return -1;
5968 }
5969 lastTask = r.task;
5970 }
5971
5972 return -1;
5973 }
5974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 // =========================================================
5976 // THUMBNAILS
5977 // =========================================================
5978
5979 public void reportThumbnail(IBinder token,
5980 Bitmap thumbnail, CharSequence description) {
5981 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5982 final long origId = Binder.clearCallingIdentity();
5983 sendPendingThumbnail(null, token, thumbnail, description, true);
5984 Binder.restoreCallingIdentity(origId);
5985 }
5986
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005987 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 Bitmap thumbnail, CharSequence description, boolean always) {
5989 TaskRecord task = null;
5990 ArrayList receivers = null;
5991
5992 //System.out.println("Send pending thumbnail: " + r);
5993
5994 synchronized(this) {
5995 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005996 r = mMainStack.isInStackLocked(token);
5997 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 return;
5999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006001 if (thumbnail == null && r.thumbHolder != null) {
6002 thumbnail = r.thumbHolder.lastThumbnail;
6003 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
6005 if (thumbnail == null && !always) {
6006 // If there is no thumbnail, and this entry is not actually
6007 // going away, then abort for now and pick up the next
6008 // thumbnail we get.
6009 return;
6010 }
6011 task = r.task;
6012
6013 int N = mPendingThumbnails.size();
6014 int i=0;
6015 while (i<N) {
6016 PendingThumbnailsRecord pr =
6017 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6018 //System.out.println("Looking in " + pr.pendingRecords);
6019 if (pr.pendingRecords.remove(r)) {
6020 if (receivers == null) {
6021 receivers = new ArrayList();
6022 }
6023 receivers.add(pr);
6024 if (pr.pendingRecords.size() == 0) {
6025 pr.finished = true;
6026 mPendingThumbnails.remove(i);
6027 N--;
6028 continue;
6029 }
6030 }
6031 i++;
6032 }
6033 }
6034
6035 if (receivers != null) {
6036 final int N = receivers.size();
6037 for (int i=0; i<N; i++) {
6038 try {
6039 PendingThumbnailsRecord pr =
6040 (PendingThumbnailsRecord)receivers.get(i);
6041 pr.receiver.newThumbnail(
6042 task != null ? task.taskId : -1, thumbnail, description);
6043 if (pr.finished) {
6044 pr.receiver.finished();
6045 }
6046 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006047 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 }
6049 }
6050 }
6051 }
6052
6053 // =========================================================
6054 // CONTENT PROVIDERS
6055 // =========================================================
6056
Jeff Brown10e89712011-07-08 18:52:57 -07006057 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6058 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006060 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006061 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006062 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 } catch (RemoteException ex) {
6064 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006065 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006066 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6067 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006069 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 for (int i=0; i<N; i++) {
6071 ProviderInfo cpi =
6072 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006073 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6074 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006075 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006076 // This is a singleton provider, but a user besides the
6077 // default user is asking to initialize a process it runs
6078 // in... well, no, it doesn't actually run in this process,
6079 // it runs in the process of the default user. Get rid of it.
6080 providers.remove(i);
6081 N--;
6082 continue;
6083 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006084
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006085 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006086 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006088 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006089 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006091 if (DEBUG_MU)
6092 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 app.pubProviders.put(cpi.name, cpr);
6094 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006095 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 }
6097 }
6098 return providers;
6099 }
6100
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006101 /**
6102 * Check if {@link ProcessRecord} has a possible chance at accessing the
6103 * given {@link ProviderInfo}. Final permission checking is always done
6104 * in {@link ContentProvider}.
6105 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006107 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006109 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006111 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006112 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 return null;
6114 }
6115 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006116 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 == PackageManager.PERMISSION_GRANTED) {
6118 return null;
6119 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006120
6121 PathPermission[] pps = cpi.pathPermissions;
6122 if (pps != null) {
6123 int i = pps.length;
6124 while (i > 0) {
6125 i--;
6126 PathPermission pp = pps[i];
6127 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006128 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006129 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006130 return null;
6131 }
6132 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006133 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006134 == PackageManager.PERMISSION_GRANTED) {
6135 return null;
6136 }
6137 }
6138 }
6139
Dianne Hackbornb424b632010-08-18 15:59:05 -07006140 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6141 if (perms != null) {
6142 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6143 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6144 return null;
6145 }
6146 }
6147 }
6148
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006149 String msg;
6150 if (!cpi.exported) {
6151 msg = "Permission Denial: opening provider " + cpi.name
6152 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6153 + ", uid=" + callingUid + ") that is not exported from uid "
6154 + cpi.applicationInfo.uid;
6155 } else {
6156 msg = "Permission Denial: opening provider " + cpi.name
6157 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6158 + ", uid=" + callingUid + ") requires "
6159 + cpi.readPermission + " or " + cpi.writePermission;
6160 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006161 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 return msg;
6163 }
6164
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6166 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006167 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006168 for (int i=0; i<r.conProviders.size(); i++) {
6169 ContentProviderConnection conn = r.conProviders.get(i);
6170 if (conn.provider == cpr) {
6171 if (DEBUG_PROVIDER) Slog.v(TAG,
6172 "Adding provider requested by "
6173 + r.processName + " from process "
6174 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6175 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6176 if (stable) {
6177 conn.stableCount++;
6178 conn.numStableIncs++;
6179 } else {
6180 conn.unstableCount++;
6181 conn.numUnstableIncs++;
6182 }
6183 return conn;
6184 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006185 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006186 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6187 if (stable) {
6188 conn.stableCount = 1;
6189 conn.numStableIncs = 1;
6190 } else {
6191 conn.unstableCount = 1;
6192 conn.numUnstableIncs = 1;
6193 }
6194 cpr.connections.add(conn);
6195 r.conProviders.add(conn);
6196 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006197 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006198 cpr.addExternalProcessHandleLocked(externalProcessToken);
6199 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006200 }
6201
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006202 boolean decProviderCountLocked(ContentProviderConnection conn,
6203 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6204 if (conn != null) {
6205 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006206 if (DEBUG_PROVIDER) Slog.v(TAG,
6207 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006208 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006209 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006210 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6211 if (stable) {
6212 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006213 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006214 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006215 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006216 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6217 cpr.connections.remove(conn);
6218 conn.client.conProviders.remove(conn);
6219 return true;
6220 }
6221 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006222 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006223 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006224 return false;
6225 }
6226
Amith Yamasani742a6712011-05-04 14:49:28 -07006227 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006228 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006230 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 ProviderInfo cpi = null;
6232
6233 synchronized(this) {
6234 ProcessRecord r = null;
6235 if (caller != null) {
6236 r = getRecordForAppLocked(caller);
6237 if (r == null) {
6238 throw new SecurityException(
6239 "Unable to find app for caller " + caller
6240 + " (pid=" + Binder.getCallingPid()
6241 + ") when getting content provider " + name);
6242 }
6243 }
6244
6245 // First check if this content provider has been published...
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006246 int userId = UserHandle.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006247 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006248 boolean providerRunning = cpr != null;
6249 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006251 String msg;
6252 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6253 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
6255
6256 if (r != null && cpr.canRunHere(r)) {
6257 // This provider has been published or is in the process
6258 // of being published... but it is also allowed to run
6259 // in the caller's process, so don't make a connection
6260 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006261 ContentProviderHolder holder = cpr.newHolder(null);
6262 // don't give caller the provider object, it needs
6263 // to make its own.
6264 holder.provider = null;
6265 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 }
6267
6268 final long origId = Binder.clearCallingIdentity();
6269
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006270 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006272 conn = incProviderCountLocked(r, cpr, token, stable);
6273 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006274 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006275 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006276 // make sure to count it as being accessed and thus
6277 // back up on the LRU list. This is good because
6278 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006279 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006280 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006281 }
6282
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006283 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006284 if (false) {
6285 if (cpr.name.flattenToShortString().equals(
6286 "com.android.providers.calendar/.CalendarProvider2")) {
6287 Slog.v(TAG, "****************** KILLING "
6288 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006289 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006290 }
6291 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006292 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006293 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6294 // NOTE: there is still a race here where a signal could be
6295 // pending on the process even though we managed to update its
6296 // adj level. Not sure what to do about this, but at least
6297 // the race is now smaller.
6298 if (!success) {
6299 // Uh oh... it looks like the provider's process
6300 // has been killed on us. We need to wait for a new
6301 // process to be started, and make sure its death
6302 // doesn't kill our process.
6303 Slog.i(TAG,
6304 "Existing provider " + cpr.name.flattenToShortString()
6305 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006306 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006307 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006308 if (!lastRef) {
6309 // This wasn't the last ref our process had on
6310 // the provider... we have now been killed, bail.
6311 return null;
6312 }
6313 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006314 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 }
6317
6318 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006321 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006322 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006324 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006325 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006326 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 } catch (RemoteException ex) {
6328 }
6329 if (cpi == null) {
6330 return null;
6331 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006332 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6333 cpi.name, cpi.flags);
6334 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006335 userId = 0;
6336 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006337 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006338
Dianne Hackbornb424b632010-08-18 15:59:05 -07006339 String msg;
6340 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6341 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 }
6343
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006344 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006345 && !cpi.processName.equals("system")) {
6346 // If this content provider does not run in the system
6347 // process, and the system is not yet ready to run other
6348 // processes, then fail fast instead of hanging.
6349 throw new IllegalArgumentException(
6350 "Attempt to launch content provider before system ready");
6351 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006352
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006353 // Make sure that the user who owns this provider is started. If not,
6354 // we don't want to allow it to run.
6355 if (mStartedUsers.get(userId) == null) {
6356 Slog.w(TAG, "Unable to launch app "
6357 + cpi.applicationInfo.packageName + "/"
6358 + cpi.applicationInfo.uid + " for provider "
6359 + name + ": user " + userId + " is stopped");
6360 return null;
6361 }
6362
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006363 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006364 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 final boolean firstClass = cpr == null;
6366 if (firstClass) {
6367 try {
6368 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006369 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 getApplicationInfo(
6371 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006372 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006374 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 + cpi.name);
6376 return null;
6377 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006378 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006379 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 } catch (RemoteException ex) {
6381 // pm is in same process, this will never happen.
6382 }
6383 }
6384
6385 if (r != null && cpr.canRunHere(r)) {
6386 // If this is a multiprocess provider, then just return its
6387 // info and allow the caller to instantiate it. Only do
6388 // this if the provider is the same user as the caller's
6389 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006390 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 }
6392
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006393 if (DEBUG_PROVIDER) {
6394 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006395 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006396 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 }
6398
6399 // This is single process, and our app is now connecting to it.
6400 // See if we are already in the process of launching this
6401 // provider.
6402 final int N = mLaunchingProviders.size();
6403 int i;
6404 for (i=0; i<N; i++) {
6405 if (mLaunchingProviders.get(i) == cpr) {
6406 break;
6407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
6409
6410 // If the provider is not already being launched, then get it
6411 // started.
6412 if (i >= N) {
6413 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006414
6415 try {
6416 // Content provider is now in use, its package can't be stopped.
6417 try {
6418 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006419 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006420 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006421 } catch (IllegalArgumentException e) {
6422 Slog.w(TAG, "Failed trying to unstop package "
6423 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006424 }
6425
6426 ProcessRecord proc = startProcessLocked(cpi.processName,
6427 cpr.appInfo, false, 0, "content provider",
6428 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006429 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006430 if (proc == null) {
6431 Slog.w(TAG, "Unable to launch app "
6432 + cpi.applicationInfo.packageName + "/"
6433 + cpi.applicationInfo.uid + " for provider "
6434 + name + ": process is bad");
6435 return null;
6436 }
6437 cpr.launchingApp = proc;
6438 mLaunchingProviders.add(cpr);
6439 } finally {
6440 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 }
6443
6444 // Make sure the provider is published (the same provider class
6445 // may be published under multiple names).
6446 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006447 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006449
Amith Yamasani742a6712011-05-04 14:49:28 -07006450 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006451 conn = incProviderCountLocked(r, cpr, token, stable);
6452 if (conn != null) {
6453 conn.waiting = true;
6454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 }
6456 }
6457
6458 // Wait for the provider to be published...
6459 synchronized (cpr) {
6460 while (cpr.provider == null) {
6461 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006462 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 + cpi.applicationInfo.packageName + "/"
6464 + cpi.applicationInfo.uid + " for provider "
6465 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006466 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 cpi.applicationInfo.packageName,
6468 cpi.applicationInfo.uid, name);
6469 return null;
6470 }
6471 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006472 if (DEBUG_MU) {
6473 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6474 + cpr.launchingApp);
6475 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006476 if (conn != null) {
6477 conn.waiting = true;
6478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 cpr.wait();
6480 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006481 } finally {
6482 if (conn != null) {
6483 conn.waiting = false;
6484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 }
6486 }
6487 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006488 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
6490
6491 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006492 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006493 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 if (caller == null) {
6495 String msg = "null IApplicationThread when getting content provider "
6496 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006497 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 throw new SecurityException(msg);
6499 }
6500
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006501 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 }
6503
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006504 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6505 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6506 "Do not have permission in call getContentProviderExternal()");
6507 return getContentProviderExternalUnchecked(name, token);
6508 }
6509
6510 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006511 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 /**
6515 * Drop a content provider from a ProcessRecord's bookkeeping
6516 * @param cpr
6517 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006518 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006519 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006521 ContentProviderConnection conn;
6522 try {
6523 conn = (ContentProviderConnection)connection;
6524 } catch (ClassCastException e) {
6525 String msg ="removeContentProvider: " + connection
6526 + " not a ContentProviderConnection";
6527 Slog.w(TAG, msg);
6528 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006530 if (conn == null) {
6531 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006533 if (decProviderCountLocked(conn, null, null, stable)) {
6534 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 }
6537 }
6538
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006539 public void removeContentProviderExternal(String name, IBinder token) {
6540 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6541 "Do not have permission in call removeContentProviderExternal()");
6542 removeContentProviderExternalUnchecked(name, token);
6543 }
6544
6545 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006547 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6548 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 if(cpr == null) {
6550 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006551 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 return;
6553 }
6554
6555 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006556 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006557 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6558 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006559 if (localCpr.hasExternalProcessHandles()) {
6560 if (localCpr.removeExternalProcessHandleLocked(token)) {
6561 updateOomAdjLocked();
6562 } else {
6563 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6564 + " with no external reference for token: "
6565 + token + ".");
6566 }
6567 } else {
6568 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6569 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 }
6572 }
6573
6574 public final void publishContentProviders(IApplicationThread caller,
6575 List<ContentProviderHolder> providers) {
6576 if (providers == null) {
6577 return;
6578 }
6579
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006580 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006581 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006583 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006584 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 if (r == null) {
6586 throw new SecurityException(
6587 "Unable to find app for caller " + caller
6588 + " (pid=" + Binder.getCallingPid()
6589 + ") when publishing content providers");
6590 }
6591
6592 final long origId = Binder.clearCallingIdentity();
6593
6594 final int N = providers.size();
6595 for (int i=0; i<N; i++) {
6596 ContentProviderHolder src = providers.get(i);
6597 if (src == null || src.info == null || src.provider == null) {
6598 continue;
6599 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006600 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006601 if (DEBUG_MU)
6602 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006604 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006605 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 String names[] = dst.info.authority.split(";");
6607 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006608 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
6610
6611 int NL = mLaunchingProviders.size();
6612 int j;
6613 for (j=0; j<NL; j++) {
6614 if (mLaunchingProviders.get(j) == dst) {
6615 mLaunchingProviders.remove(j);
6616 j--;
6617 NL--;
6618 }
6619 }
6620 synchronized (dst) {
6621 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006622 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 dst.notifyAll();
6624 }
6625 updateOomAdjLocked(r);
6626 }
6627 }
6628
6629 Binder.restoreCallingIdentity(origId);
6630 }
6631 }
6632
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006633 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6634 ContentProviderConnection conn;
6635 try {
6636 conn = (ContentProviderConnection)connection;
6637 } catch (ClassCastException e) {
6638 String msg ="refContentProvider: " + connection
6639 + " not a ContentProviderConnection";
6640 Slog.w(TAG, msg);
6641 throw new IllegalArgumentException(msg);
6642 }
6643 if (conn == null) {
6644 throw new NullPointerException("connection is null");
6645 }
6646
6647 synchronized (this) {
6648 if (stable > 0) {
6649 conn.numStableIncs += stable;
6650 }
6651 stable = conn.stableCount + stable;
6652 if (stable < 0) {
6653 throw new IllegalStateException("stableCount < 0: " + stable);
6654 }
6655
6656 if (unstable > 0) {
6657 conn.numUnstableIncs += unstable;
6658 }
6659 unstable = conn.unstableCount + unstable;
6660 if (unstable < 0) {
6661 throw new IllegalStateException("unstableCount < 0: " + unstable);
6662 }
6663
6664 if ((stable+unstable) <= 0) {
6665 throw new IllegalStateException("ref counts can't go to zero here: stable="
6666 + stable + " unstable=" + unstable);
6667 }
6668 conn.stableCount = stable;
6669 conn.unstableCount = unstable;
6670 return !conn.dead;
6671 }
6672 }
6673
6674 public void unstableProviderDied(IBinder connection) {
6675 ContentProviderConnection conn;
6676 try {
6677 conn = (ContentProviderConnection)connection;
6678 } catch (ClassCastException e) {
6679 String msg ="refContentProvider: " + connection
6680 + " not a ContentProviderConnection";
6681 Slog.w(TAG, msg);
6682 throw new IllegalArgumentException(msg);
6683 }
6684 if (conn == null) {
6685 throw new NullPointerException("connection is null");
6686 }
6687
6688 // Safely retrieve the content provider associated with the connection.
6689 IContentProvider provider;
6690 synchronized (this) {
6691 provider = conn.provider.provider;
6692 }
6693
6694 if (provider == null) {
6695 // Um, yeah, we're way ahead of you.
6696 return;
6697 }
6698
6699 // Make sure the caller is being honest with us.
6700 if (provider.asBinder().pingBinder()) {
6701 // Er, no, still looks good to us.
6702 synchronized (this) {
6703 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6704 + " says " + conn + " died, but we don't agree");
6705 return;
6706 }
6707 }
6708
6709 // Well look at that! It's dead!
6710 synchronized (this) {
6711 if (conn.provider.provider != provider) {
6712 // But something changed... good enough.
6713 return;
6714 }
6715
6716 ProcessRecord proc = conn.provider.proc;
6717 if (proc == null || proc.thread == null) {
6718 // Seems like the process is already cleaned up.
6719 return;
6720 }
6721
6722 // As far as we're concerned, this is just like receiving a
6723 // death notification... just a bit prematurely.
6724 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6725 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006726 final long ident = Binder.clearCallingIdentity();
6727 try {
6728 appDiedLocked(proc, proc.pid, proc.thread);
6729 } finally {
6730 Binder.restoreCallingIdentity(ident);
6731 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006732 }
6733 }
6734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006736 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006737 synchronized (mSelf) {
6738 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6739 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006740 if (providers != null) {
6741 for (int i=providers.size()-1; i>=0; i--) {
6742 ProviderInfo pi = (ProviderInfo)providers.get(i);
6743 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6744 Slog.w(TAG, "Not installing system proc provider " + pi.name
6745 + ": not system .apk");
6746 providers.remove(i);
6747 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006748 }
6749 }
6750 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006751 if (providers != null) {
6752 mSystemThread.installSystemProviders(providers);
6753 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006754
6755 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006756
6757 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 }
6759
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006760 /**
6761 * Allows app to retrieve the MIME type of a URI without having permission
6762 * to access its content provider.
6763 *
6764 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6765 *
6766 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6767 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6768 */
6769 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006770 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006771 final String name = uri.getAuthority();
6772 final long ident = Binder.clearCallingIdentity();
6773 ContentProviderHolder holder = null;
6774
6775 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006776 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006777 if (holder != null) {
6778 return holder.provider.getType(uri);
6779 }
6780 } catch (RemoteException e) {
6781 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6782 return null;
6783 } finally {
6784 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006785 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006786 }
6787 Binder.restoreCallingIdentity(ident);
6788 }
6789
6790 return null;
6791 }
6792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 // =========================================================
6794 // GLOBAL MANAGEMENT
6795 // =========================================================
6796
6797 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006798 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 String proc = customProcess != null ? customProcess : info.processName;
6800 BatteryStatsImpl.Uid.Proc ps = null;
6801 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006802 int uid = info.uid;
6803 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006804 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006805 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6806 uid = 0;
6807 while (true) {
6808 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6809 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6810 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6811 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006812 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006813 mNextIsolatedProcessUid++;
6814 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6815 // No process for this uid, use it.
6816 break;
6817 }
6818 stepsLeft--;
6819 if (stepsLeft <= 0) {
6820 return null;
6821 }
6822 }
6823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 synchronized (stats) {
6825 ps = stats.getProcessStatsLocked(info.uid, proc);
6826 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006827 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 }
6829
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006830 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6831 ProcessRecord app;
6832 if (!isolated) {
6833 app = getProcessRecordLocked(info.processName, info.uid);
6834 } else {
6835 app = null;
6836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837
6838 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006839 app = newProcessRecordLocked(null, info, null, isolated);
6840 mProcessNames.put(info.processName, app.uid, app);
6841 if (isolated) {
6842 mIsolatedProcesses.put(app.uid, app);
6843 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006844 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 }
6846
Dianne Hackborne7f97212011-02-24 14:40:20 -08006847 // This package really, really can not be stopped.
6848 try {
6849 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006850 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006851 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006852 } catch (IllegalArgumentException e) {
6853 Slog.w(TAG, "Failed trying to unstop package "
6854 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006855 }
6856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6858 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6859 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006860 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 }
6862 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6863 mPersistentStartingProcesses.add(app);
6864 startProcessLocked(app, "added application", app.processName);
6865 }
6866
6867 return app;
6868 }
6869
6870 public void unhandledBack() {
6871 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6872 "unhandledBack()");
6873
6874 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006875 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006876 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 TAG, "Performing unhandledBack(): stack size = " + count);
6878 if (count > 1) {
6879 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006880 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6882 Binder.restoreCallingIdentity(origId);
6883 }
6884 }
6885 }
6886
6887 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006888 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006890 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 ParcelFileDescriptor pfd = null;
6892 if (cph != null) {
6893 // We record the binder invoker's uid in thread-local storage before
6894 // going to the content provider to open the file. Later, in the code
6895 // that handles all permissions checks, we look for this uid and use
6896 // that rather than the Activity Manager's own uid. The effect is that
6897 // we do the check against the caller's permissions even though it looks
6898 // to the content provider like the Activity Manager itself is making
6899 // the request.
6900 sCallerIdentity.set(new Identity(
6901 Binder.getCallingPid(), Binder.getCallingUid()));
6902 try {
6903 pfd = cph.provider.openFile(uri, "r");
6904 } catch (FileNotFoundException e) {
6905 // do nothing; pfd will be returned null
6906 } finally {
6907 // Ensure that whatever happens, we clean up the identity state
6908 sCallerIdentity.remove();
6909 }
6910
6911 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006912 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006914 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916 return pfd;
6917 }
6918
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006919 // Actually is sleeping or shutting down or whatever else in the future
6920 // is an inactive state.
6921 public boolean isSleeping() {
6922 return mSleeping || mShuttingDown;
6923 }
6924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006926 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6927 != PackageManager.PERMISSION_GRANTED) {
6928 throw new SecurityException("Requires permission "
6929 + android.Manifest.permission.DEVICE_POWER);
6930 }
6931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006933 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006934 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006936 if (!mSleeping) {
6937 mSleeping = true;
6938 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006939
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006940 // Initialize the wake times of all processes.
6941 checkExcessivePowerUsageLocked(false);
6942 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6943 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6944 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 }
6947 }
6948
Dianne Hackborn55280a92009-05-07 15:53:46 -07006949 public boolean shutdown(int timeout) {
6950 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6951 != PackageManager.PERMISSION_GRANTED) {
6952 throw new SecurityException("Requires permission "
6953 + android.Manifest.permission.SHUTDOWN);
6954 }
6955
6956 boolean timedout = false;
6957
6958 synchronized(this) {
6959 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006960 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006961
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006962 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006963 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006964 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006965 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006966 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006967 long delay = endTime - System.currentTimeMillis();
6968 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006969 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006970 timedout = true;
6971 break;
6972 }
6973 try {
6974 this.wait();
6975 } catch (InterruptedException e) {
6976 }
6977 }
6978 }
6979 }
6980
6981 mUsageStatsService.shutdown();
6982 mBatteryStatsService.shutdown();
6983
6984 return timedout;
6985 }
6986
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006987 public final void activitySlept(IBinder token) {
6988 if (localLOGV) Slog.v(
6989 TAG, "Activity slept: token=" + token);
6990
6991 ActivityRecord r = null;
6992
6993 final long origId = Binder.clearCallingIdentity();
6994
6995 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006996 r = mMainStack.isInStackLocked(token);
6997 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006998 mMainStack.activitySleptLocked(r);
6999 }
7000 }
7001
7002 Binder.restoreCallingIdentity(origId);
7003 }
7004
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007005 private void comeOutOfSleepIfNeededLocked() {
7006 if (!mWentToSleep && !mLockScreenShown) {
7007 if (mSleeping) {
7008 mSleeping = false;
7009 mMainStack.awakeFromSleepingLocked();
7010 mMainStack.resumeTopActivityLocked(null);
7011 }
7012 }
7013 }
7014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007016 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7017 != PackageManager.PERMISSION_GRANTED) {
7018 throw new SecurityException("Requires permission "
7019 + android.Manifest.permission.DEVICE_POWER);
7020 }
7021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007023 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007024 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007025 comeOutOfSleepIfNeededLocked();
7026 }
7027 }
7028
Jeff Brownc042ee22012-05-08 13:03:42 -07007029 private void updateEventDispatchingLocked() {
7030 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7031 }
7032
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007033 public void setLockScreenShown(boolean shown) {
7034 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7035 != PackageManager.PERMISSION_GRANTED) {
7036 throw new SecurityException("Requires permission "
7037 + android.Manifest.permission.DEVICE_POWER);
7038 }
7039
7040 synchronized(this) {
7041 mLockScreenShown = shown;
7042 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 }
7044 }
7045
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007046 public void stopAppSwitches() {
7047 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7048 != PackageManager.PERMISSION_GRANTED) {
7049 throw new SecurityException("Requires permission "
7050 + android.Manifest.permission.STOP_APP_SWITCHES);
7051 }
7052
7053 synchronized(this) {
7054 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7055 + APP_SWITCH_DELAY_TIME;
7056 mDidAppSwitch = false;
7057 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7058 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7059 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7060 }
7061 }
7062
7063 public void resumeAppSwitches() {
7064 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7065 != PackageManager.PERMISSION_GRANTED) {
7066 throw new SecurityException("Requires permission "
7067 + android.Manifest.permission.STOP_APP_SWITCHES);
7068 }
7069
7070 synchronized(this) {
7071 // Note that we don't execute any pending app switches... we will
7072 // let those wait until either the timeout, or the next start
7073 // activity request.
7074 mAppSwitchesAllowedTime = 0;
7075 }
7076 }
7077
7078 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7079 String name) {
7080 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7081 return true;
7082 }
7083
7084 final int perm = checkComponentPermission(
7085 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007086 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007087 if (perm == PackageManager.PERMISSION_GRANTED) {
7088 return true;
7089 }
7090
Joe Onorato8a9b2202010-02-26 18:56:32 -08007091 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007092 return false;
7093 }
7094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 public void setDebugApp(String packageName, boolean waitForDebugger,
7096 boolean persistent) {
7097 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7098 "setDebugApp()");
7099
7100 // Note that this is not really thread safe if there are multiple
7101 // callers into it at the same time, but that's not a situation we
7102 // care about.
7103 if (persistent) {
7104 final ContentResolver resolver = mContext.getContentResolver();
7105 Settings.System.putString(
7106 resolver, Settings.System.DEBUG_APP,
7107 packageName);
7108 Settings.System.putInt(
7109 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7110 waitForDebugger ? 1 : 0);
7111 }
7112
7113 synchronized (this) {
7114 if (!persistent) {
7115 mOrigDebugApp = mDebugApp;
7116 mOrigWaitForDebugger = mWaitForDebugger;
7117 }
7118 mDebugApp = packageName;
7119 mWaitForDebugger = waitForDebugger;
7120 mDebugTransient = !persistent;
7121 if (packageName != null) {
7122 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007123 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 Binder.restoreCallingIdentity(origId);
7125 }
7126 }
7127 }
7128
Siva Velusamy92a8b222012-03-09 16:24:04 -08007129 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7130 synchronized (this) {
7131 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7132 if (!isDebuggable) {
7133 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7134 throw new SecurityException("Process not debuggable: " + app.packageName);
7135 }
7136 }
7137
7138 mOpenGlTraceApp = processName;
7139 }
7140 }
7141
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007142 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7143 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7144 synchronized (this) {
7145 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7146 if (!isDebuggable) {
7147 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7148 throw new SecurityException("Process not debuggable: " + app.packageName);
7149 }
7150 }
7151 mProfileApp = processName;
7152 mProfileFile = profileFile;
7153 if (mProfileFd != null) {
7154 try {
7155 mProfileFd.close();
7156 } catch (IOException e) {
7157 }
7158 mProfileFd = null;
7159 }
7160 mProfileFd = profileFd;
7161 mProfileType = 0;
7162 mAutoStopProfiler = autoStopProfiler;
7163 }
7164 }
7165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 public void setAlwaysFinish(boolean enabled) {
7167 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7168 "setAlwaysFinish()");
7169
7170 Settings.System.putInt(
7171 mContext.getContentResolver(),
7172 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7173
7174 synchronized (this) {
7175 mAlwaysFinishActivities = enabled;
7176 }
7177 }
7178
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007179 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007181 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007183 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 }
7185 }
7186
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007187 public boolean isUserAMonkey() {
7188 // For now the fact that there is a controller implies
7189 // we have a monkey.
7190 synchronized (this) {
7191 return mController != null;
7192 }
7193 }
7194
Jeff Sharkeya4620792011-05-20 15:29:23 -07007195 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007196 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7197 "registerProcessObserver()");
7198 synchronized (this) {
7199 mProcessObservers.register(observer);
7200 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007201 }
7202
7203 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007204 synchronized (this) {
7205 mProcessObservers.unregister(observer);
7206 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007207 }
7208
Daniel Sandler69a48172010-06-23 16:29:36 -04007209 public void setImmersive(IBinder token, boolean immersive) {
7210 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007211 ActivityRecord r = mMainStack.isInStackLocked(token);
7212 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007213 throw new IllegalArgumentException();
7214 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007215 r.immersive = immersive;
7216 }
7217 }
7218
7219 public boolean isImmersive(IBinder token) {
7220 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007221 ActivityRecord r = mMainStack.isInStackLocked(token);
7222 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007223 throw new IllegalArgumentException();
7224 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007225 return r.immersive;
7226 }
7227 }
7228
7229 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007230 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007231 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007232 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007233 return (r != null) ? r.immersive : false;
7234 }
7235 }
7236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 public final void enterSafeMode() {
7238 synchronized(this) {
7239 // It only makes sense to do this before the system is ready
7240 // and started launching other packages.
7241 if (!mSystemReady) {
7242 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007243 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 } catch (RemoteException e) {
7245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 }
7247 }
7248 }
7249
Jeff Brownb09abc12011-01-13 21:08:27 -08007250 public final void showSafeModeOverlay() {
7251 View v = LayoutInflater.from(mContext).inflate(
7252 com.android.internal.R.layout.safe_mode, null);
7253 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7254 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7255 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7256 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007257 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007258 lp.format = v.getBackground().getOpacity();
7259 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7260 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7261 ((WindowManager)mContext.getSystemService(
7262 Context.WINDOW_SERVICE)).addView(v, lp);
7263 }
7264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 public void noteWakeupAlarm(IIntentSender sender) {
7266 if (!(sender instanceof PendingIntentRecord)) {
7267 return;
7268 }
7269 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7270 synchronized (stats) {
7271 if (mBatteryStatsService.isOnBattery()) {
7272 mBatteryStatsService.enforceCallingPermission();
7273 PendingIntentRecord rec = (PendingIntentRecord)sender;
7274 int MY_UID = Binder.getCallingUid();
7275 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7276 BatteryStatsImpl.Uid.Pkg pkg =
7277 stats.getPackageStatsLocked(uid, rec.key.packageName);
7278 pkg.incWakeupsLocked();
7279 }
7280 }
7281 }
7282
Dianne Hackborn64825172011-03-02 21:32:58 -08007283 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007285 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007287 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 // XXX Note: don't acquire main activity lock here, because the window
7289 // manager calls in with its locks held.
7290
7291 boolean killed = false;
7292 synchronized (mPidsSelfLocked) {
7293 int[] types = new int[pids.length];
7294 int worstType = 0;
7295 for (int i=0; i<pids.length; i++) {
7296 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7297 if (proc != null) {
7298 int type = proc.setAdj;
7299 types[i] = type;
7300 if (type > worstType) {
7301 worstType = type;
7302 }
7303 }
7304 }
7305
Dianne Hackborn64825172011-03-02 21:32:58 -08007306 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007308 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7309 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007310 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007312
7313 // If this is not a secure call, don't let it kill processes that
7314 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007315 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7316 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007317 }
7318
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007319 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 for (int i=0; i<pids.length; i++) {
7321 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7322 if (proc == null) {
7323 continue;
7324 }
7325 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007326 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007327 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007328 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7329 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007331 proc.killedBackground = true;
7332 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 }
7334 }
7335 }
7336 return killed;
7337 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007338
7339 @Override
7340 public boolean killProcessesBelowForeground(String reason) {
7341 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7342 throw new SecurityException("killProcessesBelowForeground() only available to system");
7343 }
7344
7345 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7346 }
7347
7348 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7349 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7350 throw new SecurityException("killProcessesBelowAdj() only available to system");
7351 }
7352
7353 boolean killed = false;
7354 synchronized (mPidsSelfLocked) {
7355 final int size = mPidsSelfLocked.size();
7356 for (int i = 0; i < size; i++) {
7357 final int pid = mPidsSelfLocked.keyAt(i);
7358 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7359 if (proc == null) continue;
7360
7361 final int adj = proc.setAdj;
7362 if (adj > belowAdj && !proc.killedBackground) {
7363 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7364 EventLog.writeEvent(
7365 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7366 killed = true;
7367 proc.killedBackground = true;
7368 Process.killProcessQuiet(pid);
7369 }
7370 }
7371 }
7372 return killed;
7373 }
7374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 public final void startRunning(String pkg, String cls, String action,
7376 String data) {
7377 synchronized(this) {
7378 if (mStartRunning) {
7379 return;
7380 }
7381 mStartRunning = true;
7382 mTopComponent = pkg != null && cls != null
7383 ? new ComponentName(pkg, cls) : null;
7384 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7385 mTopData = data;
7386 if (!mSystemReady) {
7387 return;
7388 }
7389 }
7390
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007391 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 }
7393
7394 private void retrieveSettings() {
7395 final ContentResolver resolver = mContext.getContentResolver();
7396 String debugApp = Settings.System.getString(
7397 resolver, Settings.System.DEBUG_APP);
7398 boolean waitForDebugger = Settings.System.getInt(
7399 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7400 boolean alwaysFinishActivities = Settings.System.getInt(
7401 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7402
7403 Configuration configuration = new Configuration();
7404 Settings.System.getConfiguration(resolver, configuration);
7405
7406 synchronized (this) {
7407 mDebugApp = mOrigDebugApp = debugApp;
7408 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7409 mAlwaysFinishActivities = alwaysFinishActivities;
7410 // This happens before any activities are started, so we can
7411 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007412 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007413 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 }
7415 }
7416
7417 public boolean testIsSystemReady() {
7418 // no need to synchronize(this) just to read & return the value
7419 return mSystemReady;
7420 }
7421
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007422 private static File getCalledPreBootReceiversFile() {
7423 File dataDir = Environment.getDataDirectory();
7424 File systemDir = new File(dataDir, "system");
7425 File fname = new File(systemDir, "called_pre_boots.dat");
7426 return fname;
7427 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007428
7429 static final int LAST_DONE_VERSION = 10000;
7430
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007431 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7432 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7433 File file = getCalledPreBootReceiversFile();
7434 FileInputStream fis = null;
7435 try {
7436 fis = new FileInputStream(file);
7437 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007438 int fvers = dis.readInt();
7439 if (fvers == LAST_DONE_VERSION) {
7440 String vers = dis.readUTF();
7441 String codename = dis.readUTF();
7442 String build = dis.readUTF();
7443 if (android.os.Build.VERSION.RELEASE.equals(vers)
7444 && android.os.Build.VERSION.CODENAME.equals(codename)
7445 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7446 int num = dis.readInt();
7447 while (num > 0) {
7448 num--;
7449 String pkg = dis.readUTF();
7450 String cls = dis.readUTF();
7451 lastDoneReceivers.add(new ComponentName(pkg, cls));
7452 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007453 }
7454 }
7455 } catch (FileNotFoundException e) {
7456 } catch (IOException e) {
7457 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7458 } finally {
7459 if (fis != null) {
7460 try {
7461 fis.close();
7462 } catch (IOException e) {
7463 }
7464 }
7465 }
7466 return lastDoneReceivers;
7467 }
7468
7469 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7470 File file = getCalledPreBootReceiversFile();
7471 FileOutputStream fos = null;
7472 DataOutputStream dos = null;
7473 try {
7474 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7475 fos = new FileOutputStream(file);
7476 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007477 dos.writeInt(LAST_DONE_VERSION);
7478 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007479 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007480 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007481 dos.writeInt(list.size());
7482 for (int i=0; i<list.size(); i++) {
7483 dos.writeUTF(list.get(i).getPackageName());
7484 dos.writeUTF(list.get(i).getClassName());
7485 }
7486 } catch (IOException e) {
7487 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7488 file.delete();
7489 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007490 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007491 if (dos != null) {
7492 try {
7493 dos.close();
7494 } catch (IOException e) {
7495 // TODO Auto-generated catch block
7496 e.printStackTrace();
7497 }
7498 }
7499 }
7500 }
7501
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007502 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 synchronized(this) {
7504 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007505 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 return;
7507 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007508
7509 // Check to see if there are any update receivers to run.
7510 if (!mDidUpdate) {
7511 if (mWaitingUpdate) {
7512 return;
7513 }
7514 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7515 List<ResolveInfo> ris = null;
7516 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007517 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007518 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007519 } catch (RemoteException e) {
7520 }
7521 if (ris != null) {
7522 for (int i=ris.size()-1; i>=0; i--) {
7523 if ((ris.get(i).activityInfo.applicationInfo.flags
7524 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7525 ris.remove(i);
7526 }
7527 }
7528 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007529
7530 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7531
7532 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007533 for (int i=0; i<ris.size(); i++) {
7534 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007535 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7536 if (lastDoneReceivers.contains(comp)) {
7537 ris.remove(i);
7538 i--;
7539 }
7540 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007541
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007542 for (int i=0; i<ris.size(); i++) {
7543 ActivityInfo ai = ris.get(i).activityInfo;
7544 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7545 doneReceivers.add(comp);
7546 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007547 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007548 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007549 finisher = new IIntentReceiver.Stub() {
7550 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007551 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007552 boolean sticky) {
7553 // The raw IIntentReceiver interface is called
7554 // with the AM lock held, so redispatch to
7555 // execute our code without the lock.
7556 mHandler.post(new Runnable() {
7557 public void run() {
7558 synchronized (ActivityManagerService.this) {
7559 mDidUpdate = true;
7560 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007561 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007562 showBootMessage(mContext.getText(
7563 R.string.android_upgrading_complete),
7564 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007565 systemReady(goingCallback);
7566 }
7567 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007568 }
7569 };
7570 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007571 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007572 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007573 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007574 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007575 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007576 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007577 mWaitingUpdate = true;
7578 }
7579 }
7580 }
7581 if (mWaitingUpdate) {
7582 return;
7583 }
7584 mDidUpdate = true;
7585 }
7586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 mSystemReady = true;
7588 if (!mStartRunning) {
7589 return;
7590 }
7591 }
7592
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007593 ArrayList<ProcessRecord> procsToKill = null;
7594 synchronized(mPidsSelfLocked) {
7595 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7596 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7597 if (!isAllowedWhileBooting(proc.info)){
7598 if (procsToKill == null) {
7599 procsToKill = new ArrayList<ProcessRecord>();
7600 }
7601 procsToKill.add(proc);
7602 }
7603 }
7604 }
7605
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007606 synchronized(this) {
7607 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007608 for (int i=procsToKill.size()-1; i>=0; i--) {
7609 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007610 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007611 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007612 }
7613 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007614
7615 // Now that we have cleaned up any update processes, we
7616 // are ready to start launching real processes and know that
7617 // we won't trample on them any more.
7618 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007619 }
7620
Joe Onorato8a9b2202010-02-26 18:56:32 -08007621 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007622 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007623 SystemClock.uptimeMillis());
7624
7625 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007626 // Make sure we have no pre-ready processes sitting around.
7627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7629 ResolveInfo ri = mContext.getPackageManager()
7630 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007631 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 CharSequence errorMsg = null;
7633 if (ri != null) {
7634 ActivityInfo ai = ri.activityInfo;
7635 ApplicationInfo app = ai.applicationInfo;
7636 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7637 mTopAction = Intent.ACTION_FACTORY_TEST;
7638 mTopData = null;
7639 mTopComponent = new ComponentName(app.packageName,
7640 ai.name);
7641 } else {
7642 errorMsg = mContext.getResources().getText(
7643 com.android.internal.R.string.factorytest_not_system);
7644 }
7645 } else {
7646 errorMsg = mContext.getResources().getText(
7647 com.android.internal.R.string.factorytest_no_action);
7648 }
7649 if (errorMsg != null) {
7650 mTopAction = null;
7651 mTopData = null;
7652 mTopComponent = null;
7653 Message msg = Message.obtain();
7654 msg.what = SHOW_FACTORY_ERROR_MSG;
7655 msg.getData().putCharSequence("msg", errorMsg);
7656 mHandler.sendMessage(msg);
7657 }
7658 }
7659 }
7660
7661 retrieveSettings();
7662
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007663 if (goingCallback != null) goingCallback.run();
7664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 synchronized (this) {
7666 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7667 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007668 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007669 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 if (apps != null) {
7671 int N = apps.size();
7672 int i;
7673 for (i=0; i<N; i++) {
7674 ApplicationInfo info
7675 = (ApplicationInfo)apps.get(i);
7676 if (info != null &&
7677 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007678 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 }
7680 }
7681 }
7682 } catch (RemoteException ex) {
7683 // pm is in same process, this will never happen.
7684 }
7685 }
7686
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007687 // Start up initial activity.
7688 mBooting = true;
7689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007691 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 Message msg = Message.obtain();
7693 msg.what = SHOW_UID_ERROR_MSG;
7694 mHandler.sendMessage(msg);
7695 }
7696 } catch (RemoteException e) {
7697 }
7698
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007699 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 }
7701 }
7702
Dan Egnorb7f03672009-12-09 16:22:32 -08007703 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007704 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007706 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007707 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 startAppProblemLocked(app);
7709 app.stopFreezingAllLocked();
7710 return handleAppCrashLocked(app);
7711 }
7712
Dan Egnorb7f03672009-12-09 16:22:32 -08007713 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007714 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007716 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007717 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7718 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 startAppProblemLocked(app);
7720 app.stopFreezingAllLocked();
7721 }
7722
7723 /**
7724 * Generate a process error record, suitable for attachment to a ProcessRecord.
7725 *
7726 * @param app The ProcessRecord in which the error occurred.
7727 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7728 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007729 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 * @param shortMsg Short message describing the crash.
7731 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007732 * @param stackTrace Full crash stack trace, may be null.
7733 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 * @return Returns a fully-formed AppErrorStateInfo record.
7735 */
7736 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007737 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 report.condition = condition;
7741 report.processName = app.processName;
7742 report.pid = app.pid;
7743 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007744 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 report.shortMsg = shortMsg;
7746 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007747 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748
7749 return report;
7750 }
7751
Dan Egnor42471dd2010-01-07 17:25:22 -08007752 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 synchronized (this) {
7754 app.crashing = false;
7755 app.crashingReport = null;
7756 app.notResponding = false;
7757 app.notRespondingReport = null;
7758 if (app.anrDialog == fromDialog) {
7759 app.anrDialog = null;
7760 }
7761 if (app.waitDialog == fromDialog) {
7762 app.waitDialog = null;
7763 }
7764 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007765 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007766 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007767 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7768 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007769 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 }
7772 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007773
Dan Egnorb7f03672009-12-09 16:22:32 -08007774 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007775 if (mHeadless) {
7776 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7777 return false;
7778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 long now = SystemClock.uptimeMillis();
7780
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007781 Long crashTime;
7782 if (!app.isolated) {
7783 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7784 } else {
7785 crashTime = null;
7786 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007787 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007789 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007791 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007792 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007793 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7794 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007796 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007798 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 }
7800 }
7801 if (!app.persistent) {
7802 // We don't want to start this process again until the user
7803 // explicitly does so... but for persistent process, we really
7804 // need to keep it running. If a persistent process is actually
7805 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007806 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007808 if (!app.isolated) {
7809 // XXX We don't have a way to mark isolated processes
7810 // as bad, since they don't have a peristent identity.
7811 mBadProcesses.put(app.info.processName, app.uid, now);
7812 mProcessCrashTimes.remove(app.info.processName, app.uid);
7813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007816 // Don't let services in this process be restarted and potentially
7817 // annoy the user repeatedly. Unless it is persistent, since those
7818 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007819 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007820 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 return false;
7822 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007823 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007824 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007825 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007826 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007827 // If the top running activity is from this crashing
7828 // process, then terminate it to avoid getting in a loop.
7829 Slog.w(TAG, " Force finishing activity "
7830 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007831 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007832 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007833 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007834 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007835 // stopped, to avoid a situation where one will get
7836 // re-start our crashing activity once it gets resumed again.
7837 index--;
7838 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007839 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007840 if (r.state == ActivityState.RESUMED
7841 || r.state == ActivityState.PAUSING
7842 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007843 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007844 Slog.w(TAG, " Force finishing activity "
7845 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007846 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007847 Activity.RESULT_CANCELED, null, "crashed");
7848 }
7849 }
7850 }
7851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
7853
7854 // Bump up the crash count of any services currently running in the proc.
7855 if (app.services.size() != 0) {
7856 // Any services running in the application need to be placed
7857 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007858 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007860 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 sr.crashCount++;
7862 }
7863 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007864
7865 // If the crashing process is what we consider to be the "home process" and it has been
7866 // replaced by a third-party app, clear the package preferred activities from packages
7867 // with a home activity running in the process to prevent a repeatedly crashing app
7868 // from blocking the user to manually clear the list.
7869 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7870 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7871 Iterator it = mHomeProcess.activities.iterator();
7872 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007873 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007874 if (r.isHomeActivity) {
7875 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7876 try {
7877 ActivityThread.getPackageManager()
7878 .clearPackagePreferredActivities(r.packageName);
7879 } catch (RemoteException c) {
7880 // pm is in same process, this will never happen.
7881 }
7882 }
7883 }
7884 }
7885
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007886 if (!app.isolated) {
7887 // XXX Can't keep track of crash times for isolated processes,
7888 // because they don't have a perisistent identity.
7889 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7890 }
7891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 return true;
7893 }
7894
7895 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007896 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7897 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 skipCurrentReceiverLocked(app);
7899 }
7900
7901 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007902 for (BroadcastQueue queue : mBroadcastQueues) {
7903 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 }
7905 }
7906
Dan Egnor60d87622009-12-16 16:32:58 -08007907 /**
7908 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7909 * The application process will exit immediately after this call returns.
7910 * @param app object of the crashing app, null for the system server
7911 * @param crashInfo describing the exception
7912 */
7913 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007914 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007915 final String processName = app == null ? "system_server"
7916 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007917
7918 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007919 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007920 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007921 crashInfo.exceptionClassName,
7922 crashInfo.exceptionMessage,
7923 crashInfo.throwFileName,
7924 crashInfo.throwLineNumber);
7925
Jeff Sharkeya353d262011-10-28 11:12:06 -07007926 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007927
7928 crashApplication(r, crashInfo);
7929 }
7930
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007931 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007932 IBinder app,
7933 int violationMask,
7934 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007935 ProcessRecord r = findAppProcess(app, "StrictMode");
7936 if (r == null) {
7937 return;
7938 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007939
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007940 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007941 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007942 boolean logIt = true;
7943 synchronized (mAlreadyLoggedViolatedStacks) {
7944 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7945 logIt = false;
7946 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007947 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007948 // the relative pain numbers, without logging all
7949 // the stack traces repeatedly. We'd want to do
7950 // likewise in the client code, which also does
7951 // dup suppression, before the Binder call.
7952 } else {
7953 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7954 mAlreadyLoggedViolatedStacks.clear();
7955 }
7956 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7957 }
7958 }
7959 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007960 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007961 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007962 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007963
7964 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7965 AppErrorResult result = new AppErrorResult();
7966 synchronized (this) {
7967 final long origId = Binder.clearCallingIdentity();
7968
7969 Message msg = Message.obtain();
7970 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7971 HashMap<String, Object> data = new HashMap<String, Object>();
7972 data.put("result", result);
7973 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007974 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007975 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007976 msg.obj = data;
7977 mHandler.sendMessage(msg);
7978
7979 Binder.restoreCallingIdentity(origId);
7980 }
7981 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007982 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007983 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007984 }
7985
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007986 // Depending on the policy in effect, there could be a bunch of
7987 // these in quick succession so we try to batch these together to
7988 // minimize disk writes, number of dropbox entries, and maximize
7989 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007990 private void logStrictModeViolationToDropBox(
7991 ProcessRecord process,
7992 StrictMode.ViolationInfo info) {
7993 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007994 return;
7995 }
7996 final boolean isSystemApp = process == null ||
7997 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7998 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007999 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008000 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8001 final DropBoxManager dbox = (DropBoxManager)
8002 mContext.getSystemService(Context.DROPBOX_SERVICE);
8003
8004 // Exit early if the dropbox isn't configured to accept this report type.
8005 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8006
8007 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008008 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008009 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8010 synchronized (sb) {
8011 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008012 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008013 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8014 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008015 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8016 if (info.violationNumThisLoop != 0) {
8017 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8018 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008019 if (info.numAnimationsRunning != 0) {
8020 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8021 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008022 if (info.broadcastIntentAction != null) {
8023 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8024 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008025 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008026 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008027 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008028 if (info.numInstances != -1) {
8029 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8030 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008031 if (info.tags != null) {
8032 for (String tag : info.tags) {
8033 sb.append("Span-Tag: ").append(tag).append("\n");
8034 }
8035 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008036 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008037 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8038 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008039 }
8040 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008041
8042 // Only buffer up to ~64k. Various logging bits truncate
8043 // things at 128k.
8044 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008045 }
8046
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008047 // Flush immediately if the buffer's grown too large, or this
8048 // is a non-system app. Non-system apps are isolated with a
8049 // different tag & policy and not batched.
8050 //
8051 // Batching is useful during internal testing with
8052 // StrictMode settings turned up high. Without batching,
8053 // thousands of separate files could be created on boot.
8054 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008055 new Thread("Error dump: " + dropboxTag) {
8056 @Override
8057 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008058 String report;
8059 synchronized (sb) {
8060 report = sb.toString();
8061 sb.delete(0, sb.length());
8062 sb.trimToSize();
8063 }
8064 if (report.length() != 0) {
8065 dbox.addText(dropboxTag, report);
8066 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008067 }
8068 }.start();
8069 return;
8070 }
8071
8072 // System app batching:
8073 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008074 // An existing dropbox-writing thread is outstanding, so
8075 // we don't need to start it up. The existing thread will
8076 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008077 return;
8078 }
8079
8080 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8081 // (After this point, we shouldn't access AMS internal data structures.)
8082 new Thread("Error dump: " + dropboxTag) {
8083 @Override
8084 public void run() {
8085 // 5 second sleep to let stacks arrive and be batched together
8086 try {
8087 Thread.sleep(5000); // 5 seconds
8088 } catch (InterruptedException e) {}
8089
8090 String errorReport;
8091 synchronized (mStrictModeBuffer) {
8092 errorReport = mStrictModeBuffer.toString();
8093 if (errorReport.length() == 0) {
8094 return;
8095 }
8096 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8097 mStrictModeBuffer.trimToSize();
8098 }
8099 dbox.addText(dropboxTag, errorReport);
8100 }
8101 }.start();
8102 }
8103
Dan Egnor60d87622009-12-16 16:32:58 -08008104 /**
8105 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8106 * @param app object of the crashing app, null for the system server
8107 * @param tag reported by the caller
8108 * @param crashInfo describing the context of the error
8109 * @return true if the process should exit immediately (WTF is fatal)
8110 */
8111 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008112 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008113 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008114 final String processName = app == null ? "system_server"
8115 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008116
8117 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008118 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008119 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008120 tag, crashInfo.exceptionMessage);
8121
Jeff Sharkeya353d262011-10-28 11:12:06 -07008122 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008123
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008124 if (r != null && r.pid != Process.myPid() &&
8125 Settings.Secure.getInt(mContext.getContentResolver(),
8126 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008127 crashApplication(r, crashInfo);
8128 return true;
8129 } else {
8130 return false;
8131 }
8132 }
8133
8134 /**
8135 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8136 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8137 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008138 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008139 if (app == null) {
8140 return null;
8141 }
8142
8143 synchronized (this) {
8144 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8145 final int NA = apps.size();
8146 for (int ia=0; ia<NA; ia++) {
8147 ProcessRecord p = apps.valueAt(ia);
8148 if (p.thread != null && p.thread.asBinder() == app) {
8149 return p;
8150 }
8151 }
8152 }
8153
Dianne Hackborncb44d962011-03-10 17:02:27 -08008154 Slog.w(TAG, "Can't find mystery application for " + reason
8155 + " from pid=" + Binder.getCallingPid()
8156 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008157 return null;
8158 }
8159 }
8160
8161 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008162 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8163 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008164 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008165 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8166 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008167 // Watchdog thread ends up invoking this function (with
8168 // a null ProcessRecord) to add the stack file to dropbox.
8169 // Do not acquire a lock on this (am) in such cases, as it
8170 // could cause a potential deadlock, if and when watchdog
8171 // is invoked due to unavailability of lock on am and it
8172 // would prevent watchdog from killing system_server.
8173 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008174 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008175 return;
8176 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008177 // Note: ProcessRecord 'process' is guarded by the service
8178 // instance. (notably process.pkgList, which could otherwise change
8179 // concurrently during execution of this method)
8180 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008181 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008182 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008183 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008184 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8185 for (String pkg : process.pkgList) {
8186 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008187 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008188 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008189 if (pi != null) {
8190 sb.append(" v").append(pi.versionCode);
8191 if (pi.versionName != null) {
8192 sb.append(" (").append(pi.versionName).append(")");
8193 }
8194 }
8195 } catch (RemoteException e) {
8196 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008197 }
Dan Egnora455d192010-03-12 08:52:28 -08008198 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008199 }
Dan Egnora455d192010-03-12 08:52:28 -08008200 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008201 }
8202
8203 private static String processClass(ProcessRecord process) {
8204 if (process == null || process.pid == MY_PID) {
8205 return "system_server";
8206 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8207 return "system_app";
8208 } else {
8209 return "data_app";
8210 }
8211 }
8212
8213 /**
8214 * Write a description of an error (crash, WTF, ANR) to the drop box.
8215 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8216 * @param process which caused the error, null means the system server
8217 * @param activity which triggered the error, null if unknown
8218 * @param parent activity related to the error, null if unknown
8219 * @param subject line related to the error, null if absent
8220 * @param report in long form describing the error, null if absent
8221 * @param logFile to include in the report, null if none
8222 * @param crashInfo giving an application stack trace, null if absent
8223 */
8224 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008225 ProcessRecord process, String processName, ActivityRecord activity,
8226 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008227 final String report, final File logFile,
8228 final ApplicationErrorReport.CrashInfo crashInfo) {
8229 // NOTE -- this must never acquire the ActivityManagerService lock,
8230 // otherwise the watchdog may be prevented from resetting the system.
8231
8232 final String dropboxTag = processClass(process) + "_" + eventType;
8233 final DropBoxManager dbox = (DropBoxManager)
8234 mContext.getSystemService(Context.DROPBOX_SERVICE);
8235
8236 // Exit early if the dropbox isn't configured to accept this report type.
8237 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8238
8239 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008240 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008241 if (activity != null) {
8242 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8243 }
8244 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8245 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8246 }
8247 if (parent != null && parent != activity) {
8248 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8249 }
8250 if (subject != null) {
8251 sb.append("Subject: ").append(subject).append("\n");
8252 }
8253 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008254 if (Debug.isDebuggerConnected()) {
8255 sb.append("Debugger: Connected\n");
8256 }
Dan Egnora455d192010-03-12 08:52:28 -08008257 sb.append("\n");
8258
8259 // Do the rest in a worker thread to avoid blocking the caller on I/O
8260 // (After this point, we shouldn't access AMS internal data structures.)
8261 Thread worker = new Thread("Error dump: " + dropboxTag) {
8262 @Override
8263 public void run() {
8264 if (report != null) {
8265 sb.append(report);
8266 }
8267 if (logFile != null) {
8268 try {
8269 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8270 } catch (IOException e) {
8271 Slog.e(TAG, "Error reading " + logFile, e);
8272 }
8273 }
8274 if (crashInfo != null && crashInfo.stackTrace != null) {
8275 sb.append(crashInfo.stackTrace);
8276 }
8277
8278 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8279 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8280 if (lines > 0) {
8281 sb.append("\n");
8282
8283 // Merge several logcat streams, and take the last N lines
8284 InputStreamReader input = null;
8285 try {
8286 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8287 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8288 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8289
8290 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8291 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8292 input = new InputStreamReader(logcat.getInputStream());
8293
8294 int num;
8295 char[] buf = new char[8192];
8296 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8297 } catch (IOException e) {
8298 Slog.e(TAG, "Error running logcat", e);
8299 } finally {
8300 if (input != null) try { input.close(); } catch (IOException e) {}
8301 }
8302 }
8303
8304 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008305 }
Dan Egnora455d192010-03-12 08:52:28 -08008306 };
8307
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008308 if (process == null) {
8309 // If process is null, we are being called from some internal code
8310 // and may be about to die -- run this synchronously.
8311 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008312 } else {
8313 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008314 }
8315 }
8316
8317 /**
8318 * Bring up the "unexpected error" dialog box for a crashing app.
8319 * Deal with edge cases (intercepts from instrumented applications,
8320 * ActivityController, error intent receivers, that sort of thing).
8321 * @param r the application crashing
8322 * @param crashInfo describing the failure
8323 */
8324 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008325 long timeMillis = System.currentTimeMillis();
8326 String shortMsg = crashInfo.exceptionClassName;
8327 String longMsg = crashInfo.exceptionMessage;
8328 String stackTrace = crashInfo.stackTrace;
8329 if (shortMsg != null && longMsg != null) {
8330 longMsg = shortMsg + ": " + longMsg;
8331 } else if (shortMsg != null) {
8332 longMsg = shortMsg;
8333 }
8334
Dan Egnor60d87622009-12-16 16:32:58 -08008335 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008337 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 try {
8339 String name = r != null ? r.processName : null;
8340 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008341 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008342 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008343 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 + " at watcher's request");
8345 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008346 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 }
8348 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008349 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 }
8351 }
8352
8353 final long origId = Binder.clearCallingIdentity();
8354
8355 // If this process is running instrumentation, finish it.
8356 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008357 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008359 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8360 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 Bundle info = new Bundle();
8362 info.putString("shortMsg", shortMsg);
8363 info.putString("longMsg", longMsg);
8364 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8365 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008366 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 }
8368
Dan Egnor60d87622009-12-16 16:32:58 -08008369 // If we can't identify the process or it's already exceeded its crash quota,
8370 // quit right away without showing a crash dialog.
8371 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008373 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 }
8375
8376 Message msg = Message.obtain();
8377 msg.what = SHOW_ERROR_MSG;
8378 HashMap data = new HashMap();
8379 data.put("result", result);
8380 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 msg.obj = data;
8382 mHandler.sendMessage(msg);
8383
8384 Binder.restoreCallingIdentity(origId);
8385 }
8386
8387 int res = result.get();
8388
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008389 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008391 if (r != null && !r.isolated) {
8392 // XXX Can't keep track of crash time for isolated processes,
8393 // since they don't have a persistent identity.
8394 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 SystemClock.uptimeMillis());
8396 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008397 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008398 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008399 }
8400 }
8401
8402 if (appErrorIntent != null) {
8403 try {
8404 mContext.startActivity(appErrorIntent);
8405 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008406 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008410
8411 Intent createAppErrorIntentLocked(ProcessRecord r,
8412 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8413 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008414 if (report == null) {
8415 return null;
8416 }
8417 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8418 result.setComponent(r.errorReportReceiver);
8419 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8420 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8421 return result;
8422 }
8423
Dan Egnorb7f03672009-12-09 16:22:32 -08008424 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8425 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008426 if (r.errorReportReceiver == null) {
8427 return null;
8428 }
8429
8430 if (!r.crashing && !r.notResponding) {
8431 return null;
8432 }
8433
Dan Egnorb7f03672009-12-09 16:22:32 -08008434 ApplicationErrorReport report = new ApplicationErrorReport();
8435 report.packageName = r.info.packageName;
8436 report.installerPackageName = r.errorReportReceiver.getPackageName();
8437 report.processName = r.processName;
8438 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008439 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008440
Dan Egnorb7f03672009-12-09 16:22:32 -08008441 if (r.crashing) {
8442 report.type = ApplicationErrorReport.TYPE_CRASH;
8443 report.crashInfo = crashInfo;
8444 } else if (r.notResponding) {
8445 report.type = ApplicationErrorReport.TYPE_ANR;
8446 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008447
Dan Egnorb7f03672009-12-09 16:22:32 -08008448 report.anrInfo.activity = r.notRespondingReport.tag;
8449 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8450 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008451 }
8452
Dan Egnorb7f03672009-12-09 16:22:32 -08008453 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008454 }
8455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008457 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 // assume our apps are happy - lazy create the list
8459 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8460
Dianne Hackborn0c380492012-08-20 17:23:30 -07008461 final boolean allUsers = ActivityManager.checkUidPermission(
8462 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8463 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8464 int userId = UserHandle.getUserId(Binder.getCallingUid());
8465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 synchronized (this) {
8467
8468 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008469 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8470 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008471 if (!allUsers && app.userId != userId) {
8472 continue;
8473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8475 // This one's in trouble, so we'll generate a report for it
8476 // crashes are higher priority (in case there's a crash *and* an anr)
8477 ActivityManager.ProcessErrorStateInfo report = null;
8478 if (app.crashing) {
8479 report = app.crashingReport;
8480 } else if (app.notResponding) {
8481 report = app.notRespondingReport;
8482 }
8483
8484 if (report != null) {
8485 if (errList == null) {
8486 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8487 }
8488 errList.add(report);
8489 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008490 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 " crashing = " + app.crashing +
8492 " notResponding = " + app.notResponding);
8493 }
8494 }
8495 }
8496 }
8497
8498 return errList;
8499 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008500
8501 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008502 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008503 if (currApp != null) {
8504 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8505 }
8506 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008507 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8508 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008509 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8510 if (currApp != null) {
8511 currApp.lru = 0;
8512 }
8513 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008514 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008515 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8516 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8517 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8518 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8519 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8520 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8521 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8522 } else {
8523 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8524 }
8525 }
8526
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008527 private void fillInProcMemInfo(ProcessRecord app,
8528 ActivityManager.RunningAppProcessInfo outInfo) {
8529 outInfo.pid = app.pid;
8530 outInfo.uid = app.info.uid;
8531 if (mHeavyWeightProcess == app) {
8532 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8533 }
8534 if (app.persistent) {
8535 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8536 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008537 if (app.hasActivities) {
8538 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8539 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008540 outInfo.lastTrimLevel = app.trimMemoryLevel;
8541 int adj = app.curAdj;
8542 outInfo.importance = oomAdjToImportance(adj, outInfo);
8543 outInfo.importanceReasonCode = app.adjTypeCode;
8544 }
8545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008547 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 // Lazy instantiation of list
8549 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008550 final boolean allUsers = ActivityManager.checkUidPermission(
8551 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8552 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8553 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 synchronized (this) {
8555 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008556 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8557 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008558 if (!allUsers && app.userId != userId) {
8559 continue;
8560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8562 // Generate process state info for running application
8563 ActivityManager.RunningAppProcessInfo currApp =
8564 new ActivityManager.RunningAppProcessInfo(app.processName,
8565 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008566 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008567 if (app.adjSource instanceof ProcessRecord) {
8568 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008569 currApp.importanceReasonImportance = oomAdjToImportance(
8570 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008571 } else if (app.adjSource instanceof ActivityRecord) {
8572 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008573 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8574 }
8575 if (app.adjTarget instanceof ComponentName) {
8576 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8577 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008578 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 // + " lru=" + currApp.lru);
8580 if (runList == null) {
8581 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8582 }
8583 runList.add(currApp);
8584 }
8585 }
8586 }
8587 return runList;
8588 }
8589
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008590 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008591 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008592 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8593 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8594 if (runningApps != null && runningApps.size() > 0) {
8595 Set<String> extList = new HashSet<String>();
8596 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8597 if (app.pkgList != null) {
8598 for (String pkg : app.pkgList) {
8599 extList.add(pkg);
8600 }
8601 }
8602 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008603 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008604 for (String pkg : extList) {
8605 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008606 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008607 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8608 retList.add(info);
8609 }
8610 } catch (RemoteException e) {
8611 }
8612 }
8613 }
8614 return retList;
8615 }
8616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008618 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8619 enforceNotIsolatedCaller("getMyMemoryState");
8620 synchronized (this) {
8621 ProcessRecord proc;
8622 synchronized (mPidsSelfLocked) {
8623 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8624 }
8625 fillInProcMemInfo(proc, outInfo);
8626 }
8627 }
8628
8629 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008631 if (checkCallingPermission(android.Manifest.permission.DUMP)
8632 != PackageManager.PERMISSION_GRANTED) {
8633 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8634 + Binder.getCallingPid()
8635 + ", uid=" + Binder.getCallingUid()
8636 + " without permission "
8637 + android.Manifest.permission.DUMP);
8638 return;
8639 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008640
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008642 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008643 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008644
8645 int opti = 0;
8646 while (opti < args.length) {
8647 String opt = args[opti];
8648 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8649 break;
8650 }
8651 opti++;
8652 if ("-a".equals(opt)) {
8653 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008654 } else if ("-c".equals(opt)) {
8655 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656 } else if ("-h".equals(opt)) {
8657 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008660 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008661 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8662 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8663 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008664 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008665 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008666 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008667 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008668 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008670 pw.println(" all: dump all activities");
8671 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008672 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008673 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8674 pw.println(" a partial substring in a component name, a");
8675 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 pw.println(" -a: include all available server state.");
8677 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008679 } else {
8680 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008683
8684 long origId = Binder.clearCallingIdentity();
8685 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 // Is the caller requesting to dump a particular piece of data?
8687 if (opti < args.length) {
8688 String cmd = args[opti];
8689 opti++;
8690 if ("activities".equals(cmd) || "a".equals(cmd)) {
8691 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008692 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008694 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 String[] newArgs;
8696 String name;
8697 if (opti >= args.length) {
8698 name = null;
8699 newArgs = EMPTY_STRING_ARRAY;
8700 } else {
8701 name = args[opti];
8702 opti++;
8703 newArgs = new String[args.length - opti];
8704 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8705 args.length - opti);
8706 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008708 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008709 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008710 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008711 String[] newArgs;
8712 String name;
8713 if (opti >= args.length) {
8714 name = null;
8715 newArgs = EMPTY_STRING_ARRAY;
8716 } else {
8717 name = args[opti];
8718 opti++;
8719 newArgs = new String[args.length - opti];
8720 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8721 args.length - opti);
8722 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008724 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008725 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008727 String[] newArgs;
8728 String name;
8729 if (opti >= args.length) {
8730 name = null;
8731 newArgs = EMPTY_STRING_ARRAY;
8732 } else {
8733 name = args[opti];
8734 opti++;
8735 newArgs = new String[args.length - opti];
8736 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8737 args.length - opti);
8738 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008740 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008741 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008742 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8743 synchronized (this) {
8744 dumpOomLocked(fd, pw, args, opti, true);
8745 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008746 } else if ("provider".equals(cmd)) {
8747 String[] newArgs;
8748 String name;
8749 if (opti >= args.length) {
8750 name = null;
8751 newArgs = EMPTY_STRING_ARRAY;
8752 } else {
8753 name = args[opti];
8754 opti++;
8755 newArgs = new String[args.length - opti];
8756 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8757 }
8758 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8759 pw.println("No providers match: " + name);
8760 pw.println("Use -h for help.");
8761 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8763 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008766 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008767 String[] newArgs;
8768 String name;
8769 if (opti >= args.length) {
8770 name = null;
8771 newArgs = EMPTY_STRING_ARRAY;
8772 } else {
8773 name = args[opti];
8774 opti++;
8775 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8777 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008778 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008779 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 pw.println("No services match: " + name);
8781 pw.println("Use -h for help.");
8782 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 } else if ("package".equals(cmd)) {
8784 String[] newArgs;
8785 if (opti >= args.length) {
8786 pw.println("package: no package name specified");
8787 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 } else {
8789 dumpPackage = args[opti];
8790 opti++;
8791 newArgs = new String[args.length - opti];
8792 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8793 args.length - opti);
8794 args = newArgs;
8795 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008796 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008797 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008798 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8799 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008800 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008801 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008802 } else {
8803 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008804 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8805 pw.println("Bad activity command, or no activities match: " + cmd);
8806 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008807 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008808 }
8809 if (!more) {
8810 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008811 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008814
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008815 // No piece of data specified, dump everything.
8816 synchronized (this) {
8817 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008818 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 if (needSep) {
8820 pw.println(" ");
8821 }
8822 if (dumpAll) {
8823 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008825 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008826 if (needSep) {
8827 pw.println(" ");
8828 }
8829 if (dumpAll) {
8830 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008832 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833 if (needSep) {
8834 pw.println(" ");
8835 }
8836 if (dumpAll) {
8837 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008838 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008839 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 if (needSep) {
8841 pw.println(" ");
8842 }
8843 if (dumpAll) {
8844 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008846 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008847 if (needSep) {
8848 pw.println(" ");
8849 }
8850 if (dumpAll) {
8851 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008855 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008857
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008860 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8861 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8863 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 pw.println(" ");
8865 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8867 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008868 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008870 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008871 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008872 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008873 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008874 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008877 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008878 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008879 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008880 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8881 pw.println(" ");
8882 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008883 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008885 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008886 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008887 pw.println(" ");
8888 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008890 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008893 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008894 if (mMainStack.mPausingActivity != null) {
8895 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008896 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008897 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008899 if (dumpAll) {
8900 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8901 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008902 pw.println(" mDismissKeyguardOnNextActivity: "
8903 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008906 if (mRecentTasks.size() > 0) {
8907 pw.println();
8908 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008909
8910 final int N = mRecentTasks.size();
8911 for (int i=0; i<N; i++) {
8912 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008913 if (dumpPackage != null) {
8914 if (tr.realActivity == null ||
8915 !dumpPackage.equals(tr.realActivity)) {
8916 continue;
8917 }
8918 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008919 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8920 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008921 if (dumpAll) {
8922 mRecentTasks.get(i).dump(pw, " ");
8923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 }
8925 }
8926
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927 if (dumpAll) {
8928 pw.println(" ");
8929 pw.println(" mCurTask: " + mCurTask);
8930 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008931
8932 return true;
8933 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008934
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008936 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 boolean needSep = false;
8938 int numPers = 0;
8939
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008940 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8941
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8944 final int NA = procs.size();
8945 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008946 ProcessRecord r = procs.valueAt(ia);
8947 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8948 continue;
8949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 if (!needSep) {
8951 pw.println(" All known processes:");
8952 needSep = true;
8953 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008954 pw.print(r.persistent ? " *PERS*" : " *APP*");
8955 pw.print(" UID "); pw.print(procs.keyAt(ia));
8956 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 r.dump(pw, " ");
8958 if (r.persistent) {
8959 numPers++;
8960 }
8961 }
8962 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008964
8965 if (mIsolatedProcesses.size() > 0) {
8966 if (needSep) pw.println(" ");
8967 needSep = true;
8968 pw.println(" Isolated process list (sorted by uid):");
8969 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8970 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8971 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8972 continue;
8973 }
8974 pw.println(String.format("%sIsolated #%2d: %s",
8975 " ", i, r.toString()));
8976 }
8977 }
8978
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 if (mLruProcesses.size() > 0) {
8980 if (needSep) pw.println(" ");
8981 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008982 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008983 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 needSep = true;
8986 }
8987
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008988 if (dumpAll) {
8989 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008990 boolean printed = false;
8991 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8992 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8993 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8994 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008995 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008996 if (!printed) {
8997 if (needSep) pw.println(" ");
8998 needSep = true;
8999 pw.println(" PID mappings:");
9000 printed = true;
9001 }
9002 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9003 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 }
9005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 }
9007
9008 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009009 synchronized (mPidsSelfLocked) {
9010 boolean printed = false;
9011 for (int i=0; i<mForegroundProcesses.size(); i++) {
9012 ProcessRecord r = mPidsSelfLocked.get(
9013 mForegroundProcesses.valueAt(i).pid);
9014 if (dumpPackage != null && (r == null
9015 || !dumpPackage.equals(r.info.packageName))) {
9016 continue;
9017 }
9018 if (!printed) {
9019 if (needSep) pw.println(" ");
9020 needSep = true;
9021 pw.println(" Foreground Processes:");
9022 printed = true;
9023 }
9024 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9025 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 }
9029
9030 if (mPersistentStartingProcesses.size() > 0) {
9031 if (needSep) pw.println(" ");
9032 needSep = true;
9033 pw.println(" Persisent processes that are starting:");
9034 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009038 if (mRemovedProcesses.size() > 0) {
9039 if (needSep) pw.println(" ");
9040 needSep = true;
9041 pw.println(" Processes that are being removed:");
9042 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009043 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 }
9045
9046 if (mProcessesOnHold.size() > 0) {
9047 if (needSep) pw.println(" ");
9048 needSep = true;
9049 pw.println(" Processes that are on old until the system is ready:");
9050 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009054 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055
9056 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 long now = SystemClock.uptimeMillis();
9059 for (Map.Entry<String, SparseArray<Long>> procs
9060 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009061 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 SparseArray<Long> uids = procs.getValue();
9063 final int N = uids.size();
9064 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009065 int puid = uids.keyAt(i);
9066 ProcessRecord r = mProcessNames.get(pname, puid);
9067 if (dumpPackage != null && (r == null
9068 || !dumpPackage.equals(r.info.packageName))) {
9069 continue;
9070 }
9071 if (!printed) {
9072 if (needSep) pw.println(" ");
9073 needSep = true;
9074 pw.println(" Time since processes crashed:");
9075 printed = true;
9076 }
9077 pw.print(" Process "); pw.print(pname);
9078 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009080 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9081 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009082 }
9083 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009087 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088 for (Map.Entry<String, SparseArray<Long>> procs
9089 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009090 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 SparseArray<Long> uids = procs.getValue();
9092 final int N = uids.size();
9093 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094 int puid = uids.keyAt(i);
9095 ProcessRecord r = mProcessNames.get(pname, puid);
9096 if (dumpPackage != null && (r == null
9097 || !dumpPackage.equals(r.info.packageName))) {
9098 continue;
9099 }
9100 if (!printed) {
9101 if (needSep) pw.println(" ");
9102 needSep = true;
9103 pw.println(" Bad processes:");
9104 }
9105 pw.print(" Bad process "); pw.print(pname);
9106 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 pw.print(": crashed at time ");
9108 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 }
9110 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009114 pw.println(" mStartedUsers:");
9115 for (int i=0; i<mStartedUsers.size(); i++) {
9116 UserStartedState uss = mStartedUsers.valueAt(i);
9117 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
9118 pw.println(":");
9119 uss.dump(" ", pw);
9120 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009122 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009123 if (dumpAll) {
9124 StringBuilder sb = new StringBuilder(128);
9125 sb.append(" mPreviousProcessVisibleTime: ");
9126 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9127 pw.println(sb);
9128 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009129 if (mHeavyWeightProcess != null) {
9130 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9131 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009132 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009133 if (dumpAll) {
9134 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009135 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009136 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009137 for (Map.Entry<String, Integer> entry
9138 : mCompatModePackages.getPackages().entrySet()) {
9139 String pkg = entry.getKey();
9140 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009141 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9142 continue;
9143 }
9144 if (!printed) {
9145 pw.println(" mScreenCompatPackages:");
9146 printed = true;
9147 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009148 pw.print(" "); pw.print(pkg); pw.print(": ");
9149 pw.print(mode); pw.println();
9150 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009151 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009153 if (mSleeping || mWentToSleep || mLockScreenShown) {
9154 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9155 + " mLockScreenShown " + mLockScreenShown);
9156 }
9157 if (mShuttingDown) {
9158 pw.println(" mShuttingDown=" + mShuttingDown);
9159 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9161 || mOrigWaitForDebugger) {
9162 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9163 + " mDebugTransient=" + mDebugTransient
9164 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9165 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009166 if (mOpenGlTraceApp != null) {
9167 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9168 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009169 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9170 || mProfileFd != null) {
9171 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9172 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9173 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9174 + mAutoStopProfiler);
9175 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 if (mAlwaysFinishActivities || mController != null) {
9177 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9178 + " mController=" + mController);
9179 }
9180 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009183 + " mProcessesReady=" + mProcessesReady
9184 + " mSystemReady=" + mSystemReady);
9185 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 + " mBooted=" + mBooted
9187 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009188 pw.print(" mLastPowerCheckRealtime=");
9189 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9190 pw.println("");
9191 pw.print(" mLastPowerCheckUptime=");
9192 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9193 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009194 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9195 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009196 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009197 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9198 + " mNumHiddenProcs=" + mNumHiddenProcs
9199 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009200 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202
9203 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 }
9205
Dianne Hackborn287952c2010-09-22 22:34:31 -07009206 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009207 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009208 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009210 long now = SystemClock.uptimeMillis();
9211 for (int i=0; i<mProcessesToGc.size(); i++) {
9212 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009213 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9214 continue;
9215 }
9216 if (!printed) {
9217 if (needSep) pw.println(" ");
9218 needSep = true;
9219 pw.println(" Processes that are waiting to GC:");
9220 printed = true;
9221 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009222 pw.print(" Process "); pw.println(proc);
9223 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9224 pw.print(", last gced=");
9225 pw.print(now-proc.lastRequestedGc);
9226 pw.print(" ms ago, last lowMem=");
9227 pw.print(now-proc.lastLowMemory);
9228 pw.println(" ms ago");
9229
9230 }
9231 }
9232 return needSep;
9233 }
9234
9235 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9236 int opti, boolean dumpAll) {
9237 boolean needSep = false;
9238
9239 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009240 if (needSep) pw.println(" ");
9241 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009242 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009243 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009244 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009245 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9246 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9247 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9248 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9249 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009250 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009251 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009252 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009253 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009254 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009255 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009256
9257 if (needSep) pw.println(" ");
9258 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009259 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009260 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009261 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009262 needSep = true;
9263 }
9264
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009265 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009266
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009267 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009268 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009269 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009270 if (mHeavyWeightProcess != null) {
9271 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9272 }
9273
9274 return true;
9275 }
9276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 /**
9278 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009279 * - no provider specified: dump all the providers
9280 * - a flattened component name that matched an existing provider was specified as the
9281 * first arg: dump that one provider
9282 * - the first arg isn't the flattened component name of an existing provider:
9283 * dump all providers whose component contains the first arg as a substring
9284 */
9285 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9286 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009287 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009288 }
9289
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009290 static class ItemMatcher {
9291 ArrayList<ComponentName> components;
9292 ArrayList<String> strings;
9293 ArrayList<Integer> objects;
9294 boolean all;
9295
9296 ItemMatcher() {
9297 all = true;
9298 }
9299
9300 void build(String name) {
9301 ComponentName componentName = ComponentName.unflattenFromString(name);
9302 if (componentName != null) {
9303 if (components == null) {
9304 components = new ArrayList<ComponentName>();
9305 }
9306 components.add(componentName);
9307 all = false;
9308 } else {
9309 int objectId = 0;
9310 // Not a '/' separated full component name; maybe an object ID?
9311 try {
9312 objectId = Integer.parseInt(name, 16);
9313 if (objects == null) {
9314 objects = new ArrayList<Integer>();
9315 }
9316 objects.add(objectId);
9317 all = false;
9318 } catch (RuntimeException e) {
9319 // Not an integer; just do string match.
9320 if (strings == null) {
9321 strings = new ArrayList<String>();
9322 }
9323 strings.add(name);
9324 all = false;
9325 }
9326 }
9327 }
9328
9329 int build(String[] args, int opti) {
9330 for (; opti<args.length; opti++) {
9331 String name = args[opti];
9332 if ("--".equals(name)) {
9333 return opti+1;
9334 }
9335 build(name);
9336 }
9337 return opti;
9338 }
9339
9340 boolean match(Object object, ComponentName comp) {
9341 if (all) {
9342 return true;
9343 }
9344 if (components != null) {
9345 for (int i=0; i<components.size(); i++) {
9346 if (components.get(i).equals(comp)) {
9347 return true;
9348 }
9349 }
9350 }
9351 if (objects != null) {
9352 for (int i=0; i<objects.size(); i++) {
9353 if (System.identityHashCode(object) == objects.get(i)) {
9354 return true;
9355 }
9356 }
9357 }
9358 if (strings != null) {
9359 String flat = comp.flattenToString();
9360 for (int i=0; i<strings.size(); i++) {
9361 if (flat.contains(strings.get(i))) {
9362 return true;
9363 }
9364 }
9365 }
9366 return false;
9367 }
9368 }
9369
Dianne Hackborn625ac272010-09-17 18:29:22 -07009370 /**
9371 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009372 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009373 * - the cmd arg isn't the flattened component name of an existing activity:
9374 * dump all activity whose component contains the cmd as a substring
9375 * - A hex number of the ActivityRecord object instance.
9376 */
9377 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9378 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009379 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009380
9381 if ("all".equals(name)) {
9382 synchronized (this) {
9383 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009384 activities.add(r1);
9385 }
9386 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009387 } else if ("top".equals(name)) {
9388 synchronized (this) {
9389 final int N = mMainStack.mHistory.size();
9390 if (N > 0) {
9391 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9392 }
9393 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009394 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009395 ItemMatcher matcher = new ItemMatcher();
9396 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009397
9398 synchronized (this) {
9399 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009400 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401 activities.add(r1);
9402 }
9403 }
9404 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009405 }
9406
9407 if (activities.size() <= 0) {
9408 return false;
9409 }
9410
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009411 String[] newArgs = new String[args.length - opti];
9412 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9413
Dianne Hackborn30d71892010-12-11 10:37:55 -08009414 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009416 for (int i=activities.size()-1; i>=0; i--) {
9417 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 if (needSep) {
9419 pw.println();
9420 }
9421 needSep = true;
9422 synchronized (this) {
9423 if (lastTask != r.task) {
9424 lastTask = r.task;
9425 pw.print("TASK "); pw.print(lastTask.affinity);
9426 pw.print(" id="); pw.println(lastTask.taskId);
9427 if (dumpAll) {
9428 lastTask.dump(pw, " ");
9429 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009430 }
9431 }
9432 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009433 }
9434 return true;
9435 }
9436
9437 /**
9438 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9439 * there is a thread associated with the activity.
9440 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009441 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009442 final ActivityRecord r, String[] args, boolean dumpAll) {
9443 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009444 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009445 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9446 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9447 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009448 if (r.app != null) pw.println(r.app.pid);
9449 else pw.println("(not running)");
9450 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009451 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009452 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009453 }
9454 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009455 // flush anything that is already in the PrintWriter since the thread is going
9456 // to write to the file descriptor directly
9457 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009458 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 TransferPipe tp = new TransferPipe();
9460 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009461 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9462 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 tp.go(fd);
9464 } finally {
9465 tp.kill();
9466 }
9467 } catch (IOException e) {
9468 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009469 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009470 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009471 }
9472 }
9473 }
9474
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009475 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009476 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009477 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009478 boolean onlyHistory = false;
9479
9480 if ("history".equals(dumpPackage)) {
9481 onlyHistory = true;
9482 dumpPackage = null;
9483 }
9484
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009485 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009486 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 Iterator it = mRegisteredReceivers.values().iterator();
9490 while (it.hasNext()) {
9491 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 if (dumpPackage != null && (r.app == null ||
9493 !dumpPackage.equals(r.app.info.packageName))) {
9494 continue;
9495 }
9496 if (!printed) {
9497 pw.println(" Registered Receivers:");
9498 needSep = true;
9499 printed = true;
9500 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009501 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 r.dump(pw, " ");
9503 }
9504 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009505
9506 if (mReceiverResolver.dump(pw, needSep ?
9507 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9508 " ", dumpPackage, false)) {
9509 needSep = true;
9510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009512
9513 for (BroadcastQueue q : mBroadcastQueues) {
9514 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009517 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518
Dianne Hackborn786b4402012-08-27 15:14:02 -07009519 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009520 if (needSep) {
9521 pw.println();
9522 }
9523 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009524 pw.println(" Sticky broadcasts:");
9525 StringBuilder sb = new StringBuilder(128);
9526 for (Map.Entry<String, ArrayList<Intent>> ent
9527 : mStickyBroadcasts.entrySet()) {
9528 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 if (dumpAll) {
9530 pw.println(":");
9531 ArrayList<Intent> intents = ent.getValue();
9532 final int N = intents.size();
9533 for (int i=0; i<N; i++) {
9534 sb.setLength(0);
9535 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009536 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009537 pw.println(sb.toString());
9538 Bundle bundle = intents.get(i).getExtras();
9539 if (bundle != null) {
9540 pw.print(" ");
9541 pw.println(bundle.toString());
9542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009544 } else {
9545 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 }
9547 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009548 needSep = true;
9549 }
9550
Dianne Hackborn786b4402012-08-27 15:14:02 -07009551 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009552 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009553 for (BroadcastQueue queue : mBroadcastQueues) {
9554 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9555 + queue.mBroadcastsScheduled);
9556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009557 pw.println(" mHandler:");
9558 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009561
9562 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 }
9564
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009565 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009566 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009567 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009569 ItemMatcher matcher = new ItemMatcher();
9570 matcher.build(args, opti);
9571
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009572 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009573
9574 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009575
9576 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009577 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009578 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009579 ContentProviderRecord r = mLaunchingProviders.get(i);
9580 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9581 continue;
9582 }
9583 if (!printed) {
9584 if (needSep) pw.println(" ");
9585 needSep = true;
9586 pw.println(" Launching content providers:");
9587 printed = true;
9588 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009589 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009590 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009591 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009592 }
9593
9594 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009595 if (needSep) pw.println();
9596 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009597 pw.println("Granted Uri Permissions:");
9598 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9599 int uid = mGrantedUriPermissions.keyAt(i);
9600 HashMap<Uri, UriPermission> perms
9601 = mGrantedUriPermissions.valueAt(i);
9602 pw.print(" * UID "); pw.print(uid);
9603 pw.println(" holds:");
9604 for (UriPermission perm : perms.values()) {
9605 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009606 if (dumpAll) {
9607 perm.dump(pw, " ");
9608 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009609 }
9610 }
9611 needSep = true;
9612 }
9613
9614 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 }
9616
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009617 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009618 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619 boolean needSep = false;
9620
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009621 if (mIntentSenderRecords.size() > 0) {
9622 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 Iterator<WeakReference<PendingIntentRecord>> it
9624 = mIntentSenderRecords.values().iterator();
9625 while (it.hasNext()) {
9626 WeakReference<PendingIntentRecord> ref = it.next();
9627 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009628 if (dumpPackage != null && (rec == null
9629 || !dumpPackage.equals(rec.key.packageName))) {
9630 continue;
9631 }
9632 if (!printed) {
9633 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9634 printed = true;
9635 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009636 needSep = true;
9637 if (rec != null) {
9638 pw.print(" * "); pw.println(rec);
9639 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009641 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009642 } else {
9643 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 }
9645 }
9646 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009647
9648 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009649 }
9650
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009652 String prefix, String label, boolean complete, boolean brief, boolean client,
9653 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009655 boolean needNL = false;
9656 final String innerPrefix = prefix + " ";
9657 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009659 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009660 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9661 continue;
9662 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009663 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009664 if (needNL) {
9665 pw.println(" ");
9666 needNL = false;
9667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 if (lastTask != r.task) {
9669 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009670 pw.print(prefix);
9671 pw.print(full ? "* " : " ");
9672 pw.println(lastTask);
9673 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009674 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 } else if (complete) {
9676 // Complete + brief == give a summary. Isn't that obvious?!?
9677 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009678 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009679 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009680 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009683 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9684 pw.print(" #"); pw.print(i); pw.print(": ");
9685 pw.println(r);
9686 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009687 r.dump(pw, innerPrefix);
9688 } else if (complete) {
9689 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009690 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009691 if (r.app != null) {
9692 pw.print(innerPrefix); pw.println(r.app);
9693 }
9694 }
9695 if (client && r.app != null && r.app.thread != null) {
9696 // flush anything that is already in the PrintWriter since the thread is going
9697 // to write to the file descriptor directly
9698 pw.flush();
9699 try {
9700 TransferPipe tp = new TransferPipe();
9701 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009702 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9703 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009704 // Short timeout, since blocking here can
9705 // deadlock with the application.
9706 tp.go(fd, 2000);
9707 } finally {
9708 tp.kill();
9709 }
9710 } catch (IOException e) {
9711 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9712 } catch (RemoteException e) {
9713 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9714 }
9715 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 }
9718 }
9719
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009720 private static String buildOomTag(String prefix, String space, int val, int base) {
9721 if (val == base) {
9722 if (space == null) return prefix;
9723 return prefix + " ";
9724 }
9725 return prefix + "+" + Integer.toString(val-base);
9726 }
9727
9728 private static final int dumpProcessList(PrintWriter pw,
9729 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009730 String prefix, String normalLabel, String persistentLabel,
9731 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009733 final int N = list.size()-1;
9734 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009735 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009736 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9737 continue;
9738 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009739 pw.println(String.format("%s%s #%2d: %s",
9740 prefix, (r.persistent ? persistentLabel : normalLabel),
9741 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 if (r.persistent) {
9743 numPers++;
9744 }
9745 }
9746 return numPers;
9747 }
9748
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009749 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009750 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009751 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009752 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009753
Dianne Hackborn905577f2011-09-07 18:31:28 -07009754 ArrayList<Pair<ProcessRecord, Integer>> list
9755 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9756 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009757 ProcessRecord r = origList.get(i);
9758 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9759 continue;
9760 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009761 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9762 }
9763
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009764 if (list.size() <= 0) {
9765 return false;
9766 }
9767
Dianne Hackborn905577f2011-09-07 18:31:28 -07009768 Comparator<Pair<ProcessRecord, Integer>> comparator
9769 = new Comparator<Pair<ProcessRecord, Integer>>() {
9770 @Override
9771 public int compare(Pair<ProcessRecord, Integer> object1,
9772 Pair<ProcessRecord, Integer> object2) {
9773 if (object1.first.setAdj != object2.first.setAdj) {
9774 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9775 }
9776 if (object1.second.intValue() != object2.second.intValue()) {
9777 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9778 }
9779 return 0;
9780 }
9781 };
9782
9783 Collections.sort(list, comparator);
9784
Dianne Hackborn287952c2010-09-22 22:34:31 -07009785 final long curRealtime = SystemClock.elapsedRealtime();
9786 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9787 final long curUptime = SystemClock.uptimeMillis();
9788 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9789
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009790 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009791 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009792 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009793 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009794 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009795 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9796 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009797 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9798 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009799 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9800 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009801 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9802 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009803 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009804 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009805 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9806 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9807 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9808 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9809 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9810 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9811 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9812 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009813 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9814 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009815 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9816 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009817 } else {
9818 oomAdj = Integer.toString(r.setAdj);
9819 }
9820 String schedGroup;
9821 switch (r.setSchedGroup) {
9822 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9823 schedGroup = "B";
9824 break;
9825 case Process.THREAD_GROUP_DEFAULT:
9826 schedGroup = "F";
9827 break;
9828 default:
9829 schedGroup = Integer.toString(r.setSchedGroup);
9830 break;
9831 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009832 String foreground;
9833 if (r.foregroundActivities) {
9834 foreground = "A";
9835 } else if (r.foregroundServices) {
9836 foreground = "S";
9837 } else {
9838 foreground = " ";
9839 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009840 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009841 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009842 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9843 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009844 if (r.adjSource != null || r.adjTarget != null) {
9845 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009846 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009847 if (r.adjTarget instanceof ComponentName) {
9848 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9849 } else if (r.adjTarget != null) {
9850 pw.print(r.adjTarget.toString());
9851 } else {
9852 pw.print("{null}");
9853 }
9854 pw.print("<=");
9855 if (r.adjSource instanceof ProcessRecord) {
9856 pw.print("Proc{");
9857 pw.print(((ProcessRecord)r.adjSource).toShortString());
9858 pw.println("}");
9859 } else if (r.adjSource != null) {
9860 pw.println(r.adjSource.toString());
9861 } else {
9862 pw.println("{null}");
9863 }
9864 }
9865 if (inclDetails) {
9866 pw.print(prefix);
9867 pw.print(" ");
9868 pw.print("oom: max="); pw.print(r.maxAdj);
9869 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009870 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009871 pw.print(" curRaw="); pw.print(r.curRawAdj);
9872 pw.print(" setRaw="); pw.print(r.setRawAdj);
9873 pw.print(" cur="); pw.print(r.curAdj);
9874 pw.print(" set="); pw.println(r.setAdj);
9875 pw.print(prefix);
9876 pw.print(" ");
9877 pw.print("keeping="); pw.print(r.keeping);
9878 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009879 pw.print(" empty="); pw.print(r.empty);
9880 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009881
9882 if (!r.keeping) {
9883 if (r.lastWakeTime != 0) {
9884 long wtime;
9885 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9886 synchronized (stats) {
9887 wtime = stats.getProcessWakeTime(r.info.uid,
9888 r.pid, curRealtime);
9889 }
9890 long timeUsed = wtime - r.lastWakeTime;
9891 pw.print(prefix);
9892 pw.print(" ");
9893 pw.print("keep awake over ");
9894 TimeUtils.formatDuration(realtimeSince, pw);
9895 pw.print(" used ");
9896 TimeUtils.formatDuration(timeUsed, pw);
9897 pw.print(" (");
9898 pw.print((timeUsed*100)/realtimeSince);
9899 pw.println("%)");
9900 }
9901 if (r.lastCpuTime != 0) {
9902 long timeUsed = r.curCpuTime - r.lastCpuTime;
9903 pw.print(prefix);
9904 pw.print(" ");
9905 pw.print("run cpu over ");
9906 TimeUtils.formatDuration(uptimeSince, pw);
9907 pw.print(" used ");
9908 TimeUtils.formatDuration(timeUsed, pw);
9909 pw.print(" (");
9910 pw.print((timeUsed*100)/uptimeSince);
9911 pw.println("%)");
9912 }
9913 }
9914 }
9915 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009916 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009917 }
9918
Dianne Hackbornb437e092011-08-05 17:50:29 -07009919 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009920 ArrayList<ProcessRecord> procs;
9921 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009922 if (args != null && args.length > start
9923 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 procs = new ArrayList<ProcessRecord>();
9925 int pid = -1;
9926 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009927 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009928 } catch (NumberFormatException e) {
9929
9930 }
9931 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9932 ProcessRecord proc = mLruProcesses.get(i);
9933 if (proc.pid == pid) {
9934 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009935 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009936 procs.add(proc);
9937 }
9938 }
9939 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009940 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009941 return null;
9942 }
9943 } else {
9944 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9945 }
9946 }
9947 return procs;
9948 }
9949
9950 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9951 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009952 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009953 if (procs == null) {
9954 return;
9955 }
9956
9957 long uptime = SystemClock.uptimeMillis();
9958 long realtime = SystemClock.elapsedRealtime();
9959 pw.println("Applications Graphics Acceleration Info:");
9960 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9961
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009962 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9963 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009964 if (r.thread != null) {
9965 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9966 pw.flush();
9967 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009968 TransferPipe tp = new TransferPipe();
9969 try {
9970 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9971 tp.go(fd);
9972 } finally {
9973 tp.kill();
9974 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009975 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009976 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009977 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009978 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009979 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009980 pw.flush();
9981 }
9982 }
9983 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009984 }
9985
Jeff Brown6754ba22011-12-14 20:20:01 -08009986 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9987 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9988 if (procs == null) {
9989 return;
9990 }
9991
9992 pw.println("Applications Database Info:");
9993
9994 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9995 ProcessRecord r = procs.get(i);
9996 if (r.thread != null) {
9997 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9998 pw.flush();
9999 try {
10000 TransferPipe tp = new TransferPipe();
10001 try {
10002 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10003 tp.go(fd);
10004 } finally {
10005 tp.kill();
10006 }
10007 } catch (IOException e) {
10008 pw.println("Failure while dumping the app: " + r);
10009 pw.flush();
10010 } catch (RemoteException e) {
10011 pw.println("Got a RemoteException while dumping the app " + r);
10012 pw.flush();
10013 }
10014 }
10015 }
10016 }
10017
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010018 final static class MemItem {
10019 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010020 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010021 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010022 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010023 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010024
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010025 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010026 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010027 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010028 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010029 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010030 }
10031 }
10032
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010033 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010034 boolean sort) {
10035 if (sort) {
10036 Collections.sort(items, new Comparator<MemItem>() {
10037 @Override
10038 public int compare(MemItem lhs, MemItem rhs) {
10039 if (lhs.pss < rhs.pss) {
10040 return 1;
10041 } else if (lhs.pss > rhs.pss) {
10042 return -1;
10043 }
10044 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010045 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010046 });
10047 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010048
10049 for (int i=0; i<items.size(); i++) {
10050 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010051 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010052 if (mi.subitems != null) {
10053 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10054 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010055 }
10056 }
10057
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010058 // These are in KB.
10059 static final long[] DUMP_MEM_BUCKETS = new long[] {
10060 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10061 120*1024, 160*1024, 200*1024,
10062 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10063 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10064 };
10065
Dianne Hackborn672342c2011-11-29 11:29:02 -080010066 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10067 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010068 int start = label.lastIndexOf('.');
10069 if (start >= 0) start++;
10070 else start = 0;
10071 int end = label.length();
10072 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10073 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10074 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10075 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010076 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010077 out.append(label, start, end);
10078 return;
10079 }
10080 }
10081 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010082 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010083 out.append(label, start, end);
10084 }
10085
10086 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10087 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10088 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10089 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10090 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10091 };
10092 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10093 "System", "Persistent", "Foreground",
10094 "Visible", "Perceptible", "Heavy Weight",
10095 "Backup", "A Services", "Home", "Previous",
10096 "B Services", "Background"
10097 };
10098
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010099 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010100 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010101 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010102 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010103 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010104
10105 int opti = 0;
10106 while (opti < args.length) {
10107 String opt = args[opti];
10108 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10109 break;
10110 }
10111 opti++;
10112 if ("-a".equals(opt)) {
10113 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010114 } else if ("--oom".equals(opt)) {
10115 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010116 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010117 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010119 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120 pw.println("If [process] is specified it can be the name or ");
10121 pw.println("pid of a specific process to dump.");
10122 return;
10123 } else {
10124 pw.println("Unknown argument: " + opt + "; use -h for help");
10125 }
10126 }
10127
10128 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010129 if (procs == null) {
10130 return;
10131 }
10132
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010133 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010134 long uptime = SystemClock.uptimeMillis();
10135 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136
10137 if (procs.size() == 1 || isCheckinRequest) {
10138 dumpAll = true;
10139 }
10140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010141 if (isCheckinRequest) {
10142 // short checkin version
10143 pw.println(uptime + "," + realtime);
10144 pw.flush();
10145 } else {
10146 pw.println("Applications Memory Usage (kB):");
10147 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10148 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010149
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150 String[] innerArgs = new String[args.length-opti];
10151 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10152
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010153 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10154 long nativePss=0, dalvikPss=0, otherPss=0;
10155 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10156
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010157 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10158 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10159 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160
10161 long totalPss = 0;
10162
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010163 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10164 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010165 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010166 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010167 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10168 pw.flush();
10169 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010170 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010171 if (dumpAll) {
10172 try {
10173 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10174 } catch (RemoteException e) {
10175 if (!isCheckinRequest) {
10176 pw.println("Got RemoteException!");
10177 pw.flush();
10178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010179 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010180 } else {
10181 mi = new Debug.MemoryInfo();
10182 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010183 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010185 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010186 long myTotalPss = mi.getTotalPss();
10187 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010188 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010189 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010190 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010191
10192 nativePss += mi.nativePss;
10193 dalvikPss += mi.dalvikPss;
10194 otherPss += mi.otherPss;
10195 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10196 long mem = mi.getOtherPss(j);
10197 miscPss[j] += mem;
10198 otherPss -= mem;
10199 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200
10201 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010202 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10203 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010204 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010205 if (oomProcs[oomIndex] == null) {
10206 oomProcs[oomIndex] = new ArrayList<MemItem>();
10207 }
10208 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010209 break;
10210 }
10211 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010213 }
10214 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010215
10216 if (!isCheckinRequest && procs.size() > 1) {
10217 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10218
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010219 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10220 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10221 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010222 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010223 String label = Debug.MemoryInfo.getOtherLabel(j);
10224 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010225 }
10226
Dianne Hackbornb437e092011-08-05 17:50:29 -070010227 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10228 for (int j=0; j<oomPss.length; j++) {
10229 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010230 String label = DUMP_MEM_OOM_LABEL[j];
10231 MemItem item = new MemItem(label, label, oomPss[j],
10232 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010233 item.subitems = oomProcs[j];
10234 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010235 }
10236 }
10237
Dianne Hackborn672342c2011-11-29 11:29:02 -080010238 if (outTag != null || outStack != null) {
10239 if (outTag != null) {
10240 appendMemBucket(outTag, totalPss, "total", false);
10241 }
10242 if (outStack != null) {
10243 appendMemBucket(outStack, totalPss, "total", true);
10244 }
10245 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010246 for (int i=0; i<oomMems.size(); i++) {
10247 MemItem miCat = oomMems.get(i);
10248 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10249 continue;
10250 }
10251 if (miCat.id < ProcessList.SERVICE_ADJ
10252 || miCat.id == ProcessList.HOME_APP_ADJ
10253 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010254 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10255 outTag.append(" / ");
10256 }
10257 if (outStack != null) {
10258 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10259 if (firstLine) {
10260 outStack.append(":");
10261 firstLine = false;
10262 }
10263 outStack.append("\n\t at ");
10264 } else {
10265 outStack.append("$");
10266 }
10267 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010268 for (int j=0; j<miCat.subitems.size(); j++) {
10269 MemItem mi = miCat.subitems.get(j);
10270 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010271 if (outTag != null) {
10272 outTag.append(" ");
10273 }
10274 if (outStack != null) {
10275 outStack.append("$");
10276 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010277 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010278 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10279 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10280 }
10281 if (outStack != null) {
10282 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10283 }
10284 }
10285 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10286 outStack.append("(");
10287 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10288 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10289 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10290 outStack.append(":");
10291 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10292 }
10293 }
10294 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010295 }
10296 }
10297 }
10298 }
10299
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010300 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010301 pw.println();
10302 pw.println("Total PSS by process:");
10303 dumpMemItems(pw, " ", procMems, true);
10304 pw.println();
10305 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010306 pw.println("Total PSS by OOM adjustment:");
10307 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010308 if (!oomOnly) {
10309 PrintWriter out = categoryPw != null ? categoryPw : pw;
10310 out.println();
10311 out.println("Total PSS by category:");
10312 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010313 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010314 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010315 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010316 final int[] SINGLE_LONG_FORMAT = new int[] {
10317 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10318 };
10319 long[] longOut = new long[1];
10320 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10321 SINGLE_LONG_FORMAT, null, longOut, null);
10322 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10323 longOut[0] = 0;
10324 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10325 SINGLE_LONG_FORMAT, null, longOut, null);
10326 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10327 longOut[0] = 0;
10328 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10329 SINGLE_LONG_FORMAT, null, longOut, null);
10330 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10331 longOut[0] = 0;
10332 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10333 SINGLE_LONG_FORMAT, null, longOut, null);
10334 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10335 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10336 pw.print(shared); pw.println(" kB");
10337 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10338 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 }
10341
10342 /**
10343 * Searches array of arguments for the specified string
10344 * @param args array of argument strings
10345 * @param value value to search for
10346 * @return true if the value is contained in the array
10347 */
10348 private static boolean scanArgs(String[] args, String value) {
10349 if (args != null) {
10350 for (String arg : args) {
10351 if (value.equals(arg)) {
10352 return true;
10353 }
10354 }
10355 }
10356 return false;
10357 }
10358
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010359 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10360 ContentProviderRecord cpr, boolean always) {
10361 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10362
10363 if (!inLaunching || always) {
10364 synchronized (cpr) {
10365 cpr.launchingApp = null;
10366 cpr.notifyAll();
10367 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010368 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010369 String names[] = cpr.info.authority.split(";");
10370 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010371 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010372 }
10373 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010374
10375 for (int i=0; i<cpr.connections.size(); i++) {
10376 ContentProviderConnection conn = cpr.connections.get(i);
10377 if (conn.waiting) {
10378 // If this connection is waiting for the provider, then we don't
10379 // need to mess with its process unless we are always removing
10380 // or for some reason the provider is not currently launching.
10381 if (inLaunching && !always) {
10382 continue;
10383 }
10384 }
10385 ProcessRecord capp = conn.client;
10386 conn.dead = true;
10387 if (conn.stableCount > 0) {
10388 if (!capp.persistent && capp.thread != null
10389 && capp.pid != 0
10390 && capp.pid != MY_PID) {
10391 Slog.i(TAG, "Kill " + capp.processName
10392 + " (pid " + capp.pid + "): provider " + cpr.info.name
10393 + " in dying process " + (proc != null ? proc.processName : "??"));
10394 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10395 capp.processName, capp.setAdj, "dying provider "
10396 + cpr.name.toShortString());
10397 Process.killProcessQuiet(capp.pid);
10398 }
10399 } else if (capp.thread != null && conn.provider.provider != null) {
10400 try {
10401 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10402 } catch (RemoteException e) {
10403 }
10404 // In the protocol here, we don't expect the client to correctly
10405 // clean up this connection, we'll just remove it.
10406 cpr.connections.remove(i);
10407 conn.client.conProviders.remove(conn);
10408 }
10409 }
10410
10411 if (inLaunching && always) {
10412 mLaunchingProviders.remove(cpr);
10413 }
10414 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 }
10416
10417 /**
10418 * Main code for cleaning up a process when it has gone away. This is
10419 * called both as a result of the process dying, or directly when stopping
10420 * a process when running in single process mode.
10421 */
10422 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010423 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010425 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 }
10427
Dianne Hackborn36124872009-10-08 16:22:03 -070010428 mProcessesToGc.remove(app);
10429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 // Dismiss any open dialogs.
10431 if (app.crashDialog != null) {
10432 app.crashDialog.dismiss();
10433 app.crashDialog = null;
10434 }
10435 if (app.anrDialog != null) {
10436 app.anrDialog.dismiss();
10437 app.anrDialog = null;
10438 }
10439 if (app.waitDialog != null) {
10440 app.waitDialog.dismiss();
10441 app.waitDialog = null;
10442 }
10443
10444 app.crashing = false;
10445 app.notResponding = false;
10446
10447 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010448 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 app.thread = null;
10450 app.forcingToForeground = null;
10451 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010452 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010453 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010454 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010456 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457
10458 boolean restart = false;
10459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 // Remove published content providers.
10461 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010462 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010463 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010464 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010465
10466 final boolean always = app.bad || !allowRestart;
10467 if (removeDyingProviderLocked(app, cpr, always) || always) {
10468 // We left the provider in the launching list, need to
10469 // restart it.
10470 restart = true;
10471 }
10472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010474 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 }
10476 app.pubProviders.clear();
10477 }
10478
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010479 // Take care of any launching providers waiting for this process.
10480 if (checkAppInLaunchingProvidersLocked(app, false)) {
10481 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010482 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 // Unregister from connected content providers.
10485 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010486 for (int i=0; i<app.conProviders.size(); i++) {
10487 ContentProviderConnection conn = app.conProviders.get(i);
10488 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 }
10490 app.conProviders.clear();
10491 }
10492
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010493 // At this point there may be remaining entries in mLaunchingProviders
10494 // where we were the only one waiting, so they are no longer of use.
10495 // Look for these and clean up if found.
10496 // XXX Commented out for now. Trying to figure out a way to reproduce
10497 // the actual situation to identify what is actually going on.
10498 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010499 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010500 ContentProviderRecord cpr = (ContentProviderRecord)
10501 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010502 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010503 synchronized (cpr) {
10504 cpr.launchingApp = null;
10505 cpr.notifyAll();
10506 }
10507 }
10508 }
10509 }
10510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010511 skipCurrentReceiverLocked(app);
10512
10513 // Unregister any receivers.
10514 if (app.receivers.size() > 0) {
10515 Iterator<ReceiverList> it = app.receivers.iterator();
10516 while (it.hasNext()) {
10517 removeReceiverLocked(it.next());
10518 }
10519 app.receivers.clear();
10520 }
10521
Christopher Tate181fafa2009-05-14 11:12:14 -070010522 // If the app is undergoing backup, tell the backup manager about it
10523 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010524 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010525 try {
10526 IBackupManager bm = IBackupManager.Stub.asInterface(
10527 ServiceManager.getService(Context.BACKUP_SERVICE));
10528 bm.agentDisconnected(app.info.packageName);
10529 } catch (RemoteException e) {
10530 // can't happen; backup manager is local
10531 }
10532 }
10533
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010534 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10535 ProcessChangeItem item = mPendingProcessChanges.get(i);
10536 if (item.pid == app.pid) {
10537 mPendingProcessChanges.remove(i);
10538 mAvailProcessChanges.add(item);
10539 }
10540 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010541 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010543 // If the caller is restarting this app, then leave it in its
10544 // current lists and let the caller take care of it.
10545 if (restarting) {
10546 return;
10547 }
10548
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010549 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010550 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010551 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010552 mProcessNames.remove(app.processName, app.uid);
10553 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010554 if (mHeavyWeightProcess == app) {
10555 mHeavyWeightProcess = null;
10556 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010558 } else if (!app.removed) {
10559 // This app is persistent, so we need to keep its record around.
10560 // If it is not already on the pending app list, add it there
10561 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10563 mPersistentStartingProcesses.add(app);
10564 restart = true;
10565 }
10566 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010567 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10568 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010569 mProcessesOnHold.remove(app);
10570
The Android Open Source Project4df24232009-03-05 14:34:35 -080010571 if (app == mHomeProcess) {
10572 mHomeProcess = null;
10573 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010574 if (app == mPreviousProcess) {
10575 mPreviousProcess = null;
10576 }
10577
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010578 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 // We have components that still need to be running in the
10580 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010581 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 startProcessLocked(app, "restart", app.processName);
10583 } else if (app.pid > 0 && app.pid != MY_PID) {
10584 // Goodbye!
10585 synchronized (mPidsSelfLocked) {
10586 mPidsSelfLocked.remove(app.pid);
10587 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10588 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010589 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010590 }
10591 }
10592
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010593 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10594 // Look through the content providers we are waiting to have launched,
10595 // and if any run in this process then either schedule a restart of
10596 // the process or kill the client waiting for it if this process has
10597 // gone bad.
10598 int NL = mLaunchingProviders.size();
10599 boolean restart = false;
10600 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010601 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010602 if (cpr.launchingApp == app) {
10603 if (!alwaysBad && !app.bad) {
10604 restart = true;
10605 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010606 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010607 NL = mLaunchingProviders.size();
10608 }
10609 }
10610 }
10611 return restart;
10612 }
10613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 // =========================================================
10615 // SERVICES
10616 // =========================================================
10617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10619 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010620 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010622 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010623 }
10624 }
10625
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010626 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010627 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010628 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010629 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010630 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010631 }
10632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010634 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010635 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 // Refuse possible leaked file descriptors
10637 if (service != null && service.hasFileDescriptors() == true) {
10638 throw new IllegalArgumentException("File descriptors passed in Intent");
10639 }
10640
Amith Yamasani742a6712011-05-04 14:49:28 -070010641 if (DEBUG_SERVICE)
10642 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010643 synchronized(this) {
10644 final int callingPid = Binder.getCallingPid();
10645 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010646 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010648 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010649 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 Binder.restoreCallingIdentity(origId);
10651 return res;
10652 }
10653 }
10654
10655 ComponentName startServiceInPackage(int uid,
10656 Intent service, String resolvedType) {
10657 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010658 if (DEBUG_SERVICE)
10659 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010661 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010662 resolvedType, -1, uid, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 Binder.restoreCallingIdentity(origId);
10664 return res;
10665 }
10666 }
10667
10668 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010669 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010670 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010671 // Refuse possible leaked file descriptors
10672 if (service != null && service.hasFileDescriptors() == true) {
10673 throw new IllegalArgumentException("File descriptors passed in Intent");
10674 }
10675
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010676 checkValidCaller(Binder.getCallingUid(), userId);
10677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010678 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010679 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 }
10682
10683 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010684 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010685 // Refuse possible leaked file descriptors
10686 if (service != null && service.hasFileDescriptors() == true) {
10687 throw new IllegalArgumentException("File descriptors passed in Intent");
10688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010689 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010690 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 }
10693
10694 public boolean stopServiceToken(ComponentName className, IBinder token,
10695 int startId) {
10696 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010697 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 }
10700
10701 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010702 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010704 mServices.setServiceForegroundLocked(className, token, id, notification,
10705 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010706 }
10707 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010708
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010709 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10710 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010711 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010712 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010713 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10714 if (ActivityManager.checkUidPermission(
10715 android.Manifest.permission.INTERACT_ACROSS_USERS,
10716 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10717 ComponentName comp = new ComponentName(aInfo.packageName, className);
10718 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10719 + " requests FLAG_SINGLE_USER, but app does not hold "
10720 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10721 Slog.w(TAG, msg);
10722 throw new SecurityException(msg);
10723 }
10724 result = true;
10725 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010726 } else if (componentProcessName == aInfo.packageName) {
10727 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10728 } else if ("system".equals(componentProcessName)) {
10729 result = true;
10730 }
10731 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010732 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10733 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010734 }
10735 return result;
10736 }
10737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 public int bindService(IApplicationThread caller, IBinder token,
10739 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010740 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010741 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 // Refuse possible leaked file descriptors
10743 if (service != null && service.hasFileDescriptors() == true) {
10744 throw new IllegalArgumentException("File descriptors passed in Intent");
10745 }
10746
Jeff Sharkey35744c12012-08-28 16:48:05 -070010747 if (userId != UserHandle.getCallingUserId()) {
10748 // Requesting a different user, make sure that they have permission
10749 if (checkComponentPermission(
10750 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10751 Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
10752 == PackageManager.PERMISSION_GRANTED) {
10753 // Translate to the current user id, if caller wasn't aware
10754 if (userId == UserHandle.USER_CURRENT) {
10755 userId = mCurrentUserId;
10756 }
10757 } else {
10758 String msg = "Permission Denial: Request to bindService as user " + userId
10759 + " but is calling from user " + UserHandle.getCallingUserId()
10760 + "; this requires "
10761 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
10762 Slog.w(TAG, msg);
10763 throw new SecurityException(msg);
10764 }
10765 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010768 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10769 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 }
10771 }
10772
10773 public boolean unbindService(IServiceConnection connection) {
10774 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010775 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 }
10778
10779 public void publishService(IBinder token, Intent intent, IBinder service) {
10780 // Refuse possible leaked file descriptors
10781 if (intent != null && intent.hasFileDescriptors() == true) {
10782 throw new IllegalArgumentException("File descriptors passed in Intent");
10783 }
10784
10785 synchronized(this) {
10786 if (!(token instanceof ServiceRecord)) {
10787 throw new IllegalArgumentException("Invalid service token");
10788 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010789 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 }
10791 }
10792
10793 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10794 // Refuse possible leaked file descriptors
10795 if (intent != null && intent.hasFileDescriptors() == true) {
10796 throw new IllegalArgumentException("File descriptors passed in Intent");
10797 }
10798
10799 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010800 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 }
10802 }
10803
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010804 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 synchronized(this) {
10806 if (!(token instanceof ServiceRecord)) {
10807 throw new IllegalArgumentException("Invalid service token");
10808 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010809 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 }
10812
10813 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010814 // BACKUP AND RESTORE
10815 // =========================================================
10816
10817 // Cause the target app to be launched if necessary and its backup agent
10818 // instantiated. The backup agent will invoke backupAgentCreated() on the
10819 // activity manager to announce its creation.
10820 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010821 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010822 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10823
10824 synchronized(this) {
10825 // !!! TODO: currently no check here that we're already bound
10826 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10827 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10828 synchronized (stats) {
10829 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10830 }
10831
Dianne Hackborne7f97212011-02-24 14:40:20 -080010832 // Backup agent is now in use, its package can't be stopped.
10833 try {
10834 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010835 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010836 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010837 } catch (IllegalArgumentException e) {
10838 Slog.w(TAG, "Failed trying to unstop package "
10839 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010840 }
10841
Christopher Tate181fafa2009-05-14 11:12:14 -070010842 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010843 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10844 ? new ComponentName(app.packageName, app.backupAgentName)
10845 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010846 // startProcessLocked() returns existing proc's record if it's already running
10847 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010848 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010849 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010850 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010851 return false;
10852 }
10853
10854 r.app = proc;
10855 mBackupTarget = r;
10856 mBackupAppName = app.packageName;
10857
Christopher Tate6fa95972009-06-05 18:43:55 -070010858 // Try not to kill the process during backup
10859 updateOomAdjLocked(proc);
10860
Christopher Tate181fafa2009-05-14 11:12:14 -070010861 // If the process is already attached, schedule the creation of the backup agent now.
10862 // If it is not yet live, this will be done when it attaches to the framework.
10863 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010864 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010865 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010866 proc.thread.scheduleCreateBackupAgent(app,
10867 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010868 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010869 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010870 }
10871 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010872 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010873 }
10874 // Invariants: at this point, the target app process exists and the application
10875 // is either already running or in the process of coming up. mBackupTarget and
10876 // mBackupAppName describe the app, so that when it binds back to the AM we
10877 // know that it's scheduled for a backup-agent operation.
10878 }
10879
10880 return true;
10881 }
10882
10883 // A backup agent has just come up
10884 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010885 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010886 + " = " + agent);
10887
10888 synchronized(this) {
10889 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010890 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010891 return;
10892 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010893 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010894
Dianne Hackborn06740692010-09-22 22:46:21 -070010895 long oldIdent = Binder.clearCallingIdentity();
10896 try {
10897 IBackupManager bm = IBackupManager.Stub.asInterface(
10898 ServiceManager.getService(Context.BACKUP_SERVICE));
10899 bm.agentConnected(agentPackageName, agent);
10900 } catch (RemoteException e) {
10901 // can't happen; the backup manager service is local
10902 } catch (Exception e) {
10903 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10904 e.printStackTrace();
10905 } finally {
10906 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010907 }
10908 }
10909
10910 // done with this agent
10911 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010912 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010913 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010914 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010915 return;
10916 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010917
10918 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010919 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010920 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010921 return;
10922 }
10923
Christopher Tate181fafa2009-05-14 11:12:14 -070010924 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010925 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010926 return;
10927 }
10928
Christopher Tate6fa95972009-06-05 18:43:55 -070010929 ProcessRecord proc = mBackupTarget.app;
10930 mBackupTarget = null;
10931 mBackupAppName = null;
10932
10933 // Not backing this app up any more; reset its OOM adjustment
10934 updateOomAdjLocked(proc);
10935
Christopher Tatec7b31e32009-06-10 15:49:30 -070010936 // If the app crashed during backup, 'thread' will be null here
10937 if (proc.thread != null) {
10938 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010939 proc.thread.scheduleDestroyBackupAgent(appInfo,
10940 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010941 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010942 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010943 e.printStackTrace();
10944 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010945 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010946 }
10947 }
10948 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010949 // BROADCASTS
10950 // =========================================================
10951
Josh Bartel7f208742010-02-25 11:01:44 -060010952 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 List cur) {
10954 final ContentResolver resolver = mContext.getContentResolver();
10955 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10956 if (list == null) {
10957 return cur;
10958 }
10959 int N = list.size();
10960 for (int i=0; i<N; i++) {
10961 Intent intent = list.get(i);
10962 if (filter.match(resolver, intent, true, TAG) >= 0) {
10963 if (cur == null) {
10964 cur = new ArrayList<Intent>();
10965 }
10966 cur.add(intent);
10967 }
10968 }
10969 return cur;
10970 }
10971
Christopher Tatef46723b2012-01-26 14:19:24 -080010972 boolean isPendingBroadcastProcessLocked(int pid) {
10973 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
10974 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
10975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976
Christopher Tatef46723b2012-01-26 14:19:24 -080010977 void skipPendingBroadcastLocked(int pid) {
10978 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
10979 for (BroadcastQueue queue : mBroadcastQueues) {
10980 queue.skipPendingBroadcastLocked(pid);
10981 }
10982 }
10983
10984 // The app just attached; send any pending broadcasts that it should receive
10985 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
10986 boolean didSomething = false;
10987 for (BroadcastQueue queue : mBroadcastQueues) {
10988 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010990 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 }
10992
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010993 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010995 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010996 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 synchronized(this) {
10998 ProcessRecord callerApp = null;
10999 if (caller != null) {
11000 callerApp = getRecordForAppLocked(caller);
11001 if (callerApp == null) {
11002 throw new SecurityException(
11003 "Unable to find app for caller " + caller
11004 + " (pid=" + Binder.getCallingPid()
11005 + ") when registering receiver " + receiver);
11006 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011007 if (callerApp.info.uid != Process.SYSTEM_UID &&
11008 !callerApp.pkgList.contains(callerPackage)) {
11009 throw new SecurityException("Given caller package " + callerPackage
11010 + " is not running in process " + callerApp);
11011 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011012 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011013 } else {
11014 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011015 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 }
11017
11018 List allSticky = null;
11019
11020 // Look for any matching sticky broadcasts...
11021 Iterator actions = filter.actionsIterator();
11022 if (actions != null) {
11023 while (actions.hasNext()) {
11024 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060011025 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 }
11027 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060011028 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 }
11030
11031 // The first sticky in the list is returned directly back to
11032 // the client.
11033 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11034
Joe Onorato8a9b2202010-02-26 18:56:32 -080011035 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 + ": " + sticky);
11037
11038 if (receiver == null) {
11039 return sticky;
11040 }
11041
11042 ReceiverList rl
11043 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11044 if (rl == null) {
11045 rl = new ReceiverList(this, callerApp,
11046 Binder.getCallingPid(),
11047 Binder.getCallingUid(), receiver);
11048 if (rl.app != null) {
11049 rl.app.receivers.add(rl);
11050 } else {
11051 try {
11052 receiver.asBinder().linkToDeath(rl, 0);
11053 } catch (RemoteException e) {
11054 return sticky;
11055 }
11056 rl.linkedToDeath = true;
11057 }
11058 mRegisteredReceivers.put(receiver.asBinder(), rl);
11059 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011060 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
11061 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 rl.add(bf);
11063 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011064 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 }
11066 mReceiverResolver.addFilter(bf);
11067
11068 // Enqueue broadcasts for all existing stickies that match
11069 // this filter.
11070 if (allSticky != null) {
11071 ArrayList receivers = new ArrayList();
11072 receivers.add(bf);
11073
11074 int N = allSticky.size();
11075 for (int i=0; i<N; i++) {
11076 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011077 BroadcastQueue queue = broadcastQueueForIntent(intent);
11078 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011080 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011081 queue.enqueueParallelBroadcastLocked(r);
11082 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 }
11084 }
11085
11086 return sticky;
11087 }
11088 }
11089
11090 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092
Christopher Tatef46723b2012-01-26 14:19:24 -080011093 final long origId = Binder.clearCallingIdentity();
11094 try {
11095 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096
Christopher Tatef46723b2012-01-26 14:19:24 -080011097 synchronized(this) {
11098 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011099 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011100 if (rl != null) {
11101 if (rl.curBroadcast != null) {
11102 BroadcastRecord r = rl.curBroadcast;
11103 final boolean doNext = finishReceiverLocked(
11104 receiver.asBinder(), r.resultCode, r.resultData,
11105 r.resultExtras, r.resultAbort, true);
11106 if (doNext) {
11107 doTrim = true;
11108 r.queue.processNextBroadcast(false);
11109 }
11110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011111
Christopher Tatef46723b2012-01-26 14:19:24 -080011112 if (rl.app != null) {
11113 rl.app.receivers.remove(rl);
11114 }
11115 removeReceiverLocked(rl);
11116 if (rl.linkedToDeath) {
11117 rl.linkedToDeath = false;
11118 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 }
11121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122
Christopher Tatef46723b2012-01-26 14:19:24 -080011123 // If we actually concluded any broadcasts, we might now be able
11124 // to trim the recipients' apps from our working set
11125 if (doTrim) {
11126 trimApplications();
11127 return;
11128 }
11129
11130 } finally {
11131 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 }
11134
11135 void removeReceiverLocked(ReceiverList rl) {
11136 mRegisteredReceivers.remove(rl.receiver.asBinder());
11137 int N = rl.size();
11138 for (int i=0; i<N; i++) {
11139 mReceiverResolver.removeFilter(rl.get(i));
11140 }
11141 }
11142
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011143 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
11144 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11145 ProcessRecord r = mLruProcesses.get(i);
11146 if (r.thread != null) {
11147 try {
11148 r.thread.dispatchPackageBroadcast(cmd, packages);
11149 } catch (RemoteException ex) {
11150 }
11151 }
11152 }
11153 }
11154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 private final int broadcastIntentLocked(ProcessRecord callerApp,
11156 String callerPackage, Intent intent, String resolvedType,
11157 IIntentReceiver resultTo, int resultCode, String resultData,
11158 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011159 boolean ordered, boolean sticky, int callingPid, int callingUid,
11160 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 intent = new Intent(intent);
11162
Dianne Hackborne7f97212011-02-24 14:40:20 -080011163 // By default broadcasts do not go to stopped apps.
11164 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11165
Joe Onorato8a9b2202010-02-26 18:56:32 -080011166 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011168 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011170 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011172
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011173 // If the caller is trying to send this broadcast to a different
11174 // user, verify that is allowed.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011175 if (UserHandle.getUserId(callingUid) != userId) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011176 if (checkComponentPermission(
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011177 android.Manifest.permission.INTERACT_ACROSS_USERS,
11178 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED
11179 && checkComponentPermission(
11180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11181 callingPid, callingUid, -1, true)
11182 != PackageManager.PERMISSION_GRANTED) {
11183 String msg = "Permission Denial: " + intent.getAction()
11184 + " broadcast from " + callerPackage
11185 + " asks to send as user " + userId
11186 + " but is calling from user " + UserHandle.getUserId(callingUid)
11187 + "; this requires "
11188 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11189 Slog.w(TAG, msg);
11190 throw new SecurityException(msg);
11191 } else {
11192 if (userId == UserHandle.USER_CURRENT) {
11193 userId = mCurrentUserId;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011194 }
11195 }
11196 }
11197
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011198 // Make sure that the user who is receiving this broadcast is started
11199 // If not, we will just skip it.
11200 if (mStartedUsers.get(userId) == null) {
11201 Slog.w(TAG, "Skipping broadcast of " + intent
11202 + ": user " + userId + " is stopped");
11203 return ActivityManager.BROADCAST_SUCCESS;
11204 }
11205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206 // Handle special intents: if this broadcast is from the package
11207 // manager about a package being removed, we need to remove all of
11208 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011209 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011210 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011211 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11212 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011213 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 || uidRemoved) {
11215 if (checkComponentPermission(
11216 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011217 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011218 == PackageManager.PERMISSION_GRANTED) {
11219 if (uidRemoved) {
11220 final Bundle intentExtras = intent.getExtras();
11221 final int uid = intentExtras != null
11222 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11223 if (uid >= 0) {
11224 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11225 synchronized (bs) {
11226 bs.removeUidStatsLocked(uid);
11227 }
11228 }
11229 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011230 // If resources are unvailble just force stop all
11231 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011232 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011233 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11234 if (list != null && (list.length > 0)) {
11235 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011236 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011237 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011238 sendPackageBroadcastLocked(
11239 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011240 }
11241 } else {
11242 Uri data = intent.getData();
11243 String ssp;
11244 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11245 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11246 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011247 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11248 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011249 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011250 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011251 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11252 new String[] {ssp});
11253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 }
11255 }
11256 }
11257 } else {
11258 String msg = "Permission Denial: " + intent.getAction()
11259 + " broadcast from " + callerPackage + " (pid=" + callingPid
11260 + ", uid=" + callingUid + ")"
11261 + " requires "
11262 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011263 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 throw new SecurityException(msg);
11265 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011266
11267 // Special case for adding a package: by default turn on compatibility
11268 // mode.
11269 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011270 Uri data = intent.getData();
11271 String ssp;
11272 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11273 mCompatModePackages.handlePackageAddedLocked(ssp,
11274 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 }
11277
11278 /*
11279 * If this is the time zone changed action, queue up a message that will reset the timezone
11280 * of all currently running processes. This message will get queued up before the broadcast
11281 * happens.
11282 */
11283 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11284 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11285 }
11286
Robert Greenwalt03595d02010-11-02 14:08:23 -070011287 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11288 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11289 }
11290
Robert Greenwalt434203a2010-10-11 16:00:27 -070011291 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11292 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11293 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11294 }
11295
Dianne Hackborn854060af2009-07-09 18:14:31 -070011296 /*
11297 * Prevent non-system code (defined here to be non-persistent
11298 * processes) from sending protected broadcasts.
11299 */
11300 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070011301 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11302 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070011303 // Always okay.
11304 } else if (callerApp == null || !callerApp.persistent) {
11305 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011306 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011307 intent.getAction())) {
11308 String msg = "Permission Denial: not allowed to send broadcast "
11309 + intent.getAction() + " from pid="
11310 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011312 throw new SecurityException(msg);
11313 }
11314 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011315 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011316 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070011317 }
11318 }
11319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 // Add to the sticky list if requested.
11321 if (sticky) {
11322 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11323 callingPid, callingUid)
11324 != PackageManager.PERMISSION_GRANTED) {
11325 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11326 + callingPid + ", uid=" + callingUid
11327 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011328 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 throw new SecurityException(msg);
11330 }
11331 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011332 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011334 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 }
11336 if (intent.getComponent() != null) {
11337 throw new SecurityException(
11338 "Sticky broadcasts can't target a specific component");
11339 }
11340 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11341 if (list == null) {
11342 list = new ArrayList<Intent>();
11343 mStickyBroadcasts.put(intent.getAction(), list);
11344 }
11345 int N = list.size();
11346 int i;
11347 for (i=0; i<N; i++) {
11348 if (intent.filterEquals(list.get(i))) {
11349 // This sticky already exists, replace it.
11350 list.set(i, new Intent(intent));
11351 break;
11352 }
11353 }
11354 if (i >= N) {
11355 list.add(new Intent(intent));
11356 }
11357 }
11358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359 // Figure out who all will receive this broadcast.
11360 List receivers = null;
11361 List<BroadcastFilter> registeredReceivers = null;
11362 try {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011363 // Need to resolve the intent to interested receivers...
11364 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11365 == 0) {
11366 receivers = AppGlobals.getPackageManager().queryIntentReceivers(
11367 intent, resolvedType, STOCK_PM_FLAGS, userId);
11368 }
11369 if (intent.getComponent() == null) {
11370 registeredReceivers = mReceiverResolver.queryIntent(intent,
11371 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 }
11373 } catch (RemoteException ex) {
11374 // pm is in same process, this will never happen.
11375 }
11376
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011377 final boolean replacePending =
11378 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11379
Joe Onorato8a9b2202010-02-26 18:56:32 -080011380 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011381 + " replacePending=" + replacePending);
11382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011383 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11384 if (!ordered && NR > 0) {
11385 // If we are not serializing this broadcast, then send the
11386 // registered receivers separately so they don't wait for the
11387 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011388 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11389 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 callerPackage, callingPid, callingUid, requiredPermission,
11391 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011392 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011393 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011394 TAG, "Enqueueing parallel broadcast " + r);
11395 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011396 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011397 queue.enqueueParallelBroadcastLocked(r);
11398 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 registeredReceivers = null;
11401 NR = 0;
11402 }
11403
11404 // Merge into one list.
11405 int ir = 0;
11406 if (receivers != null) {
11407 // A special case for PACKAGE_ADDED: do not allow the package
11408 // being added to see this broadcast. This prevents them from
11409 // using this as a back door to get run as soon as they are
11410 // installed. Maybe in the future we want to have a special install
11411 // broadcast or such for apps, but we'd like to deliberately make
11412 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011413 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011414 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11415 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11416 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011417 Uri data = intent.getData();
11418 if (data != null) {
11419 String pkgName = data.getSchemeSpecificPart();
11420 if (pkgName != null) {
11421 skipPackages = new String[] { pkgName };
11422 }
11423 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011424 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011425 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011426 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011427 if (skipPackages != null && (skipPackages.length > 0)) {
11428 for (String skipPackage : skipPackages) {
11429 if (skipPackage != null) {
11430 int NT = receivers.size();
11431 for (int it=0; it<NT; it++) {
11432 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11433 if (curt.activityInfo.packageName.equals(skipPackage)) {
11434 receivers.remove(it);
11435 it--;
11436 NT--;
11437 }
11438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 }
11440 }
11441 }
11442
11443 int NT = receivers != null ? receivers.size() : 0;
11444 int it = 0;
11445 ResolveInfo curt = null;
11446 BroadcastFilter curr = null;
11447 while (it < NT && ir < NR) {
11448 if (curt == null) {
11449 curt = (ResolveInfo)receivers.get(it);
11450 }
11451 if (curr == null) {
11452 curr = registeredReceivers.get(ir);
11453 }
11454 if (curr.getPriority() >= curt.priority) {
11455 // Insert this broadcast record into the final list.
11456 receivers.add(it, curr);
11457 ir++;
11458 curr = null;
11459 it++;
11460 NT++;
11461 } else {
11462 // Skip to the next ResolveInfo in the final list.
11463 it++;
11464 curt = null;
11465 }
11466 }
11467 }
11468 while (ir < NR) {
11469 if (receivers == null) {
11470 receivers = new ArrayList();
11471 }
11472 receivers.add(registeredReceivers.get(ir));
11473 ir++;
11474 }
11475
11476 if ((receivers != null && receivers.size() > 0)
11477 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011478 BroadcastQueue queue = broadcastQueueForIntent(intent);
11479 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011481 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011482 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011483 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011484 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011485 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 if (DEBUG_BROADCAST) {
11487 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011488 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011490 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011491 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011492 queue.enqueueOrderedBroadcastLocked(r);
11493 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011495 }
11496
Dianne Hackborna4972e92012-03-14 10:38:05 -070011497 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498 }
11499
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011500 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011501 // Refuse possible leaked file descriptors
11502 if (intent != null && intent.hasFileDescriptors() == true) {
11503 throw new IllegalArgumentException("File descriptors passed in Intent");
11504 }
11505
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011506 int flags = intent.getFlags();
11507
11508 if (!mProcessesReady) {
11509 // if the caller really truly claims to know what they're doing, go
11510 // ahead and allow the broadcast without launching any receivers
11511 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11512 intent = new Intent(intent);
11513 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11514 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11515 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11516 + " before boot completion");
11517 throw new IllegalStateException("Cannot broadcast before boot completed");
11518 }
11519 }
11520
11521 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11522 throw new IllegalArgumentException(
11523 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11524 }
11525
11526 return intent;
11527 }
11528
11529 public final int broadcastIntent(IApplicationThread caller,
11530 Intent intent, String resolvedType, IIntentReceiver resultTo,
11531 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011532 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011533 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011535 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11538 final int callingPid = Binder.getCallingPid();
11539 final int callingUid = Binder.getCallingUid();
11540 final long origId = Binder.clearCallingIdentity();
11541 int res = broadcastIntentLocked(callerApp,
11542 callerApp != null ? callerApp.info.packageName : null,
11543 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011544 resultCode, resultData, map, requiredPermission, serialized, sticky,
11545 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 Binder.restoreCallingIdentity(origId);
11547 return res;
11548 }
11549 }
11550
11551 int broadcastIntentInPackage(String packageName, int uid,
11552 Intent intent, String resolvedType, IIntentReceiver resultTo,
11553 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011554 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011556 intent = verifyBroadcastLocked(intent);
11557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 final long origId = Binder.clearCallingIdentity();
11559 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11560 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011561 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 Binder.restoreCallingIdentity(origId);
11563 return res;
11564 }
11565 }
11566
Amith Yamasani742a6712011-05-04 14:49:28 -070011567 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
11568 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569 // Refuse possible leaked file descriptors
11570 if (intent != null && intent.hasFileDescriptors() == true) {
11571 throw new IllegalArgumentException("File descriptors passed in Intent");
11572 }
11573
11574 synchronized(this) {
11575 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11576 != PackageManager.PERMISSION_GRANTED) {
11577 String msg = "Permission Denial: unbroadcastIntent() from pid="
11578 + Binder.getCallingPid()
11579 + ", uid=" + Binder.getCallingUid()
11580 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011581 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 throw new SecurityException(msg);
11583 }
11584 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11585 if (list != null) {
11586 int N = list.size();
11587 int i;
11588 for (i=0; i<N; i++) {
11589 if (intent.filterEquals(list.get(i))) {
11590 list.remove(i);
11591 break;
11592 }
11593 }
11594 }
11595 }
11596 }
11597
11598 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11599 String resultData, Bundle resultExtras, boolean resultAbort,
11600 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011601 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11602 if (r == null) {
11603 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 return false;
11605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606
Christopher Tatef46723b2012-01-26 14:19:24 -080011607 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11608 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 }
11610
11611 public void finishReceiver(IBinder who, int resultCode, String resultData,
11612 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011613 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614
11615 // Refuse possible leaked file descriptors
11616 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11617 throw new IllegalArgumentException("File descriptors passed in Bundle");
11618 }
11619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011621 try {
11622 boolean doNext = false;
11623 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624
Christopher Tatef46723b2012-01-26 14:19:24 -080011625 synchronized(this) {
11626 r = broadcastRecordForReceiverLocked(who);
11627 if (r != null) {
11628 doNext = r.queue.finishReceiverLocked(r, resultCode,
11629 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011631 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011632
Christopher Tatef46723b2012-01-26 14:19:24 -080011633 if (doNext) {
11634 r.queue.processNextBroadcast(false);
11635 }
11636 trimApplications();
11637 } finally {
11638 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 // =========================================================
11643 // INSTRUMENTATION
11644 // =========================================================
11645
11646 public boolean startInstrumentation(ComponentName className,
11647 String profileFile, int flags, Bundle arguments,
11648 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011649 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 // Refuse possible leaked file descriptors
11651 if (arguments != null && arguments.hasFileDescriptors()) {
11652 throw new IllegalArgumentException("File descriptors passed in Bundle");
11653 }
11654
11655 synchronized(this) {
11656 InstrumentationInfo ii = null;
11657 ApplicationInfo ai = null;
11658 try {
11659 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011660 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011662 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011663 } catch (PackageManager.NameNotFoundException e) {
11664 }
11665 if (ii == null) {
11666 reportStartInstrumentationFailure(watcher, className,
11667 "Unable to find instrumentation info for: " + className);
11668 return false;
11669 }
11670 if (ai == null) {
11671 reportStartInstrumentationFailure(watcher, className,
11672 "Unable to find instrumentation target package: " + ii.targetPackage);
11673 return false;
11674 }
11675
11676 int match = mContext.getPackageManager().checkSignatures(
11677 ii.targetPackage, ii.packageName);
11678 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11679 String msg = "Permission Denial: starting instrumentation "
11680 + className + " from pid="
11681 + Binder.getCallingPid()
11682 + ", uid=" + Binder.getCallingPid()
11683 + " not allowed because package " + ii.packageName
11684 + " does not have a signature matching the target "
11685 + ii.targetPackage;
11686 reportStartInstrumentationFailure(watcher, className, msg);
11687 throw new SecurityException(msg);
11688 }
11689
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011690 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011692 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011693 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011694 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011696 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 app.instrumentationProfileFile = profileFile;
11698 app.instrumentationArguments = arguments;
11699 app.instrumentationWatcher = watcher;
11700 app.instrumentationResultClass = className;
11701 Binder.restoreCallingIdentity(origId);
11702 }
11703
11704 return true;
11705 }
11706
11707 /**
11708 * Report errors that occur while attempting to start Instrumentation. Always writes the
11709 * error to the logs, but if somebody is watching, send the report there too. This enables
11710 * the "am" command to report errors with more information.
11711 *
11712 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11713 * @param cn The component name of the instrumentation.
11714 * @param report The error report.
11715 */
11716 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11717 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011718 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 try {
11720 if (watcher != null) {
11721 Bundle results = new Bundle();
11722 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11723 results.putString("Error", report);
11724 watcher.instrumentationStatus(cn, -1, results);
11725 }
11726 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011727 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 }
11729 }
11730
11731 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11732 if (app.instrumentationWatcher != null) {
11733 try {
11734 // NOTE: IInstrumentationWatcher *must* be oneway here
11735 app.instrumentationWatcher.instrumentationFinished(
11736 app.instrumentationClass,
11737 resultCode,
11738 results);
11739 } catch (RemoteException e) {
11740 }
11741 }
11742 app.instrumentationWatcher = null;
11743 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011744 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 app.instrumentationProfileFile = null;
11746 app.instrumentationArguments = null;
11747
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011748 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 }
11750
11751 public void finishInstrumentation(IApplicationThread target,
11752 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011753 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 // Refuse possible leaked file descriptors
11755 if (results != null && results.hasFileDescriptors()) {
11756 throw new IllegalArgumentException("File descriptors passed in Intent");
11757 }
11758
11759 synchronized(this) {
11760 ProcessRecord app = getRecordForAppLocked(target);
11761 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011762 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 return;
11764 }
11765 final long origId = Binder.clearCallingIdentity();
11766 finishInstrumentationLocked(app, resultCode, results);
11767 Binder.restoreCallingIdentity(origId);
11768 }
11769 }
11770
11771 // =========================================================
11772 // CONFIGURATION
11773 // =========================================================
11774
11775 public ConfigurationInfo getDeviceConfigurationInfo() {
11776 ConfigurationInfo config = new ConfigurationInfo();
11777 synchronized (this) {
11778 config.reqTouchScreen = mConfiguration.touchscreen;
11779 config.reqKeyboardType = mConfiguration.keyboard;
11780 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011781 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11782 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11784 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011785 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11786 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11788 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011789 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790 }
11791 return config;
11792 }
11793
11794 public Configuration getConfiguration() {
11795 Configuration ci;
11796 synchronized(this) {
11797 ci = new Configuration(mConfiguration);
11798 }
11799 return ci;
11800 }
11801
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011802 public void updatePersistentConfiguration(Configuration values) {
11803 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11804 "updateConfiguration()");
11805 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11806 "updateConfiguration()");
11807 if (values == null) {
11808 throw new NullPointerException("Configuration must not be null");
11809 }
11810
11811 synchronized(this) {
11812 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011813 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011814 Binder.restoreCallingIdentity(origId);
11815 }
11816 }
11817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 public void updateConfiguration(Configuration values) {
11819 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11820 "updateConfiguration()");
11821
11822 synchronized(this) {
11823 if (values == null && mWindowManager != null) {
11824 // sentinel: fetch the current configuration from the window manager
11825 values = mWindowManager.computeNewConfiguration();
11826 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011827
11828 if (mWindowManager != null) {
11829 mProcessList.applyDisplaySize(mWindowManager);
11830 }
11831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011833 if (values != null) {
11834 Settings.System.clearConfiguration(values);
11835 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011836 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 Binder.restoreCallingIdentity(origId);
11838 }
11839 }
11840
11841 /**
11842 * Do either or both things: (1) change the current configuration, and (2)
11843 * make sure the given activity is running with the (now) current
11844 * configuration. Returns true if the activity has been left running, or
11845 * false if <var>starting</var> is being destroyed to match the new
11846 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011847 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011849 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011850 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011851 // do nothing if we are headless
11852 if (mHeadless) return true;
11853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011854 int changes = 0;
11855
11856 boolean kept = true;
11857
11858 if (values != null) {
11859 Configuration newConfig = new Configuration(mConfiguration);
11860 changes = newConfig.updateFrom(values);
11861 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011862 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011863 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 }
11865
Doug Zongker2bec3d42009-12-04 12:52:44 -080011866 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867
Dianne Hackborn813075a62011-11-14 17:45:19 -080011868 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011869 saveLocaleLocked(values.locale,
11870 !values.locale.equals(mConfiguration.locale),
11871 values.userSetLocale);
11872 }
11873
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011874 mConfigurationSeq++;
11875 if (mConfigurationSeq <= 0) {
11876 mConfigurationSeq = 1;
11877 }
11878 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011879 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011880 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011881
11882 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070011883
11884 // TODO: If our config changes, should we auto dismiss any currently
11885 // showing dialogs?
11886 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011887
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011888 AttributeCache ac = AttributeCache.instance();
11889 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080011890 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011892
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011893 // Make sure all resources in our process are updated
11894 // right now, so that anyone who is going to retrieve
11895 // resource values after we return will be sure to get
11896 // the new ones. This is especially important during
11897 // boot, where the first config change needs to guarantee
11898 // all resources have that config before following boot
11899 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080011900 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011901
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011902 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011903 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011904 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011905 mHandler.sendMessage(msg);
11906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011907
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011908 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11909 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011910 try {
11911 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011912 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011913 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011914 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 }
11916 } catch (Exception e) {
11917 }
11918 }
11919 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011920 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11921 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011923 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011924 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11925 broadcastIntentLocked(null, null,
11926 new Intent(Intent.ACTION_LOCALE_CHANGED),
11927 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011928 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930 }
11931 }
11932
11933 if (changes != 0 && starting == null) {
11934 // If the configuration changed, and the caller is not already
11935 // in the process of starting an activity, then find the top
11936 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011937 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 }
11939
11940 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011941 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011942 // And we need to make sure at this point that all other activities
11943 // are made visible with the correct configuration.
11944 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 }
11946
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011947 if (values != null && mWindowManager != null) {
11948 mWindowManager.setNewConfiguration(mConfiguration);
11949 }
11950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 return kept;
11952 }
Joe Onorato54a4a412011-11-02 20:50:08 -070011953
11954 /**
11955 * Decide based on the configuration whether we should shouw the ANR,
11956 * crash, etc dialogs. The idea is that if there is no affordnace to
11957 * press the on-screen buttons, we shouldn't show the dialog.
11958 *
11959 * A thought: SystemUI might also want to get told about this, the Power
11960 * dialog / global actions also might want different behaviors.
11961 */
11962 private static final boolean shouldShowDialogs(Configuration config) {
11963 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
11964 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
11965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966
11967 /**
11968 * Save the locale. You must be inside a synchronized (this) block.
11969 */
11970 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11971 if(isDiff) {
11972 SystemProperties.set("user.language", l.getLanguage());
11973 SystemProperties.set("user.region", l.getCountry());
11974 }
11975
11976 if(isPersist) {
11977 SystemProperties.set("persist.sys.language", l.getLanguage());
11978 SystemProperties.set("persist.sys.country", l.getCountry());
11979 SystemProperties.set("persist.sys.localevar", l.getVariant());
11980 }
11981 }
11982
Adam Powelldd8fab22012-03-22 17:47:27 -070011983 @Override
11984 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
11985 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011986 return srec != null && srec.task.affinity != null &&
11987 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070011988 }
11989
11990 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
11991 Intent resultData) {
11992 ComponentName dest = destIntent.getComponent();
11993
11994 synchronized (this) {
11995 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011996 if (srec == null) {
11997 return false;
11998 }
Adam Powelldd8fab22012-03-22 17:47:27 -070011999 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12000 final int start = history.indexOf(srec);
12001 if (start < 0) {
12002 // Current activity is not in history stack; do nothing.
12003 return false;
12004 }
12005 int finishTo = start - 1;
12006 ActivityRecord parent = null;
12007 boolean foundParentInTask = false;
12008 if (dest != null) {
12009 TaskRecord tr = srec.task;
12010 for (int i = start - 1; i >= 0; i--) {
12011 ActivityRecord r = history.get(i);
12012 if (tr != r.task) {
12013 // Couldn't find parent in the same task; stop at the one above this.
12014 // (Root of current task; in-app "home" behavior)
12015 // Always at least finish the current activity.
12016 finishTo = Math.min(start - 1, i + 1);
12017 parent = history.get(finishTo);
12018 break;
12019 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12020 r.info.name.equals(dest.getClassName())) {
12021 finishTo = i;
12022 parent = r;
12023 foundParentInTask = true;
12024 break;
12025 }
12026 }
12027 }
12028
12029 if (mController != null) {
12030 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12031 if (next != null) {
12032 // ask watcher if this is allowed
12033 boolean resumeOK = true;
12034 try {
12035 resumeOK = mController.activityResuming(next.packageName);
12036 } catch (RemoteException e) {
12037 mController = null;
12038 }
12039
12040 if (!resumeOK) {
12041 return false;
12042 }
12043 }
12044 }
12045 final long origId = Binder.clearCallingIdentity();
12046 for (int i = start; i > finishTo; i--) {
12047 ActivityRecord r = history.get(i);
12048 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12049 "navigate-up");
12050 // Only return the supplied result for the first activity finished
12051 resultCode = Activity.RESULT_CANCELED;
12052 resultData = null;
12053 }
12054
12055 if (parent != null && foundParentInTask) {
12056 final int parentLaunchMode = parent.info.launchMode;
12057 final int destIntentFlags = destIntent.getFlags();
12058 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12059 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12060 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12061 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012062 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012063 } else {
12064 try {
12065 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012066 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012067 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12068 null, aInfo, parent.appToken, null,
12069 0, -1, parent.launchedFromUid, 0, null, true, null);
12070 foundParentInTask = res == ActivityManager.START_SUCCESS;
12071 } catch (RemoteException e) {
12072 foundParentInTask = false;
12073 }
12074 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12075 resultData, "navigate-up");
12076 }
12077 }
12078 Binder.restoreCallingIdentity(origId);
12079 return foundParentInTask;
12080 }
12081 }
12082
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012083 public int getLaunchedFromUid(IBinder activityToken) {
12084 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12085 if (srec == null) {
12086 return -1;
12087 }
12088 return srec.launchedFromUid;
12089 }
12090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091 // =========================================================
12092 // LIFETIME MANAGEMENT
12093 // =========================================================
12094
Christopher Tatef46723b2012-01-26 14:19:24 -080012095 // Returns which broadcast queue the app is the current [or imminent] receiver
12096 // on, or 'null' if the app is not an active broadcast recipient.
12097 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12098 BroadcastRecord r = app.curReceiver;
12099 if (r != null) {
12100 return r.queue;
12101 }
12102
12103 // It's not the current receiver, but it might be starting up to become one
12104 synchronized (this) {
12105 for (BroadcastQueue queue : mBroadcastQueues) {
12106 r = queue.mPendingBroadcast;
12107 if (r != null && r.curApp == app) {
12108 // found it; report which queue it's in
12109 return queue;
12110 }
12111 }
12112 }
12113
12114 return null;
12115 }
12116
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012117 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012118 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012120 // This adjustment has already been computed. If we are calling
12121 // from the top, we may have already computed our adjustment with
12122 // an earlier hidden adjustment that isn't really for us... if
12123 // so, use the new hidden adjustment.
12124 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012125 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12126 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012127 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012128 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012129 }
12130
12131 if (app.thread == null) {
12132 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012133 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012134 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012135 }
12136
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012137 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12138 app.adjSource = null;
12139 app.adjTarget = null;
12140 app.empty = false;
12141 app.hidden = false;
12142
12143 final int activitiesSize = app.activities.size();
12144
Dianne Hackborn7d608422011-08-07 16:24:18 -070012145 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012146 // The max adjustment doesn't allow this app to be anything
12147 // below foreground, so it is not worth doing work for it.
12148 app.adjType = "fixed";
12149 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012150 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012151 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012152 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012153 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012154 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012155 // System process can do UI, and when they do we want to have
12156 // them trim their memory after the user leaves the UI. To
12157 // facilitate this, here we need to determine whether or not it
12158 // is currently showing UI.
12159 app.systemNoUi = true;
12160 if (app == TOP_APP) {
12161 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012162 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012163 } else if (activitiesSize > 0) {
12164 for (int j = 0; j < activitiesSize; j++) {
12165 final ActivityRecord r = app.activities.get(j);
12166 if (r.visible) {
12167 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012168 }
12169 if (r.app == app) {
12170 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012171 }
12172 }
12173 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012174 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012175 }
12176
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012177 app.keeping = false;
12178 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012179 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180
The Android Open Source Project4df24232009-03-05 14:34:35 -080012181 // Determine the importance of the process, starting with most
12182 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012184 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012185 boolean foregroundActivities = false;
12186 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012187 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012188 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012190 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012191 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012192 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012193 foregroundActivities = true;
12194 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012195 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012196 } else if (app.instrumentationClass != null) {
12197 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012198 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012199 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012200 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012201 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012202 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012204 // counts as being in the foreground for OOM killer purposes.
12205 // It's placed in a sched group based on the nature of the
12206 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012207 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012208 schedGroup = (queue == mFgBroadcastQueue)
12209 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012210 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211 } else if (app.executingServices.size() > 0) {
12212 // An app that is currently executing a service callback also
12213 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012214 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012215 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012216 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012217 } else {
12218 // Assume process is hidden (has activities); we will correct
12219 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012221 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012222 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012223 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012225
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012226 boolean hasStoppingActivities = false;
12227
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012228 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012229 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012230 for (int j = 0; j < activitiesSize; j++) {
12231 final ActivityRecord r = app.activities.get(j);
12232 if (r.visible) {
12233 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012234 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12235 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012236 app.adjType = "visible";
12237 }
12238 schedGroup = Process.THREAD_GROUP_DEFAULT;
12239 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012240 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012241 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012242 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012243 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012244 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12245 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012246 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012247 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012248 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012249 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012250 } else if (r.state == ActivityState.STOPPING) {
12251 // We will apply the actual adjustment later, because
12252 // we want to allow this process to immediately go through
12253 // any memory trimming that is in effect.
12254 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012255 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012256 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012257 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012258 if (r.app == app) {
12259 app.hasActivities = true;
12260 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012261 }
12262 }
12263
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012264 if (adj == hiddenAdj && !app.hasActivities) {
12265 // Whoops, this process is completely empty as far as we know
12266 // at this point.
12267 adj = emptyAdj;
12268 app.empty = true;
12269 app.adjType = "bg-empty";
12270 }
12271
Dianne Hackborn7d608422011-08-07 16:24:18 -070012272 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012273 if (app.foregroundServices) {
12274 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012275 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012276 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012277 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012278 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012279 } else if (app.forcingToForeground != null) {
12280 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012281 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012282 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012283 app.adjType = "force-foreground";
12284 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012285 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012286 }
12287 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012288
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012289 if (app.foregroundServices) {
12290 interesting = true;
12291 }
12292
Dianne Hackborn7d608422011-08-07 16:24:18 -070012293 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012294 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012295 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012296 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012297 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012298 app.adjType = "heavy";
12299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012300
Dianne Hackborn7d608422011-08-07 16:24:18 -070012301 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012302 // This process is hosting what we currently consider to be the
12303 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012304 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012305 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012306 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012307 app.adjType = "home";
12308 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012309
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012310 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12311 && app.activities.size() > 0) {
12312 // This was the previous process that showed UI to the user.
12313 // We want to try to keep it around more aggressively, to give
12314 // a good experience around switching between two apps.
12315 adj = ProcessList.PREVIOUS_APP_ADJ;
12316 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12317 app.hidden = false;
12318 app.adjType = "previous";
12319 }
12320
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012321 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12322 + " reason=" + app.adjType);
12323
The Android Open Source Project4df24232009-03-05 14:34:35 -080012324 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 // there are applications dependent on our services or providers, but
12326 // this gives us a baseline and makes sure we don't get into an
12327 // infinite recursion.
12328 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012329 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330
Christopher Tate6fa95972009-06-05 18:43:55 -070012331 if (mBackupTarget != null && app == mBackupTarget.app) {
12332 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012333 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012334 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012335 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012336 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012337 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012338 }
12339 }
12340
Dianne Hackborn7d608422011-08-07 16:24:18 -070012341 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012342 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 final long now = SystemClock.uptimeMillis();
12344 // This process is more important if the top activity is
12345 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012346 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012347 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012348 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012350 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012351 // If this process has shown some UI, let it immediately
12352 // go to the LRU list because it may be pretty heavy with
12353 // UI stuff. We'll tag it with a label just to help
12354 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012355 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012356 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012358 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012359 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012360 // This service has seen some activity within
12361 // recent memory, so we will keep its process ahead
12362 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012363 if (adj > ProcessList.SERVICE_ADJ) {
12364 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012365 app.adjType = "started-services";
12366 app.hidden = false;
12367 }
12368 }
12369 // If we have let the service slide into the background
12370 // state, still have some text describing what it is doing
12371 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012372 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012373 app.adjType = "started-bg-services";
12374 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012375 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012376 // Don't kill this process because it is doing work; it
12377 // has said it is doing work.
12378 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012379 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012380 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012381 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012382 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012384 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012385 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012386 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012387 // XXX should compute this based on the max of
12388 // all connected clients.
12389 ConnectionRecord cr = clist.get(i);
12390 if (cr.binding.client == app) {
12391 // Binding to ourself is not interesting.
12392 continue;
12393 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012394 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012395 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012396 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012397 int myHiddenAdj = hiddenAdj;
12398 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012399 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012400 myHiddenAdj = client.hiddenAdj;
12401 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012402 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012403 }
12404 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012405 int myEmptyAdj = emptyAdj;
12406 if (myEmptyAdj > client.emptyAdj) {
12407 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12408 myEmptyAdj = client.emptyAdj;
12409 } else {
12410 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12411 }
12412 }
12413 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12414 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012415 String adjType = null;
12416 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12417 // Not doing bind OOM management, so treat
12418 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012419 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012420 // If this process has shown some UI, let it immediately
12421 // go to the LRU list because it may be pretty heavy with
12422 // UI stuff. We'll tag it with a label just to help
12423 // debug and understand what is going on.
12424 if (adj > clientAdj) {
12425 adjType = "bound-bg-ui-services";
12426 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012427 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012428 clientAdj = adj;
12429 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012430 if (now >= (s.lastActivity
12431 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012432 // This service has not seen activity within
12433 // recent memory, so allow it to drop to the
12434 // LRU list if there is no other reason to keep
12435 // it around. We'll also tag it with a label just
12436 // to help debug and undertand what is going on.
12437 if (adj > clientAdj) {
12438 adjType = "bound-bg-services";
12439 }
12440 clientAdj = adj;
12441 }
12442 }
12443 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012444 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012445 // If this process has recently shown UI, and
12446 // the process that is binding to it is less
12447 // important than being visible, then we don't
12448 // care about the binding as much as we care
12449 // about letting this process get into the LRU
12450 // list to be killed and restarted if needed for
12451 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012452 if (app.hasShownUi && app != mHomeProcess
12453 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012454 adjType = "bound-bg-ui-services";
12455 } else {
12456 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12457 |Context.BIND_IMPORTANT)) != 0) {
12458 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012459 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12460 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12461 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12462 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12463 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012464 adj = clientAdj;
12465 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012466 app.pendingUiClean = true;
12467 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12468 adj = ProcessList.VISIBLE_APP_ADJ;
12469 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012470 }
12471 if (!client.hidden) {
12472 app.hidden = false;
12473 }
12474 if (client.keeping) {
12475 app.keeping = true;
12476 }
12477 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012478 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012479 }
12480 if (adjType != null) {
12481 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012482 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12483 .REASON_SERVICE_IN_USE;
12484 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012485 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012486 app.adjTarget = s.name;
12487 }
12488 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12489 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12490 schedGroup = Process.THREAD_GROUP_DEFAULT;
12491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 }
12493 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012494 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12495 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012496 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012497 (a.visible || a.state == ActivityState.RESUMED
12498 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012499 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012500 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12501 schedGroup = Process.THREAD_GROUP_DEFAULT;
12502 }
12503 app.hidden = false;
12504 app.adjType = "service";
12505 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12506 .REASON_SERVICE_IN_USE;
12507 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012508 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012509 app.adjTarget = s.name;
12510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 }
12513 }
12514 }
12515 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012516
Dianne Hackborn287952c2010-09-22 22:34:31 -070012517 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012518 // would like to avoid killing it unless it would prevent the current
12519 // application from running. By default we put the process in
12520 // with the rest of the background processes; as we scan through
12521 // its services we may bump it up from there.
12522 if (adj > hiddenAdj) {
12523 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012524 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012525 app.adjType = "bg-services";
12526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 }
12528
Dianne Hackborn7d608422011-08-07 16:24:18 -070012529 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012530 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012531 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012532 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012533 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012534 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012535 for (int i = cpr.connections.size()-1;
12536 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12537 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12538 i--) {
12539 ContentProviderConnection conn = cpr.connections.get(i);
12540 ProcessRecord client = conn.client;
12541 if (client == app) {
12542 // Being our own client is not interesting.
12543 continue;
12544 }
12545 int myHiddenAdj = hiddenAdj;
12546 if (myHiddenAdj > client.hiddenAdj) {
12547 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12548 myHiddenAdj = client.hiddenAdj;
12549 } else {
12550 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012551 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012552 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012553 int myEmptyAdj = emptyAdj;
12554 if (myEmptyAdj > client.emptyAdj) {
12555 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12556 myEmptyAdj = client.emptyAdj;
12557 } else {
12558 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12559 }
12560 }
12561 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12562 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012563 if (adj > clientAdj) {
12564 if (app.hasShownUi && app != mHomeProcess
12565 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12566 app.adjType = "bg-ui-provider";
12567 } else {
12568 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12569 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12570 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012572 if (!client.hidden) {
12573 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012574 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012575 if (client.keeping) {
12576 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012577 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012578 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12579 .REASON_PROVIDER_IN_USE;
12580 app.adjSource = client;
12581 app.adjSourceOom = clientAdj;
12582 app.adjTarget = cpr.name;
12583 }
12584 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12585 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012586 }
12587 }
12588 // If the provider has external (non-framework) process
12589 // dependencies, ensure that its adjustment is at least
12590 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012591 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012592 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12593 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012594 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012595 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012596 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012597 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012598 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012599 }
12600 }
12601 }
12602 }
12603
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012604 if (adj == ProcessList.SERVICE_ADJ) {
12605 if (doingAll) {
12606 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12607 mNewNumServiceProcs++;
12608 }
12609 if (app.serviceb) {
12610 adj = ProcessList.SERVICE_B_ADJ;
12611 }
12612 } else {
12613 app.serviceb = false;
12614 }
12615
12616 app.nonStoppingAdj = adj;
12617
12618 if (hasStoppingActivities) {
12619 // Only upgrade adjustment.
12620 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12621 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12622 app.adjType = "stopping";
12623 }
12624 }
12625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012626 app.curRawAdj = adj;
12627
Joe Onorato8a9b2202010-02-26 18:56:32 -080012628 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12630 if (adj > app.maxAdj) {
12631 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012633 schedGroup = Process.THREAD_GROUP_DEFAULT;
12634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012636 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012637 app.keeping = true;
12638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012639
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012640 if (app.hasAboveClient) {
12641 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12642 // then we need to drop its adjustment to be lower than the service's
12643 // in order to honor the request. We want to drop it by one adjustment
12644 // level... but there is special meaning applied to various levels so
12645 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012646 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012647 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012648 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12649 adj = ProcessList.VISIBLE_APP_ADJ;
12650 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12651 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12652 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12653 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012654 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012655 adj++;
12656 }
12657 }
12658
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012659 int importance = app.memImportance;
12660 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12661 app.curAdj = adj;
12662 app.curSchedGroup = schedGroup;
12663 if (!interesting) {
12664 // For this reporting, if there is not something explicitly
12665 // interesting in this process then we will push it to the
12666 // background importance.
12667 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12668 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12669 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12670 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12671 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12672 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12673 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12674 } else if (adj >= ProcessList.SERVICE_ADJ) {
12675 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12676 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12677 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12678 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12679 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12680 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12681 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12682 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12683 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12684 } else {
12685 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12686 }
12687 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012688
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012689 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12690 if (foregroundActivities != app.foregroundActivities) {
12691 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12692 }
12693 if (changes != 0) {
12694 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12695 app.memImportance = importance;
12696 app.foregroundActivities = foregroundActivities;
12697 int i = mPendingProcessChanges.size()-1;
12698 ProcessChangeItem item = null;
12699 while (i >= 0) {
12700 item = mPendingProcessChanges.get(i);
12701 if (item.pid == app.pid) {
12702 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12703 break;
12704 }
12705 i--;
12706 }
12707 if (i < 0) {
12708 // No existing item in pending changes; need a new one.
12709 final int NA = mAvailProcessChanges.size();
12710 if (NA > 0) {
12711 item = mAvailProcessChanges.remove(NA-1);
12712 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12713 } else {
12714 item = new ProcessChangeItem();
12715 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12716 }
12717 item.changes = 0;
12718 item.pid = app.pid;
12719 item.uid = app.info.uid;
12720 if (mPendingProcessChanges.size() == 0) {
12721 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12722 "*** Enqueueing dispatch processes changed!");
12723 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12724 }
12725 mPendingProcessChanges.add(item);
12726 }
12727 item.changes |= changes;
12728 item.importance = importance;
12729 item.foregroundActivities = foregroundActivities;
12730 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12731 + Integer.toHexString(System.identityHashCode(item))
12732 + " " + app.toShortString() + ": changes=" + item.changes
12733 + " importance=" + item.importance
12734 + " foreground=" + item.foregroundActivities
12735 + " type=" + app.adjType + " source=" + app.adjSource
12736 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012737 }
12738
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012739 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 }
12741
12742 /**
12743 * Ask a given process to GC right now.
12744 */
12745 final void performAppGcLocked(ProcessRecord app) {
12746 try {
12747 app.lastRequestedGc = SystemClock.uptimeMillis();
12748 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012749 if (app.reportLowMemory) {
12750 app.reportLowMemory = false;
12751 app.thread.scheduleLowMemory();
12752 } else {
12753 app.thread.processInBackground();
12754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012755 }
12756 } catch (Exception e) {
12757 // whatever.
12758 }
12759 }
12760
12761 /**
12762 * Returns true if things are idle enough to perform GCs.
12763 */
Josh Bartel7f208742010-02-25 11:01:44 -060012764 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012765 boolean processingBroadcasts = false;
12766 for (BroadcastQueue q : mBroadcastQueues) {
12767 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12768 processingBroadcasts = true;
12769 }
12770 }
12771 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012772 && (mSleeping || (mMainStack.mResumedActivity != null &&
12773 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 }
12775
12776 /**
12777 * Perform GCs on all processes that are waiting for it, but only
12778 * if things are idle.
12779 */
12780 final void performAppGcsLocked() {
12781 final int N = mProcessesToGc.size();
12782 if (N <= 0) {
12783 return;
12784 }
Josh Bartel7f208742010-02-25 11:01:44 -060012785 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 while (mProcessesToGc.size() > 0) {
12787 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012788 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012789 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12790 <= SystemClock.uptimeMillis()) {
12791 // To avoid spamming the system, we will GC processes one
12792 // at a time, waiting a few seconds between each.
12793 performAppGcLocked(proc);
12794 scheduleAppGcsLocked();
12795 return;
12796 } else {
12797 // It hasn't been long enough since we last GCed this
12798 // process... put it in the list to wait for its time.
12799 addProcessToGcListLocked(proc);
12800 break;
12801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802 }
12803 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012804
12805 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806 }
12807 }
12808
12809 /**
12810 * If all looks good, perform GCs on all processes waiting for them.
12811 */
12812 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012813 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 performAppGcsLocked();
12815 return;
12816 }
12817 // Still not idle, wait some more.
12818 scheduleAppGcsLocked();
12819 }
12820
12821 /**
12822 * Schedule the execution of all pending app GCs.
12823 */
12824 final void scheduleAppGcsLocked() {
12825 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012826
12827 if (mProcessesToGc.size() > 0) {
12828 // Schedule a GC for the time to the next process.
12829 ProcessRecord proc = mProcessesToGc.get(0);
12830 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12831
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012832 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012833 long now = SystemClock.uptimeMillis();
12834 if (when < (now+GC_TIMEOUT)) {
12835 when = now + GC_TIMEOUT;
12836 }
12837 mHandler.sendMessageAtTime(msg, when);
12838 }
12839 }
12840
12841 /**
12842 * Add a process to the array of processes waiting to be GCed. Keeps the
12843 * list in sorted order by the last GC time. The process can't already be
12844 * on the list.
12845 */
12846 final void addProcessToGcListLocked(ProcessRecord proc) {
12847 boolean added = false;
12848 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12849 if (mProcessesToGc.get(i).lastRequestedGc <
12850 proc.lastRequestedGc) {
12851 added = true;
12852 mProcessesToGc.add(i+1, proc);
12853 break;
12854 }
12855 }
12856 if (!added) {
12857 mProcessesToGc.add(0, proc);
12858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 }
12860
12861 /**
12862 * Set up to ask a process to GC itself. This will either do it
12863 * immediately, or put it on the list of processes to gc the next
12864 * time things are idle.
12865 */
12866 final void scheduleAppGcLocked(ProcessRecord app) {
12867 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012868 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 return;
12870 }
12871 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012872 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873 scheduleAppGcsLocked();
12874 }
12875 }
12876
Dianne Hackborn287952c2010-09-22 22:34:31 -070012877 final void checkExcessivePowerUsageLocked(boolean doKills) {
12878 updateCpuStatsNow();
12879
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012880 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012881 boolean doWakeKills = doKills;
12882 boolean doCpuKills = doKills;
12883 if (mLastPowerCheckRealtime == 0) {
12884 doWakeKills = false;
12885 }
12886 if (mLastPowerCheckUptime == 0) {
12887 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012888 }
12889 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012890 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012891 }
12892 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012893 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12894 final long curUptime = SystemClock.uptimeMillis();
12895 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12896 mLastPowerCheckRealtime = curRealtime;
12897 mLastPowerCheckUptime = curUptime;
12898 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12899 doWakeKills = false;
12900 }
12901 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12902 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012903 }
12904 int i = mLruProcesses.size();
12905 while (i > 0) {
12906 i--;
12907 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012908 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012909 long wtime;
12910 synchronized (stats) {
12911 wtime = stats.getProcessWakeTime(app.info.uid,
12912 app.pid, curRealtime);
12913 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012914 long wtimeUsed = wtime - app.lastWakeTime;
12915 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12916 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012917 StringBuilder sb = new StringBuilder(128);
12918 sb.append("Wake for ");
12919 app.toShortString(sb);
12920 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012921 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012922 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012923 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012924 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012925 sb.append((wtimeUsed*100)/realtimeSince);
12926 sb.append("%)");
12927 Slog.i(TAG, sb.toString());
12928 sb.setLength(0);
12929 sb.append("CPU for ");
12930 app.toShortString(sb);
12931 sb.append(": over ");
12932 TimeUtils.formatDuration(uptimeSince, sb);
12933 sb.append(" used ");
12934 TimeUtils.formatDuration(cputimeUsed, sb);
12935 sb.append(" (");
12936 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012937 sb.append("%)");
12938 Slog.i(TAG, sb.toString());
12939 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012940 // If a process has held a wake lock for more
12941 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012942 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012943 if (doWakeKills && realtimeSince > 0
12944 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12945 synchronized (stats) {
12946 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12947 realtimeSince, wtimeUsed);
12948 }
12949 Slog.w(TAG, "Excessive wake lock in " + app.processName
12950 + " (pid " + app.pid + "): held " + wtimeUsed
12951 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012952 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12953 app.processName, app.setAdj, "excessive wake lock");
12954 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012955 } else if (doCpuKills && uptimeSince > 0
12956 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12957 synchronized (stats) {
12958 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12959 uptimeSince, cputimeUsed);
12960 }
12961 Slog.w(TAG, "Excessive CPU in " + app.processName
12962 + " (pid " + app.pid + "): used " + cputimeUsed
12963 + " during " + uptimeSince);
12964 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12965 app.processName, app.setAdj, "excessive cpu");
12966 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012967 } else {
12968 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012969 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012970 }
12971 }
12972 }
12973 }
12974
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012975 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
12976 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012978 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979
12980 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012981 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 }
12983
Dianne Hackborn287952c2010-09-22 22:34:31 -070012984 final boolean wasKeeping = app.keeping;
12985
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012986 boolean success = true;
12987
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012988 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989
Jeff Brown10e89712011-07-08 18:52:57 -070012990 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070012991 if (wasKeeping && !app.keeping) {
12992 // This app is no longer something we want to keep. Note
12993 // its current wake lock time to later know to kill it if
12994 // it is not behaving well.
12995 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12996 synchronized (stats) {
12997 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12998 app.pid, SystemClock.elapsedRealtime());
12999 }
13000 app.lastCpuTime = app.curCpuTime;
13001 }
13002
13003 app.setRawAdj = app.curRawAdj;
13004 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013005
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013006 if (app.curAdj != app.setAdj) {
13007 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013008 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013009 TAG, "Set " + app.pid + " " + app.processName +
13010 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013011 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013012 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013013 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013014 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013015 }
13016 }
13017 if (app.setSchedGroup != app.curSchedGroup) {
13018 app.setSchedGroup = app.curSchedGroup;
13019 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13020 "Setting process group of " + app.processName
13021 + " to " + app.curSchedGroup);
13022 if (app.waitingToKill != null &&
13023 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13024 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13025 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13026 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013027 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013028 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013029 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013030 } else {
13031 if (true) {
13032 long oldId = Binder.clearCallingIdentity();
13033 try {
13034 Process.setProcessGroup(app.pid, app.curSchedGroup);
13035 } catch (Exception e) {
13036 Slog.w(TAG, "Failed setting process group of " + app.pid
13037 + " to " + app.curSchedGroup);
13038 e.printStackTrace();
13039 } finally {
13040 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013041 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013042 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013043 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013044 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013045 app.thread.setSchedulingGroup(app.curSchedGroup);
13046 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013047 }
13048 }
13049 }
13050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013052 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 }
13054
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013055 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013056 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013058 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013060 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 }
13062 }
13063 return resumedActivity;
13064 }
13065
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013066 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013067 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13069 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013070 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13071 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072
13073 mAdjSeq++;
13074
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013075 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13076 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013077 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13078 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013079 if (nowHidden != wasHidden) {
13080 // Changed to/from hidden state, so apps after it in the LRU
13081 // list may also be changed.
13082 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013084 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 }
13086
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013087 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013088 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013089 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13090
13091 if (false) {
13092 RuntimeException e = new RuntimeException();
13093 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013094 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 }
13096
13097 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013098 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013100 // Let's determine how many processes we have running vs.
13101 // how many slots we have for background processes; we may want
13102 // to put multiple processes in a slot of there are enough of
13103 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013104 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13105 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13106 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13107 if (emptyFactor < 1) emptyFactor = 1;
13108 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13109 if (hiddenFactor < 1) hiddenFactor = 1;
13110 int stepHidden = 0;
13111 int stepEmpty = 0;
13112 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13113 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013114 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013115 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013116 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013117
13118 mNumNonHiddenProcs = 0;
13119 mNumHiddenProcs = 0;
13120
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013121 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013123 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013124 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013125 int nextHiddenAdj = curHiddenAdj+1;
13126 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13127 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 while (i > 0) {
13129 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013130 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013131 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013132 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013133 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013134 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13135 // This process was assigned as a hidden process... step the
13136 // hidden level.
13137 mNumHiddenProcs++;
13138 if (curHiddenAdj != nextHiddenAdj) {
13139 stepHidden++;
13140 if (stepHidden >= hiddenFactor) {
13141 stepHidden = 0;
13142 curHiddenAdj = nextHiddenAdj;
13143 nextHiddenAdj += 2;
13144 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13145 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13146 }
13147 }
13148 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013149 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013150 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013151 Slog.i(TAG, "No longer want " + app.processName
13152 + " (pid " + app.pid + "): hidden #" + numHidden);
13153 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13154 app.processName, app.setAdj, "too many background");
13155 app.killedBackground = true;
13156 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013157 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013158 } else {
13159 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13160 // This process was assigned as an empty process... step the
13161 // empty level.
13162 if (curEmptyAdj != nextEmptyAdj) {
13163 stepEmpty++;
13164 if (stepEmpty >= emptyFactor) {
13165 stepEmpty = 0;
13166 curEmptyAdj = nextEmptyAdj;
13167 nextEmptyAdj += 2;
13168 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13169 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13170 }
13171 }
13172 }
13173 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13174 mNumNonHiddenProcs++;
13175 }
13176 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13177 numEmpty++;
13178 if (numEmpty > emptyProcessLimit) {
13179 Slog.i(TAG, "No longer want " + app.processName
13180 + " (pid " + app.pid + "): empty #" + numEmpty);
13181 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13182 app.processName, app.setAdj, "too many background");
13183 app.killedBackground = true;
13184 Process.killProcessQuiet(app.pid);
13185 }
13186 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013187 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013188 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013189 // If this is an isolated process, and there are no
13190 // services running in it, then the process is no longer
13191 // needed. We agressively kill these because we can by
13192 // definition not re-use the same process again, and it is
13193 // good to avoid having whatever code was running in them
13194 // left sitting around after no longer needed.
13195 Slog.i(TAG, "Isolated process " + app.processName
13196 + " (pid " + app.pid + ") no longer needed");
13197 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13198 app.processName, app.setAdj, "isolated not needed");
13199 app.killedBackground = true;
13200 Process.killProcessQuiet(app.pid);
13201 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013202 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13203 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13204 && !app.killedBackground) {
13205 numTrimming++;
13206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 }
13208 }
13209
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013210 mNumServiceProcs = mNewNumServiceProcs;
13211
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013212 // Now determine the memory trimming level of background processes.
13213 // Unfortunately we need to start at the back of the list to do this
13214 // properly. We only do this if the number of background apps we
13215 // are managing to keep around is less than half the maximum we desire;
13216 // if we are keeping a good number around, we'll let them use whatever
13217 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013218 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13219 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13220 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013221 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013222 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013223 int minFactor = 2;
13224 if (mHomeProcess != null) minFactor++;
13225 if (mPreviousProcess != null) minFactor++;
13226 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013227 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013228 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013229 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013230 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013231 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013232 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13233 } else {
13234 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13235 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013236 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013237 for (i=0; i<N; i++) {
13238 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013239 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13240 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013241 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013242 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13243 try {
13244 app.thread.scheduleTrimMemory(curLevel);
13245 } catch (RemoteException e) {
13246 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013247 if (false) {
13248 // For now we won't do this; our memory trimming seems
13249 // to be good enough at this point that destroying
13250 // activities causes more harm than good.
13251 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13252 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013253 // Need to do this on its own message because the stack may not
13254 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013255 // For these apps we will also finish their activities
13256 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013257 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013258 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013259 }
13260 }
13261 app.trimMemoryLevel = curLevel;
13262 step++;
13263 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013264 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013265 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013266 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13267 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013268 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013269 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13270 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013271 break;
13272 }
13273 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013274 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013275 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013276 && app.thread != null) {
13277 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013278 app.thread.scheduleTrimMemory(
13279 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013280 } catch (RemoteException e) {
13281 }
13282 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013283 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013284 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013285 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013286 && app.pendingUiClean) {
13287 // If this application is now in the background and it
13288 // had done UI, then give it the special trim level to
13289 // have it free UI resources.
13290 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13291 if (app.trimMemoryLevel < level && app.thread != null) {
13292 try {
13293 app.thread.scheduleTrimMemory(level);
13294 } catch (RemoteException e) {
13295 }
13296 }
13297 app.pendingUiClean = false;
13298 }
13299 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013300 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013301 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013302 } catch (RemoteException e) {
13303 }
13304 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013305 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013306 }
13307 }
13308 } else {
13309 final int N = mLruProcesses.size();
13310 for (i=0; i<N; i++) {
13311 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013312 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013313 && app.pendingUiClean) {
13314 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13315 && app.thread != null) {
13316 try {
13317 app.thread.scheduleTrimMemory(
13318 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13319 } catch (RemoteException e) {
13320 }
13321 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013322 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013323 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013324 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013325 }
13326 }
13327
13328 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013329 // Need to do this on its own message because the stack may not
13330 // be in a consistent state at this point.
13331 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 }
13334
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013335 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013336 synchronized (this) {
13337 int i;
13338
13339 // First remove any unused application processes whose package
13340 // has been removed.
13341 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13342 final ProcessRecord app = mRemovedProcesses.get(i);
13343 if (app.activities.size() == 0
13344 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013345 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013346 TAG, "Exiting empty application process "
13347 + app.processName + " ("
13348 + (app.thread != null ? app.thread.asBinder() : null)
13349 + ")\n");
13350 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013351 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13352 app.processName, app.setAdj, "empty");
13353 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013354 } else {
13355 try {
13356 app.thread.scheduleExit();
13357 } catch (Exception e) {
13358 // Ignore exceptions.
13359 }
13360 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013361 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 mRemovedProcesses.remove(i);
13363
13364 if (app.persistent) {
13365 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013366 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 }
13368 }
13369 }
13370 }
13371
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013372 // Now update the oom adj for all processes.
13373 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
13375 }
13376
13377 /** This method sends the specified signal to each of the persistent apps */
13378 public void signalPersistentProcesses(int sig) throws RemoteException {
13379 if (sig != Process.SIGNAL_USR1) {
13380 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13381 }
13382
13383 synchronized (this) {
13384 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13385 != PackageManager.PERMISSION_GRANTED) {
13386 throw new SecurityException("Requires permission "
13387 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13388 }
13389
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013390 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13391 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013392 if (r.thread != null && r.persistent) {
13393 Process.sendSignal(r.pid, sig);
13394 }
13395 }
13396 }
13397 }
13398
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013399 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13400 if (proc == null || proc == mProfileProc) {
13401 proc = mProfileProc;
13402 path = mProfileFile;
13403 profileType = mProfileType;
13404 clearProfilerLocked();
13405 }
13406 if (proc == null) {
13407 return;
13408 }
13409 try {
13410 proc.thread.profilerControl(false, path, null, profileType);
13411 } catch (RemoteException e) {
13412 throw new IllegalStateException("Process disappeared");
13413 }
13414 }
13415
13416 private void clearProfilerLocked() {
13417 if (mProfileFd != null) {
13418 try {
13419 mProfileFd.close();
13420 } catch (IOException e) {
13421 }
13422 }
13423 mProfileApp = null;
13424 mProfileProc = null;
13425 mProfileFile = null;
13426 mProfileType = 0;
13427 mAutoStopProfiler = false;
13428 }
13429
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013430 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013431 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013432
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013433 try {
13434 synchronized (this) {
13435 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13436 // its own permission.
13437 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13438 != PackageManager.PERMISSION_GRANTED) {
13439 throw new SecurityException("Requires permission "
13440 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013441 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013442
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013443 if (start && fd == null) {
13444 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013445 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013446
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013447 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013448 if (process != null) {
13449 try {
13450 int pid = Integer.parseInt(process);
13451 synchronized (mPidsSelfLocked) {
13452 proc = mPidsSelfLocked.get(pid);
13453 }
13454 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013455 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013456
13457 if (proc == null) {
13458 HashMap<String, SparseArray<ProcessRecord>> all
13459 = mProcessNames.getMap();
13460 SparseArray<ProcessRecord> procs = all.get(process);
13461 if (procs != null && procs.size() > 0) {
13462 proc = procs.valueAt(0);
13463 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013464 }
13465 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013466
13467 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013468 throw new IllegalArgumentException("Unknown process: " + process);
13469 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013470
13471 if (start) {
13472 stopProfilerLocked(null, null, 0);
13473 setProfileApp(proc.info, proc.processName, path, fd, false);
13474 mProfileProc = proc;
13475 mProfileType = profileType;
13476 try {
13477 fd = fd.dup();
13478 } catch (IOException e) {
13479 fd = null;
13480 }
13481 proc.thread.profilerControl(start, path, fd, profileType);
13482 fd = null;
13483 mProfileFd = null;
13484 } else {
13485 stopProfilerLocked(proc, path, profileType);
13486 if (fd != null) {
13487 try {
13488 fd.close();
13489 } catch (IOException e) {
13490 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013491 }
13492 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013493
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013494 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013495 }
13496 } catch (RemoteException e) {
13497 throw new IllegalStateException("Process disappeared");
13498 } finally {
13499 if (fd != null) {
13500 try {
13501 fd.close();
13502 } catch (IOException e) {
13503 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013504 }
13505 }
13506 }
Andy McFadden824c5102010-07-09 16:26:57 -070013507
13508 public boolean dumpHeap(String process, boolean managed,
13509 String path, ParcelFileDescriptor fd) throws RemoteException {
13510
13511 try {
13512 synchronized (this) {
13513 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13514 // its own permission (same as profileControl).
13515 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13516 != PackageManager.PERMISSION_GRANTED) {
13517 throw new SecurityException("Requires permission "
13518 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13519 }
13520
13521 if (fd == null) {
13522 throw new IllegalArgumentException("null fd");
13523 }
13524
13525 ProcessRecord proc = null;
13526 try {
13527 int pid = Integer.parseInt(process);
13528 synchronized (mPidsSelfLocked) {
13529 proc = mPidsSelfLocked.get(pid);
13530 }
13531 } catch (NumberFormatException e) {
13532 }
13533
13534 if (proc == null) {
13535 HashMap<String, SparseArray<ProcessRecord>> all
13536 = mProcessNames.getMap();
13537 SparseArray<ProcessRecord> procs = all.get(process);
13538 if (procs != null && procs.size() > 0) {
13539 proc = procs.valueAt(0);
13540 }
13541 }
13542
13543 if (proc == null || proc.thread == null) {
13544 throw new IllegalArgumentException("Unknown process: " + process);
13545 }
13546
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013547 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13548 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013549 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13550 throw new SecurityException("Process not debuggable: " + proc);
13551 }
13552 }
13553
13554 proc.thread.dumpHeap(managed, path, fd);
13555 fd = null;
13556 return true;
13557 }
13558 } catch (RemoteException e) {
13559 throw new IllegalStateException("Process disappeared");
13560 } finally {
13561 if (fd != null) {
13562 try {
13563 fd.close();
13564 } catch (IOException e) {
13565 }
13566 }
13567 }
13568 }
13569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013570 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13571 public void monitor() {
13572 synchronized (this) { }
13573 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013574
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013575 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013576 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13577 ProcessRecord processRecord = mLruProcesses.get(i);
13578 try {
13579 if (processRecord.thread != null) {
13580 processRecord.thread.setCoreSettings(settings);
13581 }
13582 } catch (RemoteException re) {
13583 /* ignore */
13584 }
13585 }
13586 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013587
13588 // Multi-user methods
13589
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013590 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013591 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013592 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13593 != PackageManager.PERMISSION_GRANTED) {
13594 String msg = "Permission Denial: switchUser() from pid="
13595 + Binder.getCallingPid()
13596 + ", uid=" + Binder.getCallingUid()
13597 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13598 Slog.w(TAG, msg);
13599 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013600 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013601 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013602 if (mCurrentUserId == userId) {
13603 return true;
13604 }
13605
13606 // If the user we are switching to is not currently started, then
13607 // we need to start it now.
13608 if (mStartedUsers.get(userId) == null) {
13609 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013610 }
13611
13612 mCurrentUserId = userId;
13613 boolean haveActivities = mMainStack.switchUser(userId);
13614 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013615 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013616 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013617 }
Amith Yamasani13593602012-03-22 16:16:17 -070013618
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013619 long ident = Binder.clearCallingIdentity();
13620 try {
13621 // Inform of user switch
13622 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13623 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13624 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_USERS);
13625 } finally {
13626 Binder.restoreCallingIdentity(ident);
13627 }
Amith Yamasani13593602012-03-22 16:16:17 -070013628
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013629 return true;
13630 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013631
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013632 void finishUserSwitch(UserStartedState uss) {
13633 synchronized (this) {
13634 if (uss.mState == UserStartedState.STATE_BOOTING
13635 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13636 uss.mState = UserStartedState.STATE_RUNNING;
13637 broadcastIntentLocked(null, null,
13638 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
13639 null, null, 0, null, null,
13640 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
13641 false, false, MY_PID, Process.SYSTEM_UID, uss.mHandle.getIdentifier());
13642 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013643 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013644 }
13645
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013646 @Override
13647 public int stopUser(final int userId, final IStopUserCallback callback) {
13648 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13649 != PackageManager.PERMISSION_GRANTED) {
13650 String msg = "Permission Denial: switchUser() from pid="
13651 + Binder.getCallingPid()
13652 + ", uid=" + Binder.getCallingUid()
13653 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13654 Slog.w(TAG, msg);
13655 throw new SecurityException(msg);
13656 }
13657 if (userId <= 0) {
13658 throw new IllegalArgumentException("Can't stop primary user " + userId);
13659 }
Amith Yamasani13593602012-03-22 16:16:17 -070013660 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013661 if (mCurrentUserId == userId) {
13662 return ActivityManager.USER_OP_IS_CURRENT;
13663 }
13664
13665 final UserStartedState uss = mStartedUsers.get(userId);
13666 if (uss == null) {
13667 // User is not started, nothing to do... but we do need to
13668 // callback if requested.
13669 if (callback != null) {
13670 mHandler.post(new Runnable() {
13671 @Override
13672 public void run() {
13673 try {
13674 callback.userStopped(userId);
13675 } catch (RemoteException e) {
13676 }
13677 }
13678 });
13679 }
13680 return ActivityManager.USER_OP_SUCCESS;
13681 }
13682
13683 if (callback != null) {
13684 uss.mStopCallbacks.add(callback);
13685 }
13686
13687 if (uss.mState != UserStartedState.STATE_STOPPING) {
13688 uss.mState = UserStartedState.STATE_STOPPING;
13689
13690 long ident = Binder.clearCallingIdentity();
13691 try {
13692 // Inform of user switch
13693 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13694 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13695 @Override
13696 public void performReceive(Intent intent, int resultCode, String data,
13697 Bundle extras, boolean ordered, boolean sticky) {
13698 finishUserStop(uss);
13699 }
13700 };
13701 broadcastIntentLocked(null, null, intent,
13702 null, resultReceiver, 0, null, null, null,
13703 true, false, MY_PID, Process.SYSTEM_UID, userId);
13704 } finally {
13705 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013706 }
13707 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013708 }
Amith Yamasani13593602012-03-22 16:16:17 -070013709
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013710 return ActivityManager.USER_OP_SUCCESS;
13711 }
13712
13713 void finishUserStop(UserStartedState uss) {
13714 final int userId = uss.mHandle.getIdentifier();
13715 boolean stopped;
13716 ArrayList<IStopUserCallback> callbacks;
13717 synchronized (this) {
13718 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13719 if (uss.mState != UserStartedState.STATE_STOPPING
13720 || mStartedUsers.get(userId) != uss) {
13721 stopped = false;
13722 } else {
13723 stopped = true;
13724 // User can no longer run.
13725 mStartedUsers.remove(userId);
13726
13727 // Clean up all state and processes associated with the user.
13728 // Kill all the processes for the user.
13729 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013730 }
13731 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013732
13733 for (int i=0; i<callbacks.size(); i++) {
13734 try {
13735 if (stopped) callbacks.get(i).userStopped(userId);
13736 else callbacks.get(i).userStopAborted(userId);
13737 } catch (RemoteException e) {
13738 }
13739 }
13740 }
13741
13742 @Override
13743 public UserInfo getCurrentUser() {
13744 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13745 != PackageManager.PERMISSION_GRANTED) {
13746 String msg = "Permission Denial: getCurrentUser() from pid="
13747 + Binder.getCallingPid()
13748 + ", uid=" + Binder.getCallingUid()
13749 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13750 Slog.w(TAG, msg);
13751 throw new SecurityException(msg);
13752 }
13753 synchronized (this) {
13754 return getUserManager().getUserInfo(mCurrentUserId);
13755 }
Amith Yamasani13593602012-03-22 16:16:17 -070013756 }
13757
Amith Yamasani742a6712011-05-04 14:49:28 -070013758 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013759 UserInfo user = getUserManager().getUserInfo(userId);
13760 return user != null;
13761 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013762
Amith Yamasani258848d2012-08-10 17:06:33 -070013763 UserManager getUserManager() {
13764 if (mUserManager == null) {
13765 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13766 }
13767 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013768 }
13769
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013770 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013771 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013772
13773 throw new SecurityException("Caller uid=" + uid
13774 + " is not privileged to communicate with user=" + userId);
13775 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013776
13777 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013778 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013779 }
13780
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013781 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013782 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013783 ApplicationInfo newInfo = new ApplicationInfo(info);
13784 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013785 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13786 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013787 return newInfo;
13788 }
13789
13790 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013791 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013792 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013793 return aInfo;
13794 }
13795
13796 ActivityInfo info = new ActivityInfo(aInfo);
13797 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13798 return info;
13799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013800}