blob: 98d34821bd5f88139b7756ae4137b2aa4d88288e [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;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
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;
Adam Powelldd8fab22012-03-22 17:47:27 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070080import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.pm.ProviderInfo;
82import android.content.pm.ResolveInfo;
83import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070084import android.content.pm.UserInfo;
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;
109import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700110import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.SystemClock;
112import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700113import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700115import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800117import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700118import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700122import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700123import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.Gravity;
125import android.view.LayoutInflater;
126import android.view.View;
127import android.view.WindowManager;
128import android.view.WindowManagerPolicy;
129
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.BufferedInputStream;
131import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700132import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.DataInputStream;
134import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.File;
136import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200140import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800141import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700143import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.lang.ref.WeakReference;
145import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700146import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700155import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700179 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700180 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800181 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700184 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700185 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_POWER = localLOGV || false;
187 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean VALIDATE_TOKENS = false;
190 static final boolean SHOW_ACTIVITY_START_TIME = true;
191
192 // Control over CPU and battery monitoring.
193 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
194 static final boolean MONITOR_CPU_USAGE = true;
195 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
196 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
197 static final boolean MONITOR_THREAD_CPU_USAGE = false;
198
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700200 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800202 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700204 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Maximum number of recent tasks that we can remember.
207 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700208
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700209 // Amount of time after a call to stopAppSwitches() during which we will
210 // prevent further untrusted switches from happening.
211 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 // How long we wait for a launched process to attach to the activity manager
214 // before we decide it's never going to come up for real.
215 static final int PROC_START_TIMEOUT = 10*1000;
216
Jeff Brown3f9dd282011-07-08 20:02:19 -0700217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real, when the process was
219 // started with a wrapper for instrumentation (such as Valgrind) because it
220 // could take much longer than usual.
221 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // How long to wait after going idle before forcing apps to GC.
224 static final int GC_TIMEOUT = 5*1000;
225
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700226 // The minimum amount of time between successive GC requests for a process.
227 static final int GC_MIN_INTERVAL = 60*1000;
228
Dianne Hackborn287952c2010-09-22 22:34:31 -0700229 // The rate at which we check for apps using excessive power -- 15 mins.
230 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
231
232 // The minimum sample duration we will allow before deciding we have
233 // enough data on wake locks to start killing things.
234 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on CPU usage to start killing things.
238 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800241 static final int BROADCAST_FG_TIMEOUT = 10*1000;
242 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we wait until we timeout on key dispatching.
245 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we wait until we timeout on key dispatching during instrumentation.
248 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
249
Dan Egnor42471dd2010-01-07 17:25:22 -0800250 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 static final String[] EMPTY_STRING_ARRAY = new String[0];
253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700254 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700255
256 private final boolean mHeadless;
257
Joe Onorato54a4a412011-11-02 20:50:08 -0700258 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
259 // default actuion automatically. Important for devices without direct input
260 // devices.
261 private boolean mShowDialogs = true;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700264 * Description of a request to start a new activity, which has been held
265 * due to app switches being disabled.
266 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700267 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700268 ActivityRecord r;
269 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700270 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700271 }
272
273 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
274 = new ArrayList<PendingActivityLaunch>();
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800277 BroadcastQueue mFgBroadcastQueue;
278 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800279 // Convenient for easy iteration over the queues. Foreground is first
280 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800282
283 BroadcastQueue broadcastQueueForIntent(Intent intent) {
284 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
285 if (DEBUG_BACKGROUND_BROADCAST) {
286 Slog.i(TAG, "Broadcast intent " + intent + " on "
287 + (isFg ? "foreground" : "background")
288 + " queue");
289 }
290 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
291 }
292
293 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
294 for (BroadcastQueue queue : mBroadcastQueues) {
295 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
296 if (r != null) {
297 return r;
298 }
299 }
300 return null;
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * Activity we have told the window manager to have key focus.
305 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700306 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * List of intents that were used to start the most recent tasks.
309 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700310 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700313 * Process management.
314 */
315 final ProcessList mProcessList = new ProcessList();
316
317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * All of the applications we currently have running organized by name.
319 * The keys are strings of the application package name (as
320 * returned by the package manager), and the keys are ApplicationRecord
321 * objects.
322 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700323 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800326 * The currently running isolated processes.
327 */
328 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
329
330 /**
331 * Counter for assigning isolated process uids, to avoid frequently reusing the
332 * same ones.
333 */
334 int mNextIsolatedProcessUid = 0;
335
336 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700337 * The currently running heavy-weight process, if any.
338 */
339 ProcessRecord mHeavyWeightProcess = null;
340
341 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 * The last time that various processes have crashed.
343 */
344 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
345
346 /**
347 * Set of applications that we consider to be bad, and will reject
348 * incoming broadcasts from (which the user has no control over).
349 * Processes are added to this set when they have crashed twice within
350 * a minimum amount of time; they are removed from it when they are
351 * later restarted (hopefully due to some user action). The value is the
352 * time it was added to the list.
353 */
354 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
355
356 /**
357 * All of the processes we currently have running organized by pid.
358 * The keys are the pid running the application.
359 *
360 * <p>NOTE: This object is protected by its own lock, NOT the global
361 * activity manager lock!
362 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 /**
366 * All of the processes that have been forced to be foreground. The key
367 * is the pid of the caller who requested it (we hold a death
368 * link on it).
369 */
370 abstract class ForegroundToken implements IBinder.DeathRecipient {
371 int pid;
372 IBinder token;
373 }
374 final SparseArray<ForegroundToken> mForegroundProcesses
375 = new SparseArray<ForegroundToken>();
376
377 /**
378 * List of records for processes that someone had tried to start before the
379 * system was ready. We don't start them at that point, but ensure they
380 * are started by the time booting is complete.
381 */
382 final ArrayList<ProcessRecord> mProcessesOnHold
383 = new ArrayList<ProcessRecord>();
384
385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * List of persistent applications that are in the process
387 * of being started.
388 */
389 final ArrayList<ProcessRecord> mPersistentStartingProcesses
390 = new ArrayList<ProcessRecord>();
391
392 /**
393 * Processes that are being forcibly torn down.
394 */
395 final ArrayList<ProcessRecord> mRemovedProcesses
396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * List of running applications, sorted by recent usage.
400 * The first entry in the list is the least recently used.
401 * It contains ApplicationRecord objects. This list does NOT include
402 * any persistent application records (since we never want to exit them).
403 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800404 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 = new ArrayList<ProcessRecord>();
406
407 /**
408 * List of processes that should gc as soon as things are idle.
409 */
410 final ArrayList<ProcessRecord> mProcessesToGc
411 = new ArrayList<ProcessRecord>();
412
413 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800414 * This is the process holding what we currently consider to be
415 * the "home" activity.
416 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800418
419 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700420 * This is the process holding the activity the user last visited that
421 * is in a different process from the one they are currently in.
422 */
423 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800424
425 /**
426 * The time at which the previous process was last visible.
427 */
428 long mPreviousProcessVisibleTime;
429
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700430 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400431 * Packages that the user has asked to have run in screen size
432 * compatibility mode instead of filling the screen.
433 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700434 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400435
436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * Set of PendingResultRecord objects that are currently active.
438 */
439 final HashSet mPendingResultRecords = new HashSet();
440
441 /**
442 * Set of IntentSenderRecord objects that are currently active.
443 */
444 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
445 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
446
447 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800448 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700449 * already logged DropBox entries for. Guarded by itself. If
450 * something (rogue user app) forces this over
451 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
452 */
453 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
454 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
455
456 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700457 * Strict Mode background batched logging state.
458 *
459 * The string buffer is guarded by itself, and its lock is also
460 * used to determine if another batched write is already
461 * in-flight.
462 */
463 private final StringBuilder mStrictModeBuffer = new StringBuilder();
464
465 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 * Keeps track of all IIntentReceivers that have been registered for
467 * broadcasts. Hash keys are the receiver IBinder, hash value is
468 * a ReceiverList.
469 */
470 final HashMap mRegisteredReceivers = new HashMap();
471
472 /**
473 * Resolver for broadcast intents to registered receivers.
474 * Holds BroadcastFilter (subclass of IntentFilter).
475 */
476 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
477 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
478 @Override
479 protected boolean allowFilterResult(
480 BroadcastFilter filter, List<BroadcastFilter> dest) {
481 IBinder target = filter.receiverList.receiver.asBinder();
482 for (int i=dest.size()-1; i>=0; i--) {
483 if (dest.get(i).receiverList.receiver.asBinder() == target) {
484 return false;
485 }
486 }
487 return true;
488 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700489
490 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700491 protected BroadcastFilter[] newArray(int size) {
492 return new BroadcastFilter[size];
493 }
494
495 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700496 protected String packageForFilter(BroadcastFilter filter) {
497 return filter.packageName;
498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 };
500
501 /**
502 * State of all active sticky broadcasts. Keys are the action of the
503 * sticky Intent, values are an ArrayList of all broadcasted intents with
504 * that action (which should usually be one).
505 */
506 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
507 new HashMap<String, ArrayList<Intent>>();
508
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700509 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510
511 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700512 * Backup/restore process management
513 */
514 String mBackupAppName = null;
515 BackupRecord mBackupTarget = null;
516
517 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 * List of PendingThumbnailsRecord objects of clients who are still
519 * waiting to receive all of the thumbnails for a task.
520 */
521 final ArrayList mPendingThumbnails = new ArrayList();
522
523 /**
524 * List of HistoryRecord objects that have been finished and must
525 * still report back to a pending thumbnail receiver.
526 */
527 final ArrayList mCancelledThumbnails = new ArrayList();
528
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 final ProviderMap mProviderMap = new ProviderMap();
530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 /**
532 * List of content providers who have clients waiting for them. The
533 * application is currently being launched and the provider will be
534 * removed from this list once it is published.
535 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700536 final ArrayList<ContentProviderRecord> mLaunchingProviders
537 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538
539 /**
540 * Global set of specific Uri permissions that have been granted.
541 */
542 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
543 = new SparseArray<HashMap<Uri, UriPermission>>();
544
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800545 CoreSettingsObserver mCoreSettingsObserver;
546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 /**
548 * Thread-local storage used to carry caller permissions over through
549 * indirect content-provider access.
550 * @see #ActivityManagerService.openContentUri()
551 */
552 private class Identity {
553 public int pid;
554 public int uid;
555
556 Identity(int _pid, int _uid) {
557 pid = _pid;
558 uid = _uid;
559 }
560 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
563
564 /**
565 * All information we have collected about the runtime performance of
566 * any user id that can impact battery performance.
567 */
568 final BatteryStatsService mBatteryStatsService;
569
570 /**
571 * information about component usage
572 */
573 final UsageStatsService mUsageStatsService;
574
575 /**
576 * Current configuration information. HistoryRecord objects are given
577 * a reference to this object to indicate which configuration they are
578 * currently running in, so this object must be kept immutable.
579 */
580 Configuration mConfiguration = new Configuration();
581
582 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800583 * Current sequencing integer of the configuration, for skipping old
584 * configurations.
585 */
586 int mConfigurationSeq = 0;
587
588 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700589 * Hardware-reported OpenGLES version.
590 */
591 final int GL_ES_VERSION;
592
593 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 * List of initialization arguments to pass to all processes when binding applications to them.
595 * For example, references to the commonly used services.
596 */
597 HashMap<String, IBinder> mAppBindArgs;
598
599 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700600 * Temporary to avoid allocations. Protected by main lock.
601 */
602 final StringBuilder mStringBuilder = new StringBuilder(256);
603
604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * Used to control how we initialize the service.
606 */
607 boolean mStartRunning = false;
608 ComponentName mTopComponent;
609 String mTopAction;
610 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700611 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 boolean mSystemReady = false;
613 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700614 boolean mWaitingUpdate = false;
615 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700616 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700617 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618
619 Context mContext;
620
621 int mFactoryTest;
622
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700623 boolean mCheckedForSetup;
624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700626 * The time at which we will allow normal application switches again,
627 * after a call to {@link #stopAppSwitches()}.
628 */
629 long mAppSwitchesAllowedTime;
630
631 /**
632 * This is set to true after the first switch after mAppSwitchesAllowedTime
633 * is set; any switches after that will clear the time.
634 */
635 boolean mDidAppSwitch;
636
637 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700638 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700639 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700640 long mLastPowerCheckRealtime;
641
642 /**
643 * Last time (in uptime) at which we checked for power usage.
644 */
645 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700646
647 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 * Set while we are wanting to sleep, to prevent any
649 * activities from being started/resumed.
650 */
651 boolean mSleeping = false;
652
653 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700654 * State of external calls telling us if the device is asleep.
655 */
656 boolean mWentToSleep = false;
657
658 /**
659 * State of external call telling us if the lock screen is shown.
660 */
661 boolean mLockScreenShown = false;
662
663 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700664 * Set if we are shutting down the system, similar to sleeping.
665 */
666 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667
668 /**
669 * Task identifier that activities are currently being started
670 * in. Incremented each time a new task is created.
671 * todo: Replace this with a TokenSpace class that generates non-repeating
672 * integers that won't wrap.
673 */
674 int mCurTask = 1;
675
676 /**
677 * Current sequence id for oom_adj computation traversal.
678 */
679 int mAdjSeq = 0;
680
681 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700682 * Current sequence id for process LRU updating.
683 */
684 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
686 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700687 * Keep track of the number of service processes we last found, to
688 * determine on the next iteration which should be B services.
689 */
690 int mNumServiceProcs = 0;
691 int mNewNumServiceProcs = 0;
692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * System monitoring: number of processes that died since the last
695 * N procs were started.
696 */
697 int[] mProcDeaths = new int[20];
698
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700699 /**
700 * This is set if we had to do a delayed dexopt of an app before launching
701 * it, to increasing the ANR timeouts in that case.
702 */
703 boolean mDidDexOpt;
704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 String mDebugApp = null;
706 boolean mWaitForDebugger = false;
707 boolean mDebugTransient = false;
708 String mOrigDebugApp = null;
709 boolean mOrigWaitForDebugger = false;
710 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700711 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700712 String mProfileApp = null;
713 ProcessRecord mProfileProc = null;
714 String mProfileFile;
715 ParcelFileDescriptor mProfileFd;
716 int mProfileType = 0;
717 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800718 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700720 static class ProcessChangeItem {
721 static final int CHANGE_ACTIVITIES = 1<<0;
722 static final int CHANGE_IMPORTANCE= 1<<1;
723 int changes;
724 int uid;
725 int pid;
726 int importance;
727 boolean foregroundActivities;
728 }
729
Jeff Sharkeya4620792011-05-20 15:29:23 -0700730 final RemoteCallbackList<IProcessObserver> mProcessObservers
731 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700732 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
733
734 final ArrayList<ProcessChangeItem> mPendingProcessChanges
735 = new ArrayList<ProcessChangeItem>();
736 final ArrayList<ProcessChangeItem> mAvailProcessChanges
737 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 /**
740 * Callback of last caller to {@link #requestPss}.
741 */
742 Runnable mRequestPssCallback;
743
744 /**
745 * Remaining processes for which we are waiting results from the last
746 * call to {@link #requestPss}.
747 */
748 final ArrayList<ProcessRecord> mRequestPssList
749 = new ArrayList<ProcessRecord>();
750
751 /**
752 * Runtime statistics collection thread. This object's lock is used to
753 * protect all related state.
754 */
755 final Thread mProcessStatsThread;
756
757 /**
758 * Used to collect process stats when showing not responding dialog.
759 * Protected by mProcessStatsThread.
760 */
761 final ProcessStats mProcessStats = new ProcessStats(
762 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700763 final AtomicLong mLastCpuTime = new AtomicLong(0);
764 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 long mLastWriteTime = 0;
767
768 /**
769 * Set to true after the system has finished booting.
770 */
771 boolean mBooted = false;
772
Dianne Hackborn7d608422011-08-07 16:24:18 -0700773 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700774 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775
776 WindowManagerService mWindowManager;
777
778 static ActivityManagerService mSelf;
779 static ActivityThread mSystemThread;
780
781 private final class AppDeathRecipient implements IBinder.DeathRecipient {
782 final ProcessRecord mApp;
783 final int mPid;
784 final IApplicationThread mAppThread;
785
786 AppDeathRecipient(ProcessRecord app, int pid,
787 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800788 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 TAG, "New death recipient " + this
790 + " for thread " + thread.asBinder());
791 mApp = app;
792 mPid = pid;
793 mAppThread = thread;
794 }
795
796 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800797 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 TAG, "Death received in " + this
799 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 synchronized(ActivityManagerService.this) {
801 appDiedLocked(mApp, mPid, mAppThread);
802 }
803 }
804 }
805
806 static final int SHOW_ERROR_MSG = 1;
807 static final int SHOW_NOT_RESPONDING_MSG = 2;
808 static final int SHOW_FACTORY_ERROR_MSG = 3;
809 static final int UPDATE_CONFIGURATION_MSG = 4;
810 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
811 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 static final int SERVICE_TIMEOUT_MSG = 12;
813 static final int UPDATE_TIME_ZONE = 13;
814 static final int SHOW_UID_ERROR_MSG = 14;
815 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700817 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700818 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800819 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700820 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
821 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700822 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700823 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700824 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700825 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700826 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700827 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700828 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700829 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800831 static final int FIRST_ACTIVITY_STACK_MSG = 100;
832 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
833 static final int FIRST_COMPAT_MODE_MSG = 300;
834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700836 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700837 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838
839 final Handler mHandler = new Handler() {
840 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 //}
843
844 public void handleMessage(Message msg) {
845 switch (msg.what) {
846 case SHOW_ERROR_MSG: {
847 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 synchronized (ActivityManagerService.this) {
849 ProcessRecord proc = (ProcessRecord)data.get("app");
850 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800851 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 return;
853 }
854 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700855 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800856 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 d.show();
858 proc.crashDialog = d;
859 } else {
860 // The device is asleep, so just pretend that the user
861 // saw a crash dialog and hit "force quit".
862 res.set(0);
863 }
864 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700865
866 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 } break;
868 case SHOW_NOT_RESPONDING_MSG: {
869 synchronized (ActivityManagerService.this) {
870 HashMap data = (HashMap) msg.obj;
871 ProcessRecord proc = (ProcessRecord)data.get("app");
872 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800873 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 return;
875 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800876
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700877 Intent intent = new Intent("android.intent.action.ANR");
878 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800879 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
880 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700881 }
882 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800883 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700884 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800885
Justin Kohbc52ca22012-03-29 15:11:44 -0700886 if (mShowDialogs) {
887 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700888 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700889 d.show();
890 proc.anrDialog = d;
891 } else {
892 // Just kill the app if there is no dialog to be shown.
893 killAppAtUsersRequest(proc, null);
894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700896
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700897 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700899 case SHOW_STRICT_MODE_VIOLATION_MSG: {
900 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
901 synchronized (ActivityManagerService.this) {
902 ProcessRecord proc = (ProcessRecord) data.get("app");
903 if (proc == null) {
904 Slog.e(TAG, "App not found when showing strict mode dialog.");
905 break;
906 }
907 if (proc.crashDialog != null) {
908 Slog.e(TAG, "App already has strict mode dialog: " + proc);
909 return;
910 }
911 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700912 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700913 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
914 d.show();
915 proc.crashDialog = d;
916 } else {
917 // The device is asleep, so just pretend that the user
918 // saw a crash dialog and hit "force quit".
919 res.set(0);
920 }
921 }
922 ensureBootCompleted();
923 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 case SHOW_FACTORY_ERROR_MSG: {
925 Dialog d = new FactoryErrorDialog(
926 mContext, msg.getData().getCharSequence("msg"));
927 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700928 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 } break;
930 case UPDATE_CONFIGURATION_MSG: {
931 final ContentResolver resolver = mContext.getContentResolver();
932 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
933 } break;
934 case GC_BACKGROUND_PROCESSES_MSG: {
935 synchronized (ActivityManagerService.this) {
936 performAppGcsIfAppropriateLocked();
937 }
938 } break;
939 case WAIT_FOR_DEBUGGER_MSG: {
940 synchronized (ActivityManagerService.this) {
941 ProcessRecord app = (ProcessRecord)msg.obj;
942 if (msg.arg1 != 0) {
943 if (!app.waitedForDebugger) {
944 Dialog d = new AppWaitingForDebuggerDialog(
945 ActivityManagerService.this,
946 mContext, app);
947 app.waitDialog = d;
948 app.waitedForDebugger = true;
949 d.show();
950 }
951 } else {
952 if (app.waitDialog != null) {
953 app.waitDialog.dismiss();
954 app.waitDialog = null;
955 }
956 }
957 }
958 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700960 if (mDidDexOpt) {
961 mDidDexOpt = false;
962 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
963 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700964 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700965 return;
966 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700967 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 } break;
969 case UPDATE_TIME_ZONE: {
970 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800971 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
972 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 if (r.thread != null) {
974 try {
975 r.thread.updateTimeZone();
976 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800977 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979 }
980 }
981 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700982 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700983 case CLEAR_DNS_CACHE: {
984 synchronized (ActivityManagerService.this) {
985 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
986 ProcessRecord r = mLruProcesses.get(i);
987 if (r.thread != null) {
988 try {
989 r.thread.clearDnsCache();
990 } catch (RemoteException ex) {
991 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
992 }
993 }
994 }
995 }
996 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700997 case UPDATE_HTTP_PROXY: {
998 ProxyProperties proxy = (ProxyProperties)msg.obj;
999 String host = "";
1000 String port = "";
1001 String exclList = "";
1002 if (proxy != null) {
1003 host = proxy.getHost();
1004 port = Integer.toString(proxy.getPort());
1005 exclList = proxy.getExclusionList();
1006 }
1007 synchronized (ActivityManagerService.this) {
1008 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1009 ProcessRecord r = mLruProcesses.get(i);
1010 if (r.thread != null) {
1011 try {
1012 r.thread.setHttpProxy(host, port, exclList);
1013 } catch (RemoteException ex) {
1014 Slog.w(TAG, "Failed to update http proxy for: " +
1015 r.info.processName);
1016 }
1017 }
1018 }
1019 }
1020 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001022 String title = "System UIDs Inconsistent";
1023 String text = "UIDs on the system are inconsistent, you need to wipe your"
1024 + " data partition or your device will be unstable.";
1025 Log.e(TAG, title + ": " + text);
1026 if (mShowDialogs) {
1027 // XXX This is a temporary dialog, no need to localize.
1028 AlertDialog d = new BaseErrorDialog(mContext);
1029 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1030 d.setCancelable(false);
1031 d.setTitle(title);
1032 d.setMessage(text);
1033 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1034 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1035 mUidAlert = d;
1036 d.show();
1037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 } break;
1039 case IM_FEELING_LUCKY_MSG: {
1040 if (mUidAlert != null) {
1041 mUidAlert.dismiss();
1042 mUidAlert = null;
1043 }
1044 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001046 if (mDidDexOpt) {
1047 mDidDexOpt = false;
1048 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1049 nmsg.obj = msg.obj;
1050 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1051 return;
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 ProcessRecord app = (ProcessRecord)msg.obj;
1054 synchronized (ActivityManagerService.this) {
1055 processStartTimedOutLocked(app);
1056 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001057 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001058 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1059 synchronized (ActivityManagerService.this) {
1060 doPendingActivityLaunchesLocked(true);
1061 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001062 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001063 case KILL_APPLICATION_MSG: {
1064 synchronized (ActivityManagerService.this) {
1065 int uid = msg.arg1;
1066 boolean restart = (msg.arg2 == 1);
1067 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001068 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1069 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001070 }
1071 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001072 case FINALIZE_PENDING_INTENT_MSG: {
1073 ((PendingIntentRecord)msg.obj).completeFinalize();
1074 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001075 case POST_HEAVY_NOTIFICATION_MSG: {
1076 INotificationManager inm = NotificationManager.getService();
1077 if (inm == null) {
1078 return;
1079 }
1080
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001081 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001082 ProcessRecord process = root.app;
1083 if (process == null) {
1084 return;
1085 }
1086
1087 try {
1088 Context context = mContext.createPackageContext(process.info.packageName, 0);
1089 String text = mContext.getString(R.string.heavy_weight_notification,
1090 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1091 Notification notification = new Notification();
1092 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1093 notification.when = 0;
1094 notification.flags = Notification.FLAG_ONGOING_EVENT;
1095 notification.tickerText = text;
1096 notification.defaults = 0; // please be quiet
1097 notification.sound = null;
1098 notification.vibrate = null;
1099 notification.setLatestEventInfo(context, text,
1100 mContext.getText(R.string.heavy_weight_notification_detail),
1101 PendingIntent.getActivity(mContext, 0, root.intent,
1102 PendingIntent.FLAG_CANCEL_CURRENT));
1103
1104 try {
1105 int[] outId = new int[1];
1106 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1107 notification, outId);
1108 } catch (RuntimeException e) {
1109 Slog.w(ActivityManagerService.TAG,
1110 "Error showing notification for heavy-weight app", e);
1111 } catch (RemoteException e) {
1112 }
1113 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001114 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001115 }
1116 } break;
1117 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1118 INotificationManager inm = NotificationManager.getService();
1119 if (inm == null) {
1120 return;
1121 }
1122 try {
1123 inm.cancelNotification("android",
1124 R.string.heavy_weight_notification);
1125 } catch (RuntimeException e) {
1126 Slog.w(ActivityManagerService.TAG,
1127 "Error canceling notification for service", e);
1128 } catch (RemoteException e) {
1129 }
1130 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001131 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1132 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001133 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001134 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001135 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1136 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001137 }
1138 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001139 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1140 synchronized (ActivityManagerService.this) {
1141 ActivityRecord ar = (ActivityRecord)msg.obj;
1142 if (mCompatModeDialog != null) {
1143 if (mCompatModeDialog.mAppInfo.packageName.equals(
1144 ar.info.applicationInfo.packageName)) {
1145 return;
1146 }
1147 mCompatModeDialog.dismiss();
1148 mCompatModeDialog = null;
1149 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001150 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001151 if (mCompatModePackages.getPackageAskCompatModeLocked(
1152 ar.packageName)) {
1153 int mode = mCompatModePackages.computeCompatModeLocked(
1154 ar.info.applicationInfo);
1155 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1156 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1157 mCompatModeDialog = new CompatModeDialog(
1158 ActivityManagerService.this, mContext,
1159 ar.info.applicationInfo);
1160 mCompatModeDialog.show();
1161 }
1162 }
1163 }
1164 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001165 break;
1166 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001167 case DISPATCH_PROCESSES_CHANGED: {
1168 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001169 break;
1170 }
1171 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001172 final int pid = msg.arg1;
1173 final int uid = msg.arg2;
1174 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001175 break;
1176 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001177 case REPORT_MEM_USAGE: {
1178 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1179 if (!isDebuggable) {
1180 return;
1181 }
1182 synchronized (ActivityManagerService.this) {
1183 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001184 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1185 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001186 // avoid spamming.
1187 return;
1188 }
1189 mLastMemUsageReportTime = now;
1190 }
1191 Thread thread = new Thread() {
1192 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001193 StringBuilder dropBuilder = new StringBuilder(1024);
1194 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001195 StringWriter oomSw = new StringWriter();
1196 PrintWriter oomPw = new PrintWriter(oomSw);
1197 StringWriter catSw = new StringWriter();
1198 PrintWriter catPw = new PrintWriter(catSw);
1199 String[] emptyArgs = new String[] { };
1200 StringBuilder tag = new StringBuilder(128);
1201 StringBuilder stack = new StringBuilder(128);
1202 tag.append("Low on memory -- ");
1203 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1204 tag, stack);
1205 dropBuilder.append(stack);
1206 dropBuilder.append('\n');
1207 dropBuilder.append('\n');
1208 String oomString = oomSw.toString();
1209 dropBuilder.append(oomString);
1210 dropBuilder.append('\n');
1211 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001212 try {
1213 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1214 "procrank", });
1215 final InputStreamReader converter = new InputStreamReader(
1216 proc.getInputStream());
1217 BufferedReader in = new BufferedReader(converter);
1218 String line;
1219 while (true) {
1220 line = in.readLine();
1221 if (line == null) {
1222 break;
1223 }
1224 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001225 logBuilder.append(line);
1226 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001227 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001228 dropBuilder.append(line);
1229 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001230 }
1231 converter.close();
1232 } catch (IOException e) {
1233 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001234 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001235 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001236 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001237 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001238 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1239 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001240 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001241 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001242 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001243 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001244 addErrorToDropBox("lowmem", null, "system_server", null,
1245 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001246 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001247 synchronized (ActivityManagerService.this) {
1248 long now = SystemClock.uptimeMillis();
1249 if (mLastMemUsageReportTime < now) {
1250 mLastMemUsageReportTime = now;
1251 }
1252 }
1253 }
1254 };
1255 thread.start();
1256 break;
1257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
1259 }
1260 };
1261
1262 public static void setSystemProcess() {
1263 try {
1264 ActivityManagerService m = mSelf;
1265
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001266 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001268 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001269 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 if (MONITOR_CPU_USAGE) {
1271 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 ServiceManager.addService("permission", new PermissionController(m));
1274
1275 ApplicationInfo info =
1276 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001277 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001278 mSystemThread.installSystemApplicationInfo(info);
1279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 synchronized (mSelf) {
1281 ProcessRecord app = mSelf.newProcessRecordLocked(
1282 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001283 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001285 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001286 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001287 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 synchronized (mSelf.mPidsSelfLocked) {
1289 mSelf.mPidsSelfLocked.put(app.pid, app);
1290 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001291 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 }
1293 } catch (PackageManager.NameNotFoundException e) {
1294 throw new RuntimeException(
1295 "Unable to find android system package", e);
1296 }
1297 }
1298
1299 public void setWindowManager(WindowManagerService wm) {
1300 mWindowManager = wm;
1301 }
1302
1303 public static final Context main(int factoryTest) {
1304 AThread thr = new AThread();
1305 thr.start();
1306
1307 synchronized (thr) {
1308 while (thr.mService == null) {
1309 try {
1310 thr.wait();
1311 } catch (InterruptedException e) {
1312 }
1313 }
1314 }
1315
1316 ActivityManagerService m = thr.mService;
1317 mSelf = m;
1318 ActivityThread at = ActivityThread.systemMain();
1319 mSystemThread = at;
1320 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001321 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 m.mContext = context;
1323 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001324 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325
1326 m.mBatteryStatsService.publish(context);
1327 m.mUsageStatsService.publish(context);
1328
1329 synchronized (thr) {
1330 thr.mReady = true;
1331 thr.notifyAll();
1332 }
1333
1334 m.startRunning(null, null, null, null);
1335
1336 return context;
1337 }
1338
1339 public static ActivityManagerService self() {
1340 return mSelf;
1341 }
1342
1343 static class AThread extends Thread {
1344 ActivityManagerService mService;
1345 boolean mReady = false;
1346
1347 public AThread() {
1348 super("ActivityManager");
1349 }
1350
1351 public void run() {
1352 Looper.prepare();
1353
1354 android.os.Process.setThreadPriority(
1355 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001356 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
1358 ActivityManagerService m = new ActivityManagerService();
1359
1360 synchronized (this) {
1361 mService = m;
1362 notifyAll();
1363 }
1364
1365 synchronized (this) {
1366 while (!mReady) {
1367 try {
1368 wait();
1369 } catch (InterruptedException e) {
1370 }
1371 }
1372 }
1373
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001374 // For debug builds, log event loop stalls to dropbox for analysis.
1375 if (StrictMode.conditionallyEnableDebugLogging()) {
1376 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 Looper.loop();
1380 }
1381 }
1382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 static class MemBinder extends Binder {
1384 ActivityManagerService mActivityManagerService;
1385 MemBinder(ActivityManagerService activityManagerService) {
1386 mActivityManagerService = activityManagerService;
1387 }
1388
1389 @Override
1390 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001391 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1392 != PackageManager.PERMISSION_GRANTED) {
1393 pw.println("Permission Denial: can't dump meminfo from from pid="
1394 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1395 + " without permission " + android.Manifest.permission.DUMP);
1396 return;
1397 }
1398
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001399 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001400 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402 }
1403
Chet Haase9c1e23b2011-03-24 10:51:31 -07001404 static class GraphicsBinder extends Binder {
1405 ActivityManagerService mActivityManagerService;
1406 GraphicsBinder(ActivityManagerService activityManagerService) {
1407 mActivityManagerService = activityManagerService;
1408 }
1409
1410 @Override
1411 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001412 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1413 != PackageManager.PERMISSION_GRANTED) {
1414 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1415 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1416 + " without permission " + android.Manifest.permission.DUMP);
1417 return;
1418 }
1419
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001420 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001421 }
1422 }
1423
Jeff Brown6754ba22011-12-14 20:20:01 -08001424 static class DbBinder extends Binder {
1425 ActivityManagerService mActivityManagerService;
1426 DbBinder(ActivityManagerService activityManagerService) {
1427 mActivityManagerService = activityManagerService;
1428 }
1429
1430 @Override
1431 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1432 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1433 != PackageManager.PERMISSION_GRANTED) {
1434 pw.println("Permission Denial: can't dump dbinfo from from pid="
1435 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1436 + " without permission " + android.Manifest.permission.DUMP);
1437 return;
1438 }
1439
1440 mActivityManagerService.dumpDbInfo(fd, pw, args);
1441 }
1442 }
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 static class CpuBinder extends Binder {
1445 ActivityManagerService mActivityManagerService;
1446 CpuBinder(ActivityManagerService activityManagerService) {
1447 mActivityManagerService = activityManagerService;
1448 }
1449
1450 @Override
1451 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001452 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1453 != PackageManager.PERMISSION_GRANTED) {
1454 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1455 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1456 + " without permission " + android.Manifest.permission.DUMP);
1457 return;
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001461 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1462 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1463 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465 }
1466 }
1467
1468 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001469 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001470
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001471 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1472 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1473 mBroadcastQueues[0] = mFgBroadcastQueue;
1474 mBroadcastQueues[1] = mBgBroadcastQueue;
1475
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001476 mServices = new ActiveServices(this);
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 File dataDir = Environment.getDataDirectory();
1479 File systemDir = new File(dataDir, "system");
1480 systemDir.mkdirs();
1481 mBatteryStatsService = new BatteryStatsService(new File(
1482 systemDir, "batterystats.bin").toString());
1483 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001484 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001485 mOnBattery = DEBUG_POWER ? true
1486 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001487 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001489 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001490 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001491 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492
Jack Palevichb90d28c2009-07-22 15:35:24 -07001493 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1494 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1495
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001496 mConfiguration.setToDefaults();
1497 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001498 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 mProcessStats.init();
1500
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001501 mCompatModePackages = new CompatModePackages(this, systemDir);
1502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 // Add ourself to the Watchdog monitors.
1504 Watchdog.getInstance().addMonitor(this);
1505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 mProcessStatsThread = new Thread("ProcessStats") {
1507 public void run() {
1508 while (true) {
1509 try {
1510 try {
1511 synchronized(this) {
1512 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001513 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 // + ", write delay=" + nextWriteDelay);
1517 if (nextWriteDelay < nextCpuDelay) {
1518 nextCpuDelay = nextWriteDelay;
1519 }
1520 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001521 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 this.wait(nextCpuDelay);
1523 }
1524 }
1525 } catch (InterruptedException e) {
1526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 updateCpuStatsNow();
1528 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 }
1532 }
1533 };
1534 mProcessStatsThread.start();
1535 }
1536
1537 @Override
1538 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1539 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001540 if (code == SYSPROPS_TRANSACTION) {
1541 // We need to tell all apps about the system property change.
1542 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1543 synchronized(this) {
1544 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1545 final int NA = apps.size();
1546 for (int ia=0; ia<NA; ia++) {
1547 ProcessRecord app = apps.valueAt(ia);
1548 if (app.thread != null) {
1549 procs.add(app.thread.asBinder());
1550 }
1551 }
1552 }
1553 }
1554
1555 int N = procs.size();
1556 for (int i=0; i<N; i++) {
1557 Parcel data2 = Parcel.obtain();
1558 try {
1559 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1560 } catch (RemoteException e) {
1561 }
1562 data2.recycle();
1563 }
1564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 try {
1566 return super.onTransact(code, data, reply, flags);
1567 } catch (RuntimeException e) {
1568 // The activity manager only throws security exceptions, so let's
1569 // log all others.
1570 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573 throw e;
1574 }
1575 }
1576
1577 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001578 final long now = SystemClock.uptimeMillis();
1579 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1580 return;
1581 }
1582 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1583 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mProcessStatsThread.notify();
1585 }
1586 }
1587 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 void updateCpuStatsNow() {
1590 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001591 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 final long now = SystemClock.uptimeMillis();
1593 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1597 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 haveNewCpuStats = true;
1599 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001600 //Slog.i(TAG, mProcessStats.printCurrentState());
1601 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 // + mProcessStats.getTotalCpuPercent() + "%");
1603
Joe Onorato8a9b2202010-02-26 18:56:32 -08001604 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 if ("true".equals(SystemProperties.get("events.cpu"))) {
1606 int user = mProcessStats.getLastUserTime();
1607 int system = mProcessStats.getLastSystemTime();
1608 int iowait = mProcessStats.getLastIoWaitTime();
1609 int irq = mProcessStats.getLastIrqTime();
1610 int softIrq = mProcessStats.getLastSoftIrqTime();
1611 int idle = mProcessStats.getLastIdleTime();
1612
1613 int total = user + system + iowait + irq + softIrq + idle;
1614 if (total == 0) total = 1;
1615
Doug Zongker2bec3d42009-12-04 12:52:44 -08001616 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 ((user+system+iowait+irq+softIrq) * 100) / total,
1618 (user * 100) / total,
1619 (system * 100) / total,
1620 (iowait * 100) / total,
1621 (irq * 100) / total,
1622 (softIrq * 100) / total);
1623 }
1624 }
1625
Amith Yamasanie43530a2009-08-21 13:11:37 -07001626 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001627 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001628 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 synchronized(mPidsSelfLocked) {
1630 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001631 if (mOnBattery) {
1632 int perc = bstats.startAddingCpuLocked();
1633 int totalUTime = 0;
1634 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001635 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001637 ProcessStats.Stats st = mProcessStats.getStats(i);
1638 if (!st.working) {
1639 continue;
1640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001642 int otherUTime = (st.rel_utime*perc)/100;
1643 int otherSTime = (st.rel_stime*perc)/100;
1644 totalUTime += otherUTime;
1645 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if (pr != null) {
1647 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001648 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1649 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001650 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001651 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001652 } else {
1653 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001654 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001655 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001656 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1657 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001658 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001662 bstats.finishAddingCpuLocked(perc, totalUTime,
1663 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665 }
1666 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1669 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001670 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672 }
1673 }
1674 }
1675
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001676 @Override
1677 public void batteryNeedsCpuUpdate() {
1678 updateCpuStatsNow();
1679 }
1680
1681 @Override
1682 public void batteryPowerChanged(boolean onBattery) {
1683 // When plugging in, update the CPU stats first before changing
1684 // the plug state.
1685 updateCpuStatsNow();
1686 synchronized (this) {
1687 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001688 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001689 }
1690 }
1691 }
1692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 /**
1694 * Initialize the application bind args. These are passed to each
1695 * process when the bindApplication() IPC is sent to the process. They're
1696 * lazily setup to make sure the services are running when they're asked for.
1697 */
1698 private HashMap<String, IBinder> getCommonServicesLocked() {
1699 if (mAppBindArgs == null) {
1700 mAppBindArgs = new HashMap<String, IBinder>();
1701
1702 // Setup the application init args
1703 mAppBindArgs.put("package", ServiceManager.getService("package"));
1704 mAppBindArgs.put("window", ServiceManager.getService("window"));
1705 mAppBindArgs.put(Context.ALARM_SERVICE,
1706 ServiceManager.getService(Context.ALARM_SERVICE));
1707 }
1708 return mAppBindArgs;
1709 }
1710
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001711 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if (mFocusedActivity != r) {
1713 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001714 if (r != null) {
1715 mWindowManager.setFocusedApp(r.appToken, true);
1716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
1718 }
1719
Dianne Hackborn906497c2010-05-10 15:57:38 -07001720 private final void updateLruProcessInternalLocked(ProcessRecord app,
1721 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001723 int lrui = mLruProcesses.indexOf(app);
1724 if (lrui >= 0) mLruProcesses.remove(lrui);
1725
1726 int i = mLruProcesses.size()-1;
1727 int skipTop = 0;
1728
Dianne Hackborn906497c2010-05-10 15:57:38 -07001729 app.lruSeq = mLruSeq;
1730
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001731 // compute the new weight for this process.
1732 if (updateActivityTime) {
1733 app.lastActivityTime = SystemClock.uptimeMillis();
1734 }
1735 if (app.activities.size() > 0) {
1736 // If this process has activities, we more strongly want to keep
1737 // it around.
1738 app.lruWeight = app.lastActivityTime;
1739 } else if (app.pubProviders.size() > 0) {
1740 // If this process contains content providers, we want to keep
1741 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001742 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001743 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001744 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 } else {
1746 // If this process doesn't have activities, we less strongly
1747 // want to keep it around, and generally want to avoid getting
1748 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001749 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001750 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001751 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001752 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001753
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001754 while (i >= 0) {
1755 ProcessRecord p = mLruProcesses.get(i);
1756 // If this app shouldn't be in front of the first N background
1757 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001758 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 skipTop--;
1760 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001761 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001762 mLruProcesses.add(i+1, app);
1763 break;
1764 }
1765 i--;
1766 }
1767 if (i < 0) {
1768 mLruProcesses.add(0, app);
1769 }
1770
Dianne Hackborn906497c2010-05-10 15:57:38 -07001771 // If the app is currently using a content provider or service,
1772 // bump those processes as well.
1773 if (app.connections.size() > 0) {
1774 for (ConnectionRecord cr : app.connections) {
1775 if (cr.binding != null && cr.binding.service != null
1776 && cr.binding.service.app != null
1777 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001778 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001779 updateActivityTime, i+1);
1780 }
1781 }
1782 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001783 for (int j=app.conProviders.size()-1; j>=0; j--) {
1784 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1785 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001786 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001787 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001788 }
1789 }
1790
Joe Onorato8a9b2202010-02-26 18:56:32 -08001791 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 if (oomAdj) {
1793 updateOomAdjLocked();
1794 }
1795 }
1796
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001797 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001798 boolean oomAdj, boolean updateActivityTime) {
1799 mLruSeq++;
1800 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1801 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001802
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001805 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001806 // The system gets to run in any process. If there are multiple
1807 // processes with the same uid, just pick the first (this
1808 // should never happen).
1809 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1810 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001811 if (procs == null) return null;
1812 final int N = procs.size();
1813 for (int i = 0; i < N; i++) {
1814 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
1817 ProcessRecord proc = mProcessNames.get(processName, uid);
1818 return proc;
1819 }
1820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001822 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001823 try {
1824 if (pm.performDexOpt(packageName)) {
1825 mDidDexOpt = true;
1826 }
1827 } catch (RemoteException e) {
1828 }
1829 }
1830
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001831 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 int transit = mWindowManager.getPendingAppTransition();
1833 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1834 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1835 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1836 }
1837
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001838 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001840 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1841 boolean isolated) {
1842 ProcessRecord app;
1843 if (!isolated) {
1844 app = getProcessRecordLocked(processName, info.uid);
1845 } else {
1846 // If this is an isolated process, it can't re-use an existing process.
1847 app = null;
1848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 // We don't have to do anything more if:
1850 // (1) There is an existing application record; and
1851 // (2) The caller doesn't think it is dead, OR there is no thread
1852 // object attached to it so we know it couldn't have crashed; and
1853 // (3) There is a pid assigned to it, so it is either starting or
1854 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001855 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 + " app=" + app + " knownToBeDead=" + knownToBeDead
1857 + " thread=" + (app != null ? app.thread : null)
1858 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001859 if (app != null && app.pid > 0) {
1860 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001861 // We already have the app running, or are waiting for it to
1862 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001863 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001864 // If this is a new package in the process, add the package to the list
1865 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001866 return app;
1867 } else {
1868 // An application record is attached to a previous process,
1869 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001870 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001871 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 String hostingNameStr = hostingName != null
1876 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001877
1878 if (!isolated) {
1879 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1880 // If we are in the background, then check to see if this process
1881 // is bad. If so, we will just silently fail.
1882 if (mBadProcesses.get(info.processName, info.uid) != null) {
1883 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1884 + "/" + info.processName);
1885 return null;
1886 }
1887 } else {
1888 // When the user is explicitly starting a process, then clear its
1889 // crash count so that we won't make it bad until they see at
1890 // least one crash dialog again, and make the process good again
1891 // if it had been bad.
1892 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001893 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001894 mProcessCrashTimes.remove(info.processName, info.uid);
1895 if (mBadProcesses.get(info.processName, info.uid) != null) {
1896 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1897 info.processName);
1898 mBadProcesses.remove(info.processName, info.uid);
1899 if (app != null) {
1900 app.bad = false;
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903 }
1904 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001907 app = newProcessRecordLocked(null, info, processName, isolated);
1908 if (app == null) {
1909 Slog.w(TAG, "Failed making new process record for "
1910 + processName + "/" + info.uid + " isolated=" + isolated);
1911 return null;
1912 }
1913 mProcessNames.put(processName, app.uid, app);
1914 if (isolated) {
1915 mIsolatedProcesses.put(app.uid, app);
1916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 } else {
1918 // If this is a new package in the process, add the package to the list
1919 app.addPackage(info.packageName);
1920 }
1921
1922 // If the system is not ready yet, then hold off on starting this
1923 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001924 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001925 && !isAllowedWhileBooting(info)
1926 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 if (!mProcessesOnHold.contains(app)) {
1928 mProcessesOnHold.add(app);
1929 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001930 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 return app;
1932 }
1933
1934 startProcessLocked(app, hostingType, hostingNameStr);
1935 return (app.pid != 0) ? app : null;
1936 }
1937
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001938 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1939 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1940 }
1941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 private final void startProcessLocked(ProcessRecord app,
1943 String hostingType, String hostingNameStr) {
1944 if (app.pid > 0 && app.pid != MY_PID) {
1945 synchronized (mPidsSelfLocked) {
1946 mPidsSelfLocked.remove(app.pid);
1947 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1948 }
1949 app.pid = 0;
1950 }
1951
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001952 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1953 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 mProcessesOnHold.remove(app);
1955
1956 updateCpuStats();
1957
1958 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1959 mProcDeaths[0] = 0;
1960
1961 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001962 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001965 if (!app.isolated) {
1966 try {
1967 gids = mContext.getPackageManager().getPackageGids(
1968 app.info.packageName);
1969 } catch (PackageManager.NameNotFoundException e) {
1970 Slog.w(TAG, "Unable to retrieve gids", e);
1971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 }
1973 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1974 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1975 && mTopComponent != null
1976 && app.processName.equals(mTopComponent.getPackageName())) {
1977 uid = 0;
1978 }
1979 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1980 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1981 uid = 0;
1982 }
1983 }
1984 int debugFlags = 0;
1985 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1986 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001987 // Also turn on CheckJNI for debuggable apps. It's quite
1988 // awkward to turn on otherwise.
1989 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001991 // Run the app in safe mode if its manifest requests so or the
1992 // system is booted in safe mode.
1993 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1994 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001995 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1998 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1999 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002000 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2001 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 if ("1".equals(SystemProperties.get("debug.assert"))) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2005 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006
2007 // Start the process. It will either succeed and return a result containing
2008 // the PID of the new process, or else throw a RuntimeException.
2009 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002010 app.processName, uid, uid, gids, debugFlags,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002011 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2014 synchronized (bs) {
2015 if (bs.isOnBattery()) {
2016 app.batteryStats.incStartsLocked();
2017 }
2018 }
2019
Jeff Brown3f9dd282011-07-08 20:02:19 -07002020 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 app.processName, hostingType,
2022 hostingNameStr != null ? hostingNameStr : "");
2023
2024 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002025 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002028 StringBuilder buf = mStringBuilder;
2029 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 buf.append("Start proc ");
2031 buf.append(app.processName);
2032 buf.append(" for ");
2033 buf.append(hostingType);
2034 if (hostingNameStr != null) {
2035 buf.append(" ");
2036 buf.append(hostingNameStr);
2037 }
2038 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002039 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 buf.append(" uid=");
2041 buf.append(uid);
2042 buf.append(" gids={");
2043 if (gids != null) {
2044 for (int gi=0; gi<gids.length; gi++) {
2045 if (gi != 0) buf.append(", ");
2046 buf.append(gids[gi]);
2047
2048 }
2049 }
2050 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002051 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002052 app.pid = startResult.pid;
2053 app.usingWrapper = startResult.usingWrapper;
2054 app.removed = false;
2055 synchronized (mPidsSelfLocked) {
2056 this.mPidsSelfLocked.put(startResult.pid, app);
2057 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2058 msg.obj = app;
2059 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2060 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 } catch (RuntimeException e) {
2063 // XXX do better error recovery.
2064 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002065 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
2068
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002069 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 if (resumed) {
2071 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2072 } else {
2073 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2074 }
2075 }
2076
Amith Yamasani742a6712011-05-04 14:49:28 -07002077 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002078 if (mHeadless) {
2079 // Added because none of the other calls to ensureBootCompleted seem to fire
2080 // when running headless.
2081 ensureBootCompleted();
2082 return false;
2083 }
2084
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002085 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2086 && mTopAction == null) {
2087 // We are running in factory test mode, but unable to find
2088 // the factory test app, so just sit around displaying the
2089 // error message and don't try to start anything.
2090 return false;
2091 }
2092 Intent intent = new Intent(
2093 mTopAction,
2094 mTopData != null ? Uri.parse(mTopData) : null);
2095 intent.setComponent(mTopComponent);
2096 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2097 intent.addCategory(Intent.CATEGORY_HOME);
2098 }
2099 ActivityInfo aInfo =
2100 intent.resolveActivityInfo(mContext.getPackageManager(),
2101 STOCK_PM_FLAGS);
2102 if (aInfo != null) {
2103 intent.setComponent(new ComponentName(
2104 aInfo.applicationInfo.packageName, aInfo.name));
2105 // Don't do this if the home app is currently being
2106 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002107 aInfo = new ActivityInfo(aInfo);
2108 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002109 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2110 aInfo.applicationInfo.uid);
2111 if (app == null || app.instrumentationClass == null) {
2112 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002113 mMainStack.startActivityLocked(null, intent, null, aInfo,
2114 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 }
2116 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002117
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002118 return true;
2119 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002120
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002121 /**
2122 * Starts the "new version setup screen" if appropriate.
2123 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002125 // Only do this once per boot.
2126 if (mCheckedForSetup) {
2127 return;
2128 }
2129
2130 // We will show this screen if the current one is a different
2131 // version than the last one shown, and we are not running in
2132 // low-level factory test mode.
2133 final ContentResolver resolver = mContext.getContentResolver();
2134 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2135 Settings.Secure.getInt(resolver,
2136 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2137 mCheckedForSetup = true;
2138
2139 // See if we should be showing the platform update setup UI.
2140 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2141 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2142 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2143
2144 // We don't allow third party apps to replace this.
2145 ResolveInfo ri = null;
2146 for (int i=0; ris != null && i<ris.size(); i++) {
2147 if ((ris.get(i).activityInfo.applicationInfo.flags
2148 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2149 ri = ris.get(i);
2150 break;
2151 }
2152 }
2153
2154 if (ri != null) {
2155 String vers = ri.activityInfo.metaData != null
2156 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2157 : null;
2158 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2159 vers = ri.activityInfo.applicationInfo.metaData.getString(
2160 Intent.METADATA_SETUP_VERSION);
2161 }
2162 String lastVers = Settings.Secure.getString(
2163 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2164 if (vers != null && !vers.equals(lastVers)) {
2165 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2166 intent.setComponent(new ComponentName(
2167 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002168 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2169 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002170 }
2171 }
2172 }
2173 }
2174
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002175 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002176 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002177 }
2178
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002179 void enforceNotIsolatedCaller(String caller) {
2180 if (UserId.isIsolated(Binder.getCallingUid())) {
2181 throw new SecurityException("Isolated process not allowed to call " + caller);
2182 }
2183 }
2184
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002185 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002186 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002187 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002188 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2189 }
2190 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002191
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002192 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002193 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2194 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002195 synchronized (this) {
2196 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2197 }
2198 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002199
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002200 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002201 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002202 synchronized (this) {
2203 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2204 }
2205 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002207 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002208 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2209 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002210 synchronized (this) {
2211 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002212 }
2213 }
2214
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002215 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002216 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002217 synchronized (this) {
2218 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2219 }
2220 }
2221
2222 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002223 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2224 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002225 synchronized (this) {
2226 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2227 }
2228 }
2229
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002230 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002231 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002232 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002235 private void dispatchProcessesChanged() {
2236 int N;
2237 synchronized (this) {
2238 N = mPendingProcessChanges.size();
2239 if (mActiveProcessChanges.length < N) {
2240 mActiveProcessChanges = new ProcessChangeItem[N];
2241 }
2242 mPendingProcessChanges.toArray(mActiveProcessChanges);
2243 mAvailProcessChanges.addAll(mPendingProcessChanges);
2244 mPendingProcessChanges.clear();
2245 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2246 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002247 int i = mProcessObservers.beginBroadcast();
2248 while (i > 0) {
2249 i--;
2250 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2251 if (observer != null) {
2252 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002253 for (int j=0; j<N; j++) {
2254 ProcessChangeItem item = mActiveProcessChanges[j];
2255 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2256 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2257 + item.pid + " uid=" + item.uid + ": "
2258 + item.foregroundActivities);
2259 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2260 item.foregroundActivities);
2261 }
2262 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2263 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2264 + item.pid + " uid=" + item.uid + ": " + item.importance);
2265 observer.onImportanceChanged(item.pid, item.uid,
2266 item.importance);
2267 }
2268 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002269 } catch (RemoteException e) {
2270 }
2271 }
2272 }
2273 mProcessObservers.finishBroadcast();
2274 }
2275
2276 private void dispatchProcessDied(int pid, int uid) {
2277 int i = mProcessObservers.beginBroadcast();
2278 while (i > 0) {
2279 i--;
2280 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2281 if (observer != null) {
2282 try {
2283 observer.onProcessDied(pid, uid);
2284 } catch (RemoteException e) {
2285 }
2286 }
2287 }
2288 mProcessObservers.finishBroadcast();
2289 }
2290
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002291 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002292 final int N = mPendingActivityLaunches.size();
2293 if (N <= 0) {
2294 return;
2295 }
2296 for (int i=0; i<N; i++) {
2297 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002298 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002299 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002300 }
2301 mPendingActivityLaunches.clear();
2302 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002303
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002304 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002305 Intent intent, String resolvedType, IBinder resultTo,
2306 String resultWho, int requestCode, int startFlags,
2307 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002308 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002309 int userId = 0;
2310 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2311 // Requesting home, set the identity to the current user
2312 // HACK!
2313 userId = mCurrentUserId;
2314 } else {
2315 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2316 // the current user's userId
2317 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2318 userId = 0;
2319 } else {
2320 userId = Binder.getOrigCallingUser();
2321 }
2322 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002323 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002324 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2325 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002326 }
2327
2328 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002329 Intent intent, String resolvedType, IBinder resultTo,
2330 String resultWho, int requestCode, int startFlags, String profileFile,
2331 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002332 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002333 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002334 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002335 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002336 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2337 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002338 return res;
2339 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002340
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002341 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002342 Intent intent, String resolvedType, IBinder resultTo,
2343 String resultWho, int requestCode, int startFlags, Configuration config,
2344 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002345 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002346 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002347 resultTo, resultWho, requestCode, startFlags,
2348 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002349 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002350 }
2351
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002352 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002353 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002354 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002355 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002356 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002357 // Refuse possible leaked file descriptors
2358 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2359 throw new IllegalArgumentException("File descriptors passed in Intent");
2360 }
2361
2362 IIntentSender sender = intent.getTarget();
2363 if (!(sender instanceof PendingIntentRecord)) {
2364 throw new IllegalArgumentException("Bad PendingIntent object");
2365 }
2366
2367 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002368
2369 synchronized (this) {
2370 // If this is coming from the currently resumed activity, it is
2371 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002372 if (mMainStack.mResumedActivity != null
2373 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002374 Binder.getCallingUid()) {
2375 mAppSwitchesAllowedTime = 0;
2376 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002377 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002378 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2379 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002380 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002381 }
2382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002384 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 // Refuse possible leaked file descriptors
2386 if (intent != null && intent.hasFileDescriptors() == true) {
2387 throw new IllegalArgumentException("File descriptors passed in Intent");
2388 }
2389
2390 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002391 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2392 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002393 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 return false;
2395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 if (r.app == null || r.app.thread == null) {
2397 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002398 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 return false;
2400 }
2401 intent = new Intent(intent);
2402 // The caller is not allowed to change the data.
2403 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2404 // And we are resetting to find the next component...
2405 intent.setComponent(null);
2406
2407 ActivityInfo aInfo = null;
2408 try {
2409 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002410 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002412 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2413 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414
2415 // Look for the original activity in the list...
2416 final int N = resolves != null ? resolves.size() : 0;
2417 for (int i=0; i<N; i++) {
2418 ResolveInfo rInfo = resolves.get(i);
2419 if (rInfo.activityInfo.packageName.equals(r.packageName)
2420 && rInfo.activityInfo.name.equals(r.info.name)) {
2421 // We found the current one... the next matching is
2422 // after it.
2423 i++;
2424 if (i<N) {
2425 aInfo = resolves.get(i).activityInfo;
2426 }
2427 break;
2428 }
2429 }
2430 } catch (RemoteException e) {
2431 }
2432
2433 if (aInfo == null) {
2434 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002435 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 return false;
2437 }
2438
2439 intent.setComponent(new ComponentName(
2440 aInfo.applicationInfo.packageName, aInfo.name));
2441 intent.setFlags(intent.getFlags()&~(
2442 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2443 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2444 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2445 Intent.FLAG_ACTIVITY_NEW_TASK));
2446
2447 // Okay now we need to start the new activity, replacing the
2448 // currently running activity. This is a little tricky because
2449 // we want to start the new one as if the current one is finished,
2450 // but not finish the current one first so that there is no flicker.
2451 // And thus...
2452 final boolean wasFinishing = r.finishing;
2453 r.finishing = true;
2454
2455 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002456 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 final String resultWho = r.resultWho;
2458 final int requestCode = r.requestCode;
2459 r.resultTo = null;
2460 if (resultTo != null) {
2461 resultTo.removeResultsLocked(r, resultWho, requestCode);
2462 }
2463
2464 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002465 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002466 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2467 resultWho, requestCode, -1, r.launchedFromUid, 0,
2468 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 Binder.restoreCallingIdentity(origId);
2470
2471 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 return false;
2474 }
2475 return true;
2476 }
2477 }
2478
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002479 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002482
2483 // This is so super not safe, that only the system (or okay root)
2484 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002485 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002486 final int callingUid = Binder.getCallingUid();
2487 if (callingUid != 0 && callingUid != Process.myUid()) {
2488 throw new SecurityException(
2489 "startActivityInPackage only available to the system");
2490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491
Amith Yamasani742a6712011-05-04 14:49:28 -07002492 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002493 resultTo, resultWho, requestCode, startFlags,
2494 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002495 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002496 }
2497
2498 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002499 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002500 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002502 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002503 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002504 }
2505
2506 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002507 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2508 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002509
2510 // This is so super not safe, that only the system (or okay root)
2511 // can do it.
2512 final int callingUid = Binder.getCallingUid();
2513 if (callingUid != 0 && callingUid != Process.myUid()) {
2514 throw new SecurityException(
2515 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002517 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002518 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002519 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 }
2521
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002524 // Quick case: check if the top-most recent task is the same.
2525 if (N > 0 && mRecentTasks.get(0) == task) {
2526 return;
2527 }
2528 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 for (int i=0; i<N; i++) {
2530 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002531 if (task.userId == tr.userId
2532 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2533 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 mRecentTasks.remove(i);
2535 i--;
2536 N--;
2537 if (task.intent == null) {
2538 // If the new recent task we are adding is not fully
2539 // specified, then replace it with the existing recent task.
2540 task = tr;
2541 }
2542 }
2543 }
2544 if (N >= MAX_RECENT_TASKS) {
2545 mRecentTasks.remove(N-1);
2546 }
2547 mRecentTasks.add(0, task);
2548 }
2549
2550 public void setRequestedOrientation(IBinder token,
2551 int requestedOrientation) {
2552 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002553 ActivityRecord r = mMainStack.isInStackLocked(token);
2554 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 return;
2556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002558 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002560 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002561 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 if (config != null) {
2563 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002564 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 Binder.restoreCallingIdentity(origId);
2569 }
2570 }
2571
2572 public int getRequestedOrientation(IBinder token) {
2573 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002574 ActivityRecord r = mMainStack.isInStackLocked(token);
2575 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2577 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002578 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
2581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 /**
2583 * This is the internal entry point for handling Activity.finish().
2584 *
2585 * @param token The Binder token referencing the Activity we want to finish.
2586 * @param resultCode Result code, if any, from this Activity.
2587 * @param resultData Result data (Intent), if any, from this Activity.
2588 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002589 * @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 -08002590 */
2591 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2592 // Refuse possible leaked file descriptors
2593 if (resultData != null && resultData.hasFileDescriptors() == true) {
2594 throw new IllegalArgumentException("File descriptors passed in Intent");
2595 }
2596
2597 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002598 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002600 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 if (next != null) {
2602 // ask watcher if this is allowed
2603 boolean resumeOK = true;
2604 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002605 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002607 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 }
2609
2610 if (!resumeOK) {
2611 return false;
2612 }
2613 }
2614 }
2615 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 resultData, "app-request");
2618 Binder.restoreCallingIdentity(origId);
2619 return res;
2620 }
2621 }
2622
Dianne Hackborn860755f2010-06-03 18:47:52 -07002623 public final void finishHeavyWeightApp() {
2624 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2625 != PackageManager.PERMISSION_GRANTED) {
2626 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2627 + Binder.getCallingPid()
2628 + ", uid=" + Binder.getCallingUid()
2629 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2630 Slog.w(TAG, msg);
2631 throw new SecurityException(msg);
2632 }
2633
2634 synchronized(this) {
2635 if (mHeavyWeightProcess == null) {
2636 return;
2637 }
2638
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002639 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002640 mHeavyWeightProcess.activities);
2641 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002642 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002643 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002644 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002645 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002646 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002647 null, "finish-heavy");
2648 }
2649 }
2650 }
2651
2652 mHeavyWeightProcess = null;
2653 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2654 }
2655 }
2656
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002657 public void crashApplication(int uid, int initialPid, String packageName,
2658 String message) {
2659 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2660 != PackageManager.PERMISSION_GRANTED) {
2661 String msg = "Permission Denial: crashApplication() from pid="
2662 + Binder.getCallingPid()
2663 + ", uid=" + Binder.getCallingUid()
2664 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2665 Slog.w(TAG, msg);
2666 throw new SecurityException(msg);
2667 }
2668
2669 synchronized(this) {
2670 ProcessRecord proc = null;
2671
2672 // Figure out which process to kill. We don't trust that initialPid
2673 // still has any relation to current pids, so must scan through the
2674 // list.
2675 synchronized (mPidsSelfLocked) {
2676 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2677 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002678 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002679 continue;
2680 }
2681 if (p.pid == initialPid) {
2682 proc = p;
2683 break;
2684 }
2685 for (String str : p.pkgList) {
2686 if (str.equals(packageName)) {
2687 proc = p;
2688 }
2689 }
2690 }
2691 }
2692
2693 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002694 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002695 + " initialPid=" + initialPid
2696 + " packageName=" + packageName);
2697 return;
2698 }
2699
2700 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002701 if (proc.pid == Process.myPid()) {
2702 Log.w(TAG, "crashApplication: trying to crash self!");
2703 return;
2704 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002705 long ident = Binder.clearCallingIdentity();
2706 try {
2707 proc.thread.scheduleCrash(message);
2708 } catch (RemoteException e) {
2709 }
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713 }
2714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 public final void finishSubActivity(IBinder token, String resultWho,
2716 int requestCode) {
2717 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002719 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 Binder.restoreCallingIdentity(origId);
2721 }
2722 }
2723
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002724 public boolean finishActivityAffinity(IBinder token) {
2725 synchronized(this) {
2726 final long origId = Binder.clearCallingIdentity();
2727 boolean res = mMainStack.finishActivityAffinityLocked(token);
2728 Binder.restoreCallingIdentity(origId);
2729 return res;
2730 }
2731 }
2732
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002733 public boolean willActivityBeVisible(IBinder token) {
2734 synchronized(this) {
2735 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002736 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2737 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002738 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002739 return true;
2740 }
2741 if (r.fullscreen && !r.finishing) {
2742 return false;
2743 }
2744 }
2745 return true;
2746 }
2747 }
2748
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002749 public void overridePendingTransition(IBinder token, String packageName,
2750 int enterAnim, int exitAnim) {
2751 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002752 ActivityRecord self = mMainStack.isInStackLocked(token);
2753 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002754 return;
2755 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002756
2757 final long origId = Binder.clearCallingIdentity();
2758
2759 if (self.state == ActivityState.RESUMED
2760 || self.state == ActivityState.PAUSING) {
2761 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002762 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002763 }
2764
2765 Binder.restoreCallingIdentity(origId);
2766 }
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 * Main function for removing an existing process from the activity manager
2771 * as a result of that process going away. Clears out all connections
2772 * to the process.
2773 */
2774 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002775 boolean restarting, boolean allowRestart) {
2776 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002778 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002781 if (mProfileProc == app) {
2782 clearProfilerLocked();
2783 }
2784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002786 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2787 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2788 mMainStack.mPausingActivity = null;
2789 }
2790 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2791 mMainStack.mLastPausedActivity = null;
2792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793
2794 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002795 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
2797 boolean atTop = true;
2798 boolean hasVisibleActivities = false;
2799
2800 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002802 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 TAG, "Removing app " + app + " from history with " + i + " entries");
2804 while (i > 0) {
2805 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002806 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002807 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2809 if (r.app == app) {
2810 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002811 if (ActivityStack.DEBUG_ADD_REMOVE) {
2812 RuntimeException here = new RuntimeException("here");
2813 here.fillInStackTrace();
2814 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2815 + ": haveState=" + r.haveState
2816 + " stateNotNeeded=" + r.stateNotNeeded
2817 + " finishing=" + r.finishing
2818 + " state=" + r.state, here);
2819 }
2820 if (!r.finishing) {
2821 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002822 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2823 System.identityHashCode(r),
2824 r.task.taskId, r.shortComponentName,
2825 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002826 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002827 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828
2829 } else {
2830 // We have the current state for this activity, so
2831 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002832 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 TAG, "Keeping entry, setting app to null");
2834 if (r.visible) {
2835 hasVisibleActivities = true;
2836 }
2837 r.app = null;
2838 r.nowVisible = false;
2839 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002840 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2841 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 r.icicle = null;
2843 }
2844 }
2845
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002846 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 }
2848 atTop = false;
2849 }
2850
2851 app.activities.clear();
2852
2853 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002854 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 + " running instrumentation " + app.instrumentationClass);
2856 Bundle info = new Bundle();
2857 info.putString("shortMsg", "Process crashed.");
2858 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2859 }
2860
2861 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 // If there was nothing to resume, and we are not already
2864 // restarting this process, but there is a visible activity that
2865 // is hosted by the process... then make sure all visible
2866 // activities are running, taking care of restarting this
2867 // process.
2868 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871 }
2872 }
2873 }
2874
2875 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2876 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002878 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2879 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2881 return i;
2882 }
2883 }
2884 return -1;
2885 }
2886
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002887 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 IApplicationThread thread) {
2889 if (thread == null) {
2890 return null;
2891 }
2892
2893 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002894 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 }
2896
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002897 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 IApplicationThread thread) {
2899
2900 mProcDeaths[0]++;
2901
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002902 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2903 synchronized (stats) {
2904 stats.noteProcessDiedLocked(app.info.uid, pid);
2905 }
2906
Magnus Edlund7bb25812010-02-24 15:45:06 +01002907 // Clean up already done if the process has been re-started.
2908 if (app.pid == pid && app.thread != null &&
2909 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002910 if (!app.killedBackground) {
2911 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2912 + ") has died.");
2913 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002914 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002915 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 TAG, "Dying app: " + app + ", pid: " + pid
2917 + ", thread: " + thread.asBinder());
2918 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002919 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920
2921 if (doLowMem) {
2922 // If there are no longer any background processes running,
2923 // and the app that died was not running instrumentation,
2924 // then tell everyone we are now low on memory.
2925 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002926 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2927 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002928 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 haveBg = true;
2930 break;
2931 }
2932 }
2933
2934 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002935 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002936 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002937 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2938 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002939 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002940 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2941 // The low memory report is overriding any current
2942 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002943 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002944 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002945 rec.lastRequestedGc = 0;
2946 } else {
2947 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002949 rec.reportLowMemory = true;
2950 rec.lastLowMemory = now;
2951 mProcessesToGc.remove(rec);
2952 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 }
2954 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002955 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002956 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002959 } else if (app.pid != pid) {
2960 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002961 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002962 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002963 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002964 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002965 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 + thread.asBinder());
2967 }
2968 }
2969
Dan Egnor42471dd2010-01-07 17:25:22 -08002970 /**
2971 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002972 * @param clearTraces causes the dump file to be erased prior to the new
2973 * traces being written, if true; when false, the new traces will be
2974 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002975 * @param firstPids of dalvik VM processes to dump stack traces for first
2976 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07002977 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08002978 * @return file containing stack traces, or null if no dump file is configured
2979 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002980 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07002981 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002982 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2983 if (tracesPath == null || tracesPath.length() == 0) {
2984 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002986
2987 File tracesFile = new File(tracesPath);
2988 try {
2989 File tracesDir = tracesFile.getParentFile();
2990 if (!tracesDir.exists()) tracesFile.mkdirs();
2991 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2992
Christopher Tate6ee412d2010-05-28 12:01:56 -07002993 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002994 tracesFile.createNewFile();
2995 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2996 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002997 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002998 return null;
2999 }
3000
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003001 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003002 return tracesFile;
3003 }
3004
3005 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003006 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003007 // Use a FileObserver to detect when traces finish writing.
3008 // The order of traces is considered important to maintain for legibility.
3009 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3010 public synchronized void onEvent(int event, String path) { notify(); }
3011 };
3012
3013 try {
3014 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003015
3016 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003017 if (firstPids != null) {
3018 try {
3019 int num = firstPids.size();
3020 for (int i = 0; i < num; i++) {
3021 synchronized (observer) {
3022 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3023 observer.wait(200); // Wait for write-close, give up after 200msec
3024 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003025 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003026 } catch (InterruptedException e) {
3027 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003028 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003029 }
3030
3031 // Next measure CPU usage.
3032 if (processStats != null) {
3033 processStats.init();
3034 System.gc();
3035 processStats.update();
3036 try {
3037 synchronized (processStats) {
3038 processStats.wait(500); // measure over 1/2 second.
3039 }
3040 } catch (InterruptedException e) {
3041 }
3042 processStats.update();
3043
3044 // We'll take the stack crawls of just the top apps using CPU.
3045 final int N = processStats.countWorkingStats();
3046 int numProcs = 0;
3047 for (int i=0; i<N && numProcs<5; i++) {
3048 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3049 if (lastPids.indexOfKey(stats.pid) >= 0) {
3050 numProcs++;
3051 try {
3052 synchronized (observer) {
3053 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3054 observer.wait(200); // Wait for write-close, give up after 200msec
3055 }
3056 } catch (InterruptedException e) {
3057 Log.wtf(TAG, e);
3058 }
3059
3060 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003061 }
3062 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003063
Dan Egnor42471dd2010-01-07 17:25:22 -08003064 } finally {
3065 observer.stopWatching();
3066 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003067
3068 if (nativeProcs != null) {
3069 int[] pids = Process.getPidsForCommands(nativeProcs);
3070 if (pids != null) {
3071 for (int pid : pids) {
3072 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3073 }
3074 }
3075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
3077
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003078 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003079 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003080 return;
3081 }
3082 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3083 if (tracesPath == null || tracesPath.length() == 0) {
3084 return;
3085 }
3086
3087 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3088 StrictMode.allowThreadDiskWrites();
3089 try {
3090 final File tracesFile = new File(tracesPath);
3091 final File tracesDir = tracesFile.getParentFile();
3092 final File tracesTmp = new File(tracesDir, "__tmp__");
3093 try {
3094 if (!tracesDir.exists()) tracesFile.mkdirs();
3095 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3096
3097 if (tracesFile.exists()) {
3098 tracesTmp.delete();
3099 tracesFile.renameTo(tracesTmp);
3100 }
3101 StringBuilder sb = new StringBuilder();
3102 Time tobj = new Time();
3103 tobj.set(System.currentTimeMillis());
3104 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3105 sb.append(": ");
3106 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3107 sb.append(" since ");
3108 sb.append(msg);
3109 FileOutputStream fos = new FileOutputStream(tracesFile);
3110 fos.write(sb.toString().getBytes());
3111 if (app == null) {
3112 fos.write("\n*** No application process!".getBytes());
3113 }
3114 fos.close();
3115 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3116 } catch (IOException e) {
3117 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3118 return;
3119 }
3120
3121 if (app != null) {
3122 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3123 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003124 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003125 }
3126
3127 File lastTracesFile = null;
3128 File curTracesFile = null;
3129 for (int i=9; i>=0; i--) {
3130 String name = String.format("slow%02d.txt", i);
3131 curTracesFile = new File(tracesDir, name);
3132 if (curTracesFile.exists()) {
3133 if (lastTracesFile != null) {
3134 curTracesFile.renameTo(lastTracesFile);
3135 } else {
3136 curTracesFile.delete();
3137 }
3138 }
3139 lastTracesFile = curTracesFile;
3140 }
3141 tracesFile.renameTo(curTracesFile);
3142 if (tracesTmp.exists()) {
3143 tracesTmp.renameTo(tracesFile);
3144 }
3145 } finally {
3146 StrictMode.setThreadPolicy(oldPolicy);
3147 }
3148 }
3149
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003150 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3151 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003152 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3153 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3154
Dianne Hackborn287952c2010-09-22 22:34:31 -07003155 if (mController != null) {
3156 try {
3157 // 0 == continue, -1 = kill process immediately
3158 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3159 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3160 } catch (RemoteException e) {
3161 mController = null;
3162 }
3163 }
3164
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003165 long anrTime = SystemClock.uptimeMillis();
3166 if (MONITOR_CPU_USAGE) {
3167 updateCpuStatsNow();
3168 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003169
3170 synchronized (this) {
3171 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3172 if (mShuttingDown) {
3173 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3174 return;
3175 } else if (app.notResponding) {
3176 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3177 return;
3178 } else if (app.crashing) {
3179 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3180 return;
3181 }
3182
3183 // In case we come through here for the same app before completing
3184 // this one, mark as anring now so we will bail out.
3185 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003186
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003187 // Log the ANR to the event log.
3188 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3189 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003190
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003191 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003192 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003193
3194 int parentPid = app.pid;
3195 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003196 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003197
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003198 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003199
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003200 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3201 ProcessRecord r = mLruProcesses.get(i);
3202 if (r != null && r.thread != null) {
3203 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003204 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3205 if (r.persistent) {
3206 firstPids.add(pid);
3207 } else {
3208 lastPids.put(pid, Boolean.TRUE);
3209 }
3210 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 }
3213 }
3214
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003216 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003217 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003218 info.append("ANR in ").append(app.processName);
3219 if (activity != null && activity.shortComponentName != null) {
3220 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003221 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003222 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003224 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003226 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003227 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229
Dianne Hackborn287952c2010-09-22 22:34:31 -07003230 final ProcessStats processStats = new ProcessStats(true);
3231
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003232 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003233
Dan Egnor42471dd2010-01-07 17:25:22 -08003234 String cpuInfo = null;
3235 if (MONITOR_CPU_USAGE) {
3236 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003237 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003238 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003239 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003240 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003241 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003244 info.append(processStats.printCurrentState(anrTime));
3245
Joe Onorato8a9b2202010-02-26 18:56:32 -08003246 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003247 if (tracesFile == null) {
3248 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3249 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3250 }
3251
Jeff Sharkeya353d262011-10-28 11:12:06 -07003252 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3253 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003254
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003255 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003257 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3258 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003260 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3261 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003264 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
3266 }
3267
Dan Egnor42471dd2010-01-07 17:25:22 -08003268 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3269 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3270 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003271
3272 synchronized (this) {
3273 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003274 Slog.w(TAG, "Killing " + app + ": background ANR");
3275 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3276 app.processName, app.setAdj, "background ANR");
3277 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003278 return;
3279 }
3280
3281 // Set the app's notResponding state, and look up the errorReportReceiver
3282 makeAppNotRespondingLocked(app,
3283 activity != null ? activity.shortComponentName : null,
3284 annotation != null ? "ANR " + annotation : "ANR",
3285 info.toString());
3286
3287 // Bring up the infamous App Not Responding dialog
3288 Message msg = Message.obtain();
3289 HashMap map = new HashMap();
3290 msg.what = SHOW_NOT_RESPONDING_MSG;
3291 msg.obj = map;
3292 map.put("app", app);
3293 if (activity != null) {
3294 map.put("activity", activity);
3295 }
3296
3297 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
3300
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003301 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3302 if (!mLaunchWarningShown) {
3303 mLaunchWarningShown = true;
3304 mHandler.post(new Runnable() {
3305 @Override
3306 public void run() {
3307 synchronized (ActivityManagerService.this) {
3308 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3309 d.show();
3310 mHandler.postDelayed(new Runnable() {
3311 @Override
3312 public void run() {
3313 synchronized (ActivityManagerService.this) {
3314 d.dismiss();
3315 mLaunchWarningShown = false;
3316 }
3317 }
3318 }, 4000);
3319 }
3320 }
3321 });
3322 }
3323 }
3324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003326 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003327 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 int uid = Binder.getCallingUid();
3329 int pid = Binder.getCallingPid();
3330 long callingId = Binder.clearCallingIdentity();
3331 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003332 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 int pkgUid = -1;
3334 synchronized(this) {
3335 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003336 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 } catch (RemoteException e) {
3338 }
3339 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003340 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 return false;
3342 }
3343 if (uid == pkgUid || checkComponentPermission(
3344 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003345 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003347 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 } else {
3349 throw new SecurityException(pid+" does not have permission:"+
3350 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3351 "for process:"+packageName);
3352 }
3353 }
3354
3355 try {
3356 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003357 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3359 Uri.fromParts("package", packageName, null));
3360 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003361 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003362 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 } catch (RemoteException e) {
3364 }
3365 } finally {
3366 Binder.restoreCallingIdentity(callingId);
3367 }
3368 return true;
3369 }
3370
Dianne Hackborn03abb812010-01-04 18:43:19 -08003371 public void killBackgroundProcesses(final String packageName) {
3372 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3373 != PackageManager.PERMISSION_GRANTED &&
3374 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3375 != PackageManager.PERMISSION_GRANTED) {
3376 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 + Binder.getCallingPid()
3378 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003379 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003380 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 throw new SecurityException(msg);
3382 }
3383
Amith Yamasani483f3b02012-03-13 16:08:00 -07003384 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 long callingId = Binder.clearCallingIdentity();
3386 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003387 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 int pkgUid = -1;
3389 synchronized(this) {
3390 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003391 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 } catch (RemoteException e) {
3393 }
3394 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003395 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 return;
3397 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003398 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003399 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3400 }
3401 } finally {
3402 Binder.restoreCallingIdentity(callingId);
3403 }
3404 }
3405
3406 public void killAllBackgroundProcesses() {
3407 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3408 != PackageManager.PERMISSION_GRANTED) {
3409 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3410 + Binder.getCallingPid()
3411 + ", uid=" + Binder.getCallingUid()
3412 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3413 Slog.w(TAG, msg);
3414 throw new SecurityException(msg);
3415 }
3416
3417 long callingId = Binder.clearCallingIdentity();
3418 try {
3419 synchronized(this) {
3420 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3421 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3422 final int NA = apps.size();
3423 for (int ia=0; ia<NA; ia++) {
3424 ProcessRecord app = apps.valueAt(ia);
3425 if (app.persistent) {
3426 // we don't kill persistent processes
3427 continue;
3428 }
3429 if (app.removed) {
3430 procs.add(app);
3431 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3432 app.removed = true;
3433 procs.add(app);
3434 }
3435 }
3436 }
3437
3438 int N = procs.size();
3439 for (int i=0; i<N; i++) {
3440 removeProcessLocked(procs.get(i), false, true, "kill all background");
3441 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003442 }
3443 } finally {
3444 Binder.restoreCallingIdentity(callingId);
3445 }
3446 }
3447
3448 public void forceStopPackage(final String packageName) {
3449 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3450 != PackageManager.PERMISSION_GRANTED) {
3451 String msg = "Permission Denial: forceStopPackage() from pid="
3452 + Binder.getCallingPid()
3453 + ", uid=" + Binder.getCallingUid()
3454 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003455 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003456 throw new SecurityException(msg);
3457 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003458 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003459 long callingId = Binder.clearCallingIdentity();
3460 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003461 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003462 int pkgUid = -1;
3463 synchronized(this) {
3464 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003465 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003466 } catch (RemoteException e) {
3467 }
3468 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003469 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003470 return;
3471 }
3472 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003473 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003474 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003475 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003476 } catch (IllegalArgumentException e) {
3477 Slog.w(TAG, "Failed trying to unstop package "
3478 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 }
3481 } finally {
3482 Binder.restoreCallingIdentity(callingId);
3483 }
3484 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003485
3486 /*
3487 * The pkg name and uid have to be specified.
3488 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3489 */
3490 public void killApplicationWithUid(String pkg, int uid) {
3491 if (pkg == null) {
3492 return;
3493 }
3494 // Make sure the uid is valid.
3495 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003496 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003497 return;
3498 }
3499 int callerUid = Binder.getCallingUid();
3500 // Only the system server can kill an application
3501 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003502 // Post an aysnc message to kill the application
3503 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3504 msg.arg1 = uid;
3505 msg.arg2 = 0;
3506 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003507 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003508 } else {
3509 throw new SecurityException(callerUid + " cannot kill pkg: " +
3510 pkg);
3511 }
3512 }
3513
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003514 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003515 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003516
3517 final int uid = Binder.getCallingUid();
3518 final long origId = Binder.clearCallingIdentity();
3519 synchronized (this) {
3520 closeSystemDialogsLocked(uid, reason);
3521 }
3522 Binder.restoreCallingIdentity(origId);
3523 }
3524
3525 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003526 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003527 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003528 if (reason != null) {
3529 intent.putExtra("reason", reason);
3530 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003531 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003532
Dianne Hackborne302a162012-05-15 14:58:32 -07003533 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3534 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003535 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003536 r.stack.finishActivityLocked(r, i,
3537 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003538 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003539 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003540
3541 broadcastIntentLocked(null, null, intent, null,
3542 null, 0, null, null, null, false, false, -1,
3543 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003544 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003545
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003546 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003547 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003548 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003549 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3550 for (int i=pids.length-1; i>=0; i--) {
3551 infos[i] = new Debug.MemoryInfo();
3552 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003553 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003554 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003555 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003556
Dianne Hackbornb437e092011-08-05 17:50:29 -07003557 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003558 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003559 long[] pss = new long[pids.length];
3560 for (int i=pids.length-1; i>=0; i--) {
3561 pss[i] = Debug.getPss(pids[i]);
3562 }
3563 return pss;
3564 }
3565
Christopher Tate5e1ab332009-09-01 20:32:49 -07003566 public void killApplicationProcess(String processName, int uid) {
3567 if (processName == null) {
3568 return;
3569 }
3570
3571 int callerUid = Binder.getCallingUid();
3572 // Only the system server can kill an application
3573 if (callerUid == Process.SYSTEM_UID) {
3574 synchronized (this) {
3575 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003576 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003577 try {
3578 app.thread.scheduleSuicide();
3579 } catch (RemoteException e) {
3580 // If the other end already died, then our work here is done.
3581 }
3582 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003583 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003584 + processName + " / " + uid);
3585 }
3586 }
3587 } else {
3588 throw new SecurityException(callerUid + " cannot kill app process: " +
3589 processName);
3590 }
3591 }
3592
Dianne Hackborn03abb812010-01-04 18:43:19 -08003593 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003594 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3596 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003597 if (!mProcessesReady) {
3598 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 intent.putExtra(Intent.EXTRA_UID, uid);
3601 broadcastIntentLocked(null, null, intent,
3602 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003603 false, false,
3604 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 }
3606
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003607 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003608 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003609 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003610 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611
Dianne Hackborn03abb812010-01-04 18:43:19 -08003612 // Remove all processes this package may have touched: all with the
3613 // same UID (except for the system or root user), and all whose name
3614 // matches the package name.
3615 final String procNamePrefix = packageName + ":";
3616 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3617 final int NA = apps.size();
3618 for (int ia=0; ia<NA; ia++) {
3619 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003620 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003621 // we don't kill persistent processes
3622 continue;
3623 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003624 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003625 if (doit) {
3626 procs.add(app);
3627 }
Amith Yamasani13593602012-03-22 16:16:17 -07003628 // If uid is specified and the uid and process name match
3629 // Or, the uid is not specified and the process name matches
3630 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003631 || ((app.processName.equals(packageName)
3632 || app.processName.startsWith(procNamePrefix))
3633 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003634 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003635 if (!doit) {
3636 return true;
3637 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003638 app.removed = true;
3639 procs.add(app);
3640 }
3641 }
3642 }
3643 }
3644
3645 int N = procs.size();
3646 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003647 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003648 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003649 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003650 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003651
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003652 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003653 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003654 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003655 int i;
3656 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 if (uid < 0) {
3659 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003660 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 } catch (RemoteException e) {
3662 }
3663 }
3664
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003665 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003666 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003667
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3669 while (badApps.hasNext()) {
3670 SparseArray<Long> ba = badApps.next();
3671 if (ba.get(uid) != null) {
3672 badApps.remove();
3673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 }
3675 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003676
3677 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003678 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003680 TaskRecord lastTask = null;
3681 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003682 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003683 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003684 if (r.userId == userId
3685 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003686 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003687 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003688 if (r.finishing) {
3689 // If this activity is just finishing, then it is not
3690 // interesting as far as something to stop.
3691 continue;
3692 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003693 return true;
3694 }
3695 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003696 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003697 if (samePackage) {
3698 if (r.app != null) {
3699 r.app.removed = true;
3700 }
3701 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003703 lastTask = r.task;
3704 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003705 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003706 i--;
3707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 }
3709 }
3710
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003711 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3712 if (!doit) {
3713 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003715 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003717
3718 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003719 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003720 if (provider.info.packageName.equals(name)
3721 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3722 if (!doit) {
3723 return true;
3724 }
3725 didSomething = true;
3726 providers.add(provider);
3727 }
3728 }
3729
3730 N = providers.size();
3731 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003732 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003733 }
3734
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003735 if (doit) {
3736 if (purgeCache) {
3737 AttributeCache ac = AttributeCache.instance();
3738 if (ac != null) {
3739 ac.removePackage(name);
3740 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003741 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003742 if (mBooted) {
3743 mMainStack.resumeTopActivityLocked(null);
3744 mMainStack.scheduleIdleLocked();
3745 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003746 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003747
3748 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 }
3750
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003751 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003752 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003754 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003755 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003756 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 + "/" + uid + ")");
3758
3759 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003760 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003761 if (mHeavyWeightProcess == app) {
3762 mHeavyWeightProcess = null;
3763 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 boolean needRestart = false;
3766 if (app.pid > 0 && app.pid != MY_PID) {
3767 int pid = app.pid;
3768 synchronized (mPidsSelfLocked) {
3769 mPidsSelfLocked.remove(pid);
3770 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3771 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003772 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003773 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003774 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003775 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003777 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003779 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 } else {
3781 needRestart = true;
3782 }
3783 }
3784 } else {
3785 mRemovedProcesses.add(app);
3786 }
3787
3788 return needRestart;
3789 }
3790
3791 private final void processStartTimedOutLocked(ProcessRecord app) {
3792 final int pid = app.pid;
3793 boolean gone = false;
3794 synchronized (mPidsSelfLocked) {
3795 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3796 if (knownApp != null && knownApp.thread == null) {
3797 mPidsSelfLocked.remove(pid);
3798 gone = true;
3799 }
3800 }
3801
3802 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003803 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003804 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003805 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003806 mProcessNames.remove(app.processName, app.uid);
3807 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003808 if (mHeavyWeightProcess == app) {
3809 mHeavyWeightProcess = null;
3810 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3811 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003812 // Take care of any launching providers waiting for this process.
3813 checkAppInLaunchingProvidersLocked(app, true);
3814 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003815 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003816 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3817 app.processName, app.setAdj, "start timeout");
3818 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003819 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003820 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003821 try {
3822 IBackupManager bm = IBackupManager.Stub.asInterface(
3823 ServiceManager.getService(Context.BACKUP_SERVICE));
3824 bm.agentDisconnected(app.info.packageName);
3825 } catch (RemoteException e) {
3826 // Can't happen; the backup manager is local
3827 }
3828 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003829 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003830 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003831 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003834 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 }
3837
3838 private final boolean attachApplicationLocked(IApplicationThread thread,
3839 int pid) {
3840
3841 // Find the application record that is being attached... either via
3842 // the pid if we are running in multiple processes, or just pull the
3843 // next app record if we are emulating process with anonymous threads.
3844 ProcessRecord app;
3845 if (pid != MY_PID && pid >= 0) {
3846 synchronized (mPidsSelfLocked) {
3847 app = mPidsSelfLocked.get(pid);
3848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 } else {
3850 app = null;
3851 }
3852
3853 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003856 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003858 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 } else {
3860 try {
3861 thread.scheduleExit();
3862 } catch (Exception e) {
3863 // Ignore exceptions.
3864 }
3865 }
3866 return false;
3867 }
3868
3869 // If this application record is still attached to a previous
3870 // process, clean it up now.
3871 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003872 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 }
3874
3875 // Tell the process all about itself.
3876
Joe Onorato8a9b2202010-02-26 18:56:32 -08003877 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 TAG, "Binding process pid " + pid + " to record " + app);
3879
3880 String processName = app.processName;
3881 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003882 AppDeathRecipient adr = new AppDeathRecipient(
3883 app, pid, thread);
3884 thread.asBinder().linkToDeath(adr, 0);
3885 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 } catch (RemoteException e) {
3887 app.resetPackageList();
3888 startProcessLocked(app, "link fail", processName);
3889 return false;
3890 }
3891
Doug Zongker2bec3d42009-12-04 12:52:44 -08003892 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893
3894 app.thread = thread;
3895 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003896 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3897 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 app.forcingToForeground = null;
3899 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003900 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 app.debugging = false;
3902
3903 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3904
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003905 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003906 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003908 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003909 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003910 }
3911
Joe Onorato8a9b2202010-02-26 18:56:32 -08003912 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 TAG, "New app record " + app
3914 + " thread=" + thread.asBinder() + " pid=" + pid);
3915 try {
3916 int testMode = IApplicationThread.DEBUG_OFF;
3917 if (mDebugApp != null && mDebugApp.equals(processName)) {
3918 testMode = mWaitForDebugger
3919 ? IApplicationThread.DEBUG_WAIT
3920 : IApplicationThread.DEBUG_ON;
3921 app.debugging = true;
3922 if (mDebugTransient) {
3923 mDebugApp = mOrigDebugApp;
3924 mWaitForDebugger = mOrigWaitForDebugger;
3925 }
3926 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003927 String profileFile = app.instrumentationProfileFile;
3928 ParcelFileDescriptor profileFd = null;
3929 boolean profileAutoStop = false;
3930 if (mProfileApp != null && mProfileApp.equals(processName)) {
3931 mProfileProc = app;
3932 profileFile = mProfileFile;
3933 profileFd = mProfileFd;
3934 profileAutoStop = mAutoStopProfiler;
3935 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003936 boolean enableOpenGlTrace = false;
3937 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3938 enableOpenGlTrace = true;
3939 mOpenGlTraceApp = null;
3940 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003941
Christopher Tate181fafa2009-05-14 11:12:14 -07003942 // If the app is being launched for restore or full backup, set it up specially
3943 boolean isRestrictedBackupMode = false;
3944 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3945 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003946 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003947 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3948 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003949
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003950 ensurePackageDexOpt(app.instrumentationInfo != null
3951 ? app.instrumentationInfo.packageName
3952 : app.info.packageName);
3953 if (app.instrumentationClass != null) {
3954 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003955 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003956 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003957 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003958 ApplicationInfo appInfo = app.instrumentationInfo != null
3959 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003960 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003961 if (profileFd != null) {
3962 profileFd = profileFd.dup();
3963 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003964 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003965 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003966 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3967 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003968 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003969 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003970 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003971 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 } catch (Exception e) {
3973 // todo: Yikes! What should we do? For now we will try to
3974 // start another process, but that could easily get us in
3975 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003976 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977
3978 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003979 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 startProcessLocked(app, "bind fail", processName);
3981 return false;
3982 }
3983
3984 // Remove this record from the list of starting applications.
3985 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003986 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3987 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 mProcessesOnHold.remove(app);
3989
3990 boolean badApp = false;
3991 boolean didSomething = false;
3992
3993 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003995 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003996 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 && processName.equals(hr.processName)) {
3998 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003999 if (mHeadless) {
4000 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4001 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 didSomething = true;
4003 }
4004 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004005 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 + hr.intent.getComponent().flattenToShortString(), e);
4007 badApp = true;
4008 }
4009 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012 }
4013
4014 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004015 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004017 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 badApp = true;
4020 }
4021 }
4022
Christopher Tatef46723b2012-01-26 14:19:24 -08004023 // Check if a next-broadcast receiver is in this process...
4024 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004026 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004028 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 }
4032
Christopher Tate181fafa2009-05-14 11:12:14 -07004033 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004034 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004035 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004036 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004038 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4039 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4040 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004041 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004042 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004043 e.printStackTrace();
4044 }
4045 }
4046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 if (badApp) {
4048 // todo: Also need to kill application to deal with all
4049 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004050 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 return false;
4052 }
4053
4054 if (!didSomething) {
4055 updateOomAdjLocked();
4056 }
4057
4058 return true;
4059 }
4060
4061 public final void attachApplication(IApplicationThread thread) {
4062 synchronized (this) {
4063 int callingPid = Binder.getCallingPid();
4064 final long origId = Binder.clearCallingIdentity();
4065 attachApplicationLocked(thread, callingPid);
4066 Binder.restoreCallingIdentity(origId);
4067 }
4068 }
4069
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004070 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004072 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4073 if (stopProfiling) {
4074 synchronized (this) {
4075 if (mProfileProc == r.app) {
4076 if (mProfileFd != null) {
4077 try {
4078 mProfileFd.close();
4079 } catch (IOException e) {
4080 }
4081 clearProfilerLocked();
4082 }
4083 }
4084 }
4085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 Binder.restoreCallingIdentity(origId);
4087 }
4088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004090 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004091 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004093
4094 synchronized (this) {
4095 updateEventDispatchingLocked();
4096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098
Dianne Hackborn661cd522011-08-22 00:26:20 -07004099 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004100 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004101 mWindowManager.showBootMessage(msg, always);
4102 }
4103
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004104 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004105 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004106 final long token = Binder.clearCallingIdentity();
4107 try {
4108 synchronized (this) {
4109 if (mLockScreenShown) {
4110 mLockScreenShown = false;
4111 comeOutOfSleepIfNeededLocked();
4112 }
4113 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004114 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004115 } finally {
4116 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004117 }
4118 }
4119
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004120 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004121 IntentFilter pkgFilter = new IntentFilter();
4122 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4123 pkgFilter.addDataScheme("package");
4124 mContext.registerReceiver(new BroadcastReceiver() {
4125 @Override
4126 public void onReceive(Context context, Intent intent) {
4127 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4128 if (pkgs != null) {
4129 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004130 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004131 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4132 setResultCode(Activity.RESULT_OK);
4133 return;
4134 }
4135 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004136 }
4137 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004138 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004139 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004140
4141 IntentFilter userFilter = new IntentFilter();
4142 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4143 mContext.registerReceiver(new BroadcastReceiver() {
4144 @Override
4145 public void onReceive(Context context, Intent intent) {
4146 onUserRemoved(intent);
4147 }
4148 }, userFilter);
4149
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004150 synchronized (this) {
4151 // Ensure that any processes we had put on hold are now started
4152 // up.
4153 final int NP = mProcessesOnHold.size();
4154 if (NP > 0) {
4155 ArrayList<ProcessRecord> procs =
4156 new ArrayList<ProcessRecord>(mProcessesOnHold);
4157 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004158 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4159 + procs.get(ip));
4160 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004161 }
4162 }
4163
4164 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004165 // Start looking for apps that are abusing wake locks.
4166 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004167 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004168 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004169 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004170 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004171 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004172 broadcastIntentLocked(null, null,
4173 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4174 null, null, 0, null, null,
4175 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004176 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004177 }
4178 }
4179 }
4180
4181 final void ensureBootCompleted() {
4182 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004183 boolean enableScreen;
4184 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004185 booting = mBooting;
4186 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004187 enableScreen = !mBooted;
4188 mBooted = true;
4189 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004190
4191 if (booting) {
4192 finishBooting();
4193 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004194
4195 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004196 enableScreenAfterBoot();
4197 }
4198 }
4199
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004200 public final void activityPaused(IBinder token) {
4201 final long origId = Binder.clearCallingIdentity();
4202 mMainStack.activityPaused(token, false);
4203 Binder.restoreCallingIdentity(origId);
4204 }
4205
4206 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4207 CharSequence description) {
4208 if (localLOGV) Slog.v(
4209 TAG, "Activity stopped: token=" + token);
4210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 // Refuse possible leaked file descriptors
4212 if (icicle != null && icicle.hasFileDescriptors()) {
4213 throw new IllegalArgumentException("File descriptors passed in Bundle");
4214 }
4215
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004216 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217
4218 final long origId = Binder.clearCallingIdentity();
4219
4220 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004221 r = mMainStack.isInStackLocked(token);
4222 if (r != null) {
4223 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 }
4225 }
4226
4227 if (r != null) {
4228 sendPendingThumbnail(r, null, null, null, false);
4229 }
4230
4231 trimApplications();
4232
4233 Binder.restoreCallingIdentity(origId);
4234 }
4235
4236 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004237 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004238 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
4240
4241 public String getCallingPackage(IBinder token) {
4242 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004243 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004244 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 }
4246 }
4247
4248 public ComponentName getCallingActivity(IBinder token) {
4249 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004250 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 return r != null ? r.intent.getComponent() : null;
4252 }
4253 }
4254
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004255 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004256 ActivityRecord r = mMainStack.isInStackLocked(token);
4257 if (r == null) {
4258 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004260 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262
4263 public ComponentName getActivityClassForToken(IBinder token) {
4264 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004265 ActivityRecord r = mMainStack.isInStackLocked(token);
4266 if (r == null) {
4267 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004269 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 }
4271 }
4272
4273 public String getPackageForToken(IBinder token) {
4274 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004275 ActivityRecord r = mMainStack.isInStackLocked(token);
4276 if (r == null) {
4277 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004279 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 }
4281 }
4282
4283 public IIntentSender getIntentSender(int type,
4284 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004285 int requestCode, Intent[] intents, String[] resolvedTypes,
4286 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004287 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004289 if (intents != null) {
4290 if (intents.length < 1) {
4291 throw new IllegalArgumentException("Intents array length must be >= 1");
4292 }
4293 for (int i=0; i<intents.length; i++) {
4294 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004295 if (intent != null) {
4296 if (intent.hasFileDescriptors()) {
4297 throw new IllegalArgumentException("File descriptors passed in Intent");
4298 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004299 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004300 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4301 throw new IllegalArgumentException(
4302 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4303 }
4304 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004305 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004306 }
4307 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004308 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004309 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004310 }
4311 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004312 if (options != null) {
4313 if (options.hasFileDescriptors()) {
4314 throw new IllegalArgumentException("File descriptors passed in options");
4315 }
4316 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 synchronized(this) {
4319 int callingUid = Binder.getCallingUid();
4320 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004321 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004322 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004323 .getPackageUid(packageName, UserId.getUserId(callingUid));
4324 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 String msg = "Permission Denial: getIntentSender() from pid="
4326 + Binder.getCallingPid()
4327 + ", uid=" + Binder.getCallingUid()
4328 + ", (need uid=" + uid + ")"
4329 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004330 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004331 throw new SecurityException(msg);
4332 }
4333 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004334
Amith Yamasani742a6712011-05-04 14:49:28 -07004335 if (DEBUG_MU)
4336 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4337 + Binder.getOrigCallingUid());
4338 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004339 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 } catch (RemoteException e) {
4342 throw new SecurityException(e);
4343 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004344 }
4345 }
4346
4347 IIntentSender getIntentSenderLocked(int type,
4348 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004349 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4350 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004351 if (DEBUG_MU)
4352 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004353 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004354 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004355 activity = mMainStack.isInStackLocked(token);
4356 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004357 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004359 if (activity.finishing) {
4360 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004362 }
4363
4364 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4365 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4366 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4367 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4368 |PendingIntent.FLAG_UPDATE_CURRENT);
4369
4370 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4371 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004372 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004373 WeakReference<PendingIntentRecord> ref;
4374 ref = mIntentSenderRecords.get(key);
4375 PendingIntentRecord rec = ref != null ? ref.get() : null;
4376 if (rec != null) {
4377 if (!cancelCurrent) {
4378 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004379 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004380 rec.key.requestIntent.replaceExtras(intents != null ?
4381 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004382 }
4383 if (intents != null) {
4384 intents[intents.length-1] = rec.key.requestIntent;
4385 rec.key.allIntents = intents;
4386 rec.key.allResolvedTypes = resolvedTypes;
4387 } else {
4388 rec.key.allIntents = null;
4389 rec.key.allResolvedTypes = null;
4390 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 return rec;
4393 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004394 rec.canceled = true;
4395 mIntentSenderRecords.remove(key);
4396 }
4397 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 return rec;
4399 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004400 rec = new PendingIntentRecord(this, key, callingUid);
4401 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004402 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004403 if (activity.pendingResults == null) {
4404 activity.pendingResults
4405 = new HashSet<WeakReference<PendingIntentRecord>>();
4406 }
4407 activity.pendingResults.add(rec.ref);
4408 }
4409 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 }
4411
4412 public void cancelIntentSender(IIntentSender sender) {
4413 if (!(sender instanceof PendingIntentRecord)) {
4414 return;
4415 }
4416 synchronized(this) {
4417 PendingIntentRecord rec = (PendingIntentRecord)sender;
4418 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004419 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004420 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004421 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 String msg = "Permission Denial: cancelIntentSender() from pid="
4423 + Binder.getCallingPid()
4424 + ", uid=" + Binder.getCallingUid()
4425 + " is not allowed to cancel packges "
4426 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004427 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 throw new SecurityException(msg);
4429 }
4430 } catch (RemoteException e) {
4431 throw new SecurityException(e);
4432 }
4433 cancelIntentSenderLocked(rec, true);
4434 }
4435 }
4436
4437 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4438 rec.canceled = true;
4439 mIntentSenderRecords.remove(rec.key);
4440 if (cleanActivity && rec.key.activity != null) {
4441 rec.key.activity.pendingResults.remove(rec.ref);
4442 }
4443 }
4444
4445 public String getPackageForIntentSender(IIntentSender pendingResult) {
4446 if (!(pendingResult instanceof PendingIntentRecord)) {
4447 return null;
4448 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004449 try {
4450 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4451 return res.key.packageName;
4452 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454 return null;
4455 }
4456
Christopher Tatec4a07d12012-04-06 14:19:13 -07004457 public int getUidForIntentSender(IIntentSender sender) {
4458 if (sender instanceof PendingIntentRecord) {
4459 try {
4460 PendingIntentRecord res = (PendingIntentRecord)sender;
4461 return res.uid;
4462 } catch (ClassCastException e) {
4463 }
4464 }
4465 return -1;
4466 }
4467
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004468 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4469 if (!(pendingResult instanceof PendingIntentRecord)) {
4470 return false;
4471 }
4472 try {
4473 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4474 if (res.key.allIntents == null) {
4475 return false;
4476 }
4477 for (int i=0; i<res.key.allIntents.length; i++) {
4478 Intent intent = res.key.allIntents[i];
4479 if (intent.getPackage() != null && intent.getComponent() != null) {
4480 return false;
4481 }
4482 }
4483 return true;
4484 } catch (ClassCastException e) {
4485 }
4486 return false;
4487 }
4488
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004489 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4490 if (!(pendingResult instanceof PendingIntentRecord)) {
4491 return false;
4492 }
4493 try {
4494 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4495 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4496 return true;
4497 }
4498 return false;
4499 } catch (ClassCastException e) {
4500 }
4501 return false;
4502 }
4503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 public void setProcessLimit(int max) {
4505 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4506 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004507 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004508 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004509 mProcessLimitOverride = max;
4510 }
4511 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
4513
4514 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004515 synchronized (this) {
4516 return mProcessLimitOverride;
4517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 }
4519
4520 void foregroundTokenDied(ForegroundToken token) {
4521 synchronized (ActivityManagerService.this) {
4522 synchronized (mPidsSelfLocked) {
4523 ForegroundToken cur
4524 = mForegroundProcesses.get(token.pid);
4525 if (cur != token) {
4526 return;
4527 }
4528 mForegroundProcesses.remove(token.pid);
4529 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4530 if (pr == null) {
4531 return;
4532 }
4533 pr.forcingToForeground = null;
4534 pr.foregroundServices = false;
4535 }
4536 updateOomAdjLocked();
4537 }
4538 }
4539
4540 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4541 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4542 "setProcessForeground()");
4543 synchronized(this) {
4544 boolean changed = false;
4545
4546 synchronized (mPidsSelfLocked) {
4547 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004548 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 return;
4551 }
4552 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4553 if (oldToken != null) {
4554 oldToken.token.unlinkToDeath(oldToken, 0);
4555 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004556 if (pr != null) {
4557 pr.forcingToForeground = null;
4558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 changed = true;
4560 }
4561 if (isForeground && token != null) {
4562 ForegroundToken newToken = new ForegroundToken() {
4563 public void binderDied() {
4564 foregroundTokenDied(this);
4565 }
4566 };
4567 newToken.pid = pid;
4568 newToken.token = token;
4569 try {
4570 token.linkToDeath(newToken, 0);
4571 mForegroundProcesses.put(pid, newToken);
4572 pr.forcingToForeground = token;
4573 changed = true;
4574 } catch (RemoteException e) {
4575 // If the process died while doing this, we will later
4576 // do the cleanup with the process death link.
4577 }
4578 }
4579 }
4580
4581 if (changed) {
4582 updateOomAdjLocked();
4583 }
4584 }
4585 }
4586
4587 // =========================================================
4588 // PERMISSIONS
4589 // =========================================================
4590
4591 static class PermissionController extends IPermissionController.Stub {
4592 ActivityManagerService mActivityManagerService;
4593 PermissionController(ActivityManagerService activityManagerService) {
4594 mActivityManagerService = activityManagerService;
4595 }
4596
4597 public boolean checkPermission(String permission, int pid, int uid) {
4598 return mActivityManagerService.checkPermission(permission, pid,
4599 uid) == PackageManager.PERMISSION_GRANTED;
4600 }
4601 }
4602
4603 /**
4604 * This can be called with or without the global lock held.
4605 */
4606 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004607 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 // We might be performing an operation on behalf of an indirect binder
4609 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4610 // client identity accordingly before proceeding.
4611 Identity tlsIdentity = sCallerIdentity.get();
4612 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004613 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4615 uid = tlsIdentity.uid;
4616 pid = tlsIdentity.pid;
4617 }
4618
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004619 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 return PackageManager.PERMISSION_GRANTED;
4621 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004622
4623 return ActivityManager.checkComponentPermission(permission, uid,
4624 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
4626
4627 /**
4628 * As the only public entry point for permissions checking, this method
4629 * can enforce the semantic that requesting a check on a null global
4630 * permission is automatically denied. (Internally a null permission
4631 * string is used when calling {@link #checkComponentPermission} in cases
4632 * when only uid-based security is needed.)
4633 *
4634 * This can be called with or without the global lock held.
4635 */
4636 public int checkPermission(String permission, int pid, int uid) {
4637 if (permission == null) {
4638 return PackageManager.PERMISSION_DENIED;
4639 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004640 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 }
4642
4643 /**
4644 * Binder IPC calls go through the public entry point.
4645 * This can be called with or without the global lock held.
4646 */
4647 int checkCallingPermission(String permission) {
4648 return checkPermission(permission,
4649 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004650 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 }
4652
4653 /**
4654 * This can be called with or without the global lock held.
4655 */
4656 void enforceCallingPermission(String permission, String func) {
4657 if (checkCallingPermission(permission)
4658 == PackageManager.PERMISSION_GRANTED) {
4659 return;
4660 }
4661
4662 String msg = "Permission Denial: " + func + " from pid="
4663 + Binder.getCallingPid()
4664 + ", uid=" + Binder.getCallingUid()
4665 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004666 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 throw new SecurityException(msg);
4668 }
4669
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004670 /**
4671 * Determine if UID is holding permissions required to access {@link Uri} in
4672 * the given {@link ProviderInfo}. Final permission checking is always done
4673 * in {@link ContentProvider}.
4674 */
4675 private final boolean checkHoldingPermissionsLocked(
4676 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004677 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4678 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004679
4680 if (pi.applicationInfo.uid == uid) {
4681 return true;
4682 } else if (!pi.exported) {
4683 return false;
4684 }
4685
4686 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4687 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004689 // check if target holds top-level <provider> permissions
4690 if (!readMet && pi.readPermission != null
4691 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4692 readMet = true;
4693 }
4694 if (!writeMet && pi.writePermission != null
4695 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4696 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004698
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 // track if unprotected read/write is allowed; any denied
4700 // <path-permission> below removes this ability
4701 boolean allowDefaultRead = pi.readPermission == null;
4702 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004703
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004704 // check if target holds any <path-permission> that match uri
4705 final PathPermission[] pps = pi.pathPermissions;
4706 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004707 final String path = uri.getPath();
4708 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004709 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004710 i--;
4711 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004712 if (pp.match(path)) {
4713 if (!readMet) {
4714 final String pprperm = pp.getReadPermission();
4715 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4716 + pprperm + " for " + pp.getPath()
4717 + ": match=" + pp.match(path)
4718 + " check=" + pm.checkUidPermission(pprperm, uid));
4719 if (pprperm != null) {
4720 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4721 readMet = true;
4722 } else {
4723 allowDefaultRead = false;
4724 }
4725 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004726 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004727 if (!writeMet) {
4728 final String ppwperm = pp.getWritePermission();
4729 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4730 + ppwperm + " for " + pp.getPath()
4731 + ": match=" + pp.match(path)
4732 + " check=" + pm.checkUidPermission(ppwperm, uid));
4733 if (ppwperm != null) {
4734 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4735 writeMet = true;
4736 } else {
4737 allowDefaultWrite = false;
4738 }
4739 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004740 }
4741 }
4742 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004743 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004744
4745 // grant unprotected <provider> read/write, if not blocked by
4746 // <path-permission> above
4747 if (allowDefaultRead) readMet = true;
4748 if (allowDefaultWrite) writeMet = true;
4749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 } catch (RemoteException e) {
4751 return false;
4752 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004753
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004754 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 }
4756
4757 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4758 int modeFlags) {
4759 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004760 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 return true;
4762 }
4763 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4764 if (perms == null) return false;
4765 UriPermission perm = perms.get(uri);
4766 if (perm == null) return false;
4767 return (modeFlags&perm.modeFlags) == modeFlags;
4768 }
4769
4770 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004771 enforceNotIsolatedCaller("checkUriPermission");
4772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 // Another redirected-binder-call permissions check as in
4774 // {@link checkComponentPermission}.
4775 Identity tlsIdentity = sCallerIdentity.get();
4776 if (tlsIdentity != null) {
4777 uid = tlsIdentity.uid;
4778 pid = tlsIdentity.pid;
4779 }
4780
Amith Yamasani742a6712011-05-04 14:49:28 -07004781 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004782 // Our own process gets to do everything.
4783 if (pid == MY_PID) {
4784 return PackageManager.PERMISSION_GRANTED;
4785 }
4786 synchronized(this) {
4787 return checkUriPermissionLocked(uri, uid, modeFlags)
4788 ? PackageManager.PERMISSION_GRANTED
4789 : PackageManager.PERMISSION_DENIED;
4790 }
4791 }
4792
Dianne Hackborn39792d22010-08-19 18:01:52 -07004793 /**
4794 * Check if the targetPkg can be granted permission to access uri by
4795 * the callingUid using the given modeFlags. Throws a security exception
4796 * if callingUid is not allowed to do this. Returns the uid of the target
4797 * if the URI permission grant should be performed; returns -1 if it is not
4798 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004799 * If you already know the uid of the target, you can supply it in
4800 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004801 */
4802 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004803 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4805 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4806 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004807 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 }
4809
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004810 if (targetPkg != null) {
4811 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4812 "Checking grant " + targetPkg + " permission to " + uri);
4813 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004814
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004815 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816
4817 // If this is not a content: uri, we can't do anything with it.
4818 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004819 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004820 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004821 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 }
4823
4824 String name = uri.getAuthority();
4825 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004826 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4827 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 if (cpr != null) {
4829 pi = cpr.info;
4830 } else {
4831 try {
4832 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004833 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 } catch (RemoteException ex) {
4835 }
4836 }
4837 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004838 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004839 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 }
4841
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004842 int targetUid = lastTargetUid;
4843 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004844 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004845 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004846 if (targetUid < 0) {
4847 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4848 "Can't grant URI permission no uid for: " + targetPkg);
4849 return -1;
4850 }
4851 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004852 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
4855
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004856 if (targetUid >= 0) {
4857 // First... does the target actually need this permission?
4858 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4859 // No need to grant the target this permission.
4860 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4861 "Target " + targetPkg + " already has full permission to " + uri);
4862 return -1;
4863 }
4864 } else {
4865 // First... there is no target package, so can anyone access it?
4866 boolean allowed = pi.exported;
4867 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4868 if (pi.readPermission != null) {
4869 allowed = false;
4870 }
4871 }
4872 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4873 if (pi.writePermission != null) {
4874 allowed = false;
4875 }
4876 }
4877 if (allowed) {
4878 return -1;
4879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 }
4881
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004882 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 if (!pi.grantUriPermissions) {
4884 throw new SecurityException("Provider " + pi.packageName
4885 + "/" + pi.name
4886 + " does not allow granting of Uri permissions (uri "
4887 + uri + ")");
4888 }
4889 if (pi.uriPermissionPatterns != null) {
4890 final int N = pi.uriPermissionPatterns.length;
4891 boolean allowed = false;
4892 for (int i=0; i<N; i++) {
4893 if (pi.uriPermissionPatterns[i] != null
4894 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4895 allowed = true;
4896 break;
4897 }
4898 }
4899 if (!allowed) {
4900 throw new SecurityException("Provider " + pi.packageName
4901 + "/" + pi.name
4902 + " does not allow granting of permission to path of Uri "
4903 + uri);
4904 }
4905 }
4906
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004907 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004909 if (callingUid != Process.myUid()) {
4910 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4911 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4912 throw new SecurityException("Uid " + callingUid
4913 + " does not have permission to uri " + uri);
4914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
4916 }
4917
Dianne Hackborn39792d22010-08-19 18:01:52 -07004918 return targetUid;
4919 }
4920
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004921 public int checkGrantUriPermission(int callingUid, String targetPkg,
4922 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004923 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004924 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004925 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004926 }
4927 }
4928
Dianne Hackborn39792d22010-08-19 18:01:52 -07004929 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4930 Uri uri, int modeFlags, UriPermissionOwner owner) {
4931 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4932 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4933 if (modeFlags == 0) {
4934 return;
4935 }
4936
4937 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 // to the uri, and the target doesn't. Let's now give this to
4939 // the target.
4940
Joe Onorato8a9b2202010-02-26 18:56:32 -08004941 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004942 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 HashMap<Uri, UriPermission> targetUris
4945 = mGrantedUriPermissions.get(targetUid);
4946 if (targetUris == null) {
4947 targetUris = new HashMap<Uri, UriPermission>();
4948 mGrantedUriPermissions.put(targetUid, targetUris);
4949 }
4950
4951 UriPermission perm = targetUris.get(uri);
4952 if (perm == null) {
4953 perm = new UriPermission(targetUid, uri);
4954 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004958 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004959 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004960 } else {
4961 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4962 perm.readOwners.add(owner);
4963 owner.addReadPermission(perm);
4964 }
4965 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4966 perm.writeOwners.add(owner);
4967 owner.addWritePermission(perm);
4968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 }
4970 }
4971
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004972 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4973 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004974 if (targetPkg == null) {
4975 throw new NullPointerException("targetPkg");
4976 }
4977
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004978 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004979 if (targetUid < 0) {
4980 return;
4981 }
4982
4983 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4984 }
4985
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004986 static class NeededUriGrants extends ArrayList<Uri> {
4987 final String targetPkg;
4988 final int targetUid;
4989 final int flags;
4990
4991 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4992 targetPkg = _targetPkg;
4993 targetUid = _targetUid;
4994 flags = _flags;
4995 }
4996 }
4997
Dianne Hackborn39792d22010-08-19 18:01:52 -07004998 /**
4999 * Like checkGrantUriPermissionLocked, but takes an Intent.
5000 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5002 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005003 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005004 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5005 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005006 + " from " + intent + "; flags=0x"
5007 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5008
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005009 if (targetPkg == null) {
5010 throw new NullPointerException("targetPkg");
5011 }
5012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005014 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 }
5016 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005017 ClipData clip = intent.getClipData();
5018 if (data == null && clip == null) {
5019 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005020 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005021 if (data != null) {
5022 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5023 mode, needed != null ? needed.targetUid : -1);
5024 if (target > 0) {
5025 if (needed == null) {
5026 needed = new NeededUriGrants(targetPkg, target, mode);
5027 }
5028 needed.add(data);
5029 }
5030 }
5031 if (clip != null) {
5032 for (int i=0; i<clip.getItemCount(); i++) {
5033 Uri uri = clip.getItemAt(i).getUri();
5034 if (uri != null) {
5035 int target = -1;
5036 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5037 mode, needed != null ? needed.targetUid : -1);
5038 if (target > 0) {
5039 if (needed == null) {
5040 needed = new NeededUriGrants(targetPkg, target, mode);
5041 }
5042 needed.add(uri);
5043 }
5044 } else {
5045 Intent clipIntent = clip.getItemAt(i).getIntent();
5046 if (clipIntent != null) {
5047 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5048 callingUid, targetPkg, clipIntent, mode, needed);
5049 if (newNeeded != null) {
5050 needed = newNeeded;
5051 }
5052 }
5053 }
5054 }
5055 }
5056
5057 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005058 }
5059
5060 /**
5061 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5062 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5064 UriPermissionOwner owner) {
5065 if (needed != null) {
5066 for (int i=0; i<needed.size(); i++) {
5067 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5068 needed.get(i), needed.flags, owner);
5069 }
5070 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005071 }
5072
5073 void grantUriPermissionFromIntentLocked(int callingUid,
5074 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005075 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005076 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005077 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 return;
5079 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005080
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005081 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 }
5083
5084 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5085 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005086 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 synchronized(this) {
5088 final ProcessRecord r = getRecordForAppLocked(caller);
5089 if (r == null) {
5090 throw new SecurityException("Unable to find app for caller "
5091 + caller
5092 + " when granting permission to uri " + uri);
5093 }
5094 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005095 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 }
5097 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005098 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 }
5100
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005101 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 null);
5103 }
5104 }
5105
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005106 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5108 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5109 HashMap<Uri, UriPermission> perms
5110 = mGrantedUriPermissions.get(perm.uid);
5111 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005112 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005113 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 perms.remove(perm.uri);
5115 if (perms.size() == 0) {
5116 mGrantedUriPermissions.remove(perm.uid);
5117 }
5118 }
5119 }
5120 }
5121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5123 int modeFlags) {
5124 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5125 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5126 if (modeFlags == 0) {
5127 return;
5128 }
5129
Joe Onorato8a9b2202010-02-26 18:56:32 -08005130 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005131 "Revoking all granted permissions to " + uri);
5132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005133 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134
5135 final String authority = uri.getAuthority();
5136 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005137 int userId = UserId.getUserId(callingUid);
5138 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 if (cpr != null) {
5140 pi = cpr.info;
5141 } else {
5142 try {
5143 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005144 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 } catch (RemoteException ex) {
5146 }
5147 }
5148 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005149 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 return;
5151 }
5152
5153 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005154 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005155 // Right now, if you are not the original owner of the permission,
5156 // you are not allowed to revoke it.
5157 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5158 throw new SecurityException("Uid " + callingUid
5159 + " does not have permission to uri " + uri);
5160 //}
5161 }
5162
5163 // Go through all of the permissions and remove any that match.
5164 final List<String> SEGMENTS = uri.getPathSegments();
5165 if (SEGMENTS != null) {
5166 final int NS = SEGMENTS.size();
5167 int N = mGrantedUriPermissions.size();
5168 for (int i=0; i<N; i++) {
5169 HashMap<Uri, UriPermission> perms
5170 = mGrantedUriPermissions.valueAt(i);
5171 Iterator<UriPermission> it = perms.values().iterator();
5172 toploop:
5173 while (it.hasNext()) {
5174 UriPermission perm = it.next();
5175 Uri targetUri = perm.uri;
5176 if (!authority.equals(targetUri.getAuthority())) {
5177 continue;
5178 }
5179 List<String> targetSegments = targetUri.getPathSegments();
5180 if (targetSegments == null) {
5181 continue;
5182 }
5183 if (targetSegments.size() < NS) {
5184 continue;
5185 }
5186 for (int j=0; j<NS; j++) {
5187 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5188 continue toploop;
5189 }
5190 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005191 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005192 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 perm.clearModes(modeFlags);
5194 if (perm.modeFlags == 0) {
5195 it.remove();
5196 }
5197 }
5198 if (perms.size() == 0) {
5199 mGrantedUriPermissions.remove(
5200 mGrantedUriPermissions.keyAt(i));
5201 N--;
5202 i--;
5203 }
5204 }
5205 }
5206 }
5207
5208 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5209 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005210 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 synchronized(this) {
5212 final ProcessRecord r = getRecordForAppLocked(caller);
5213 if (r == null) {
5214 throw new SecurityException("Unable to find app for caller "
5215 + caller
5216 + " when revoking permission to uri " + uri);
5217 }
5218 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005219 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 return;
5221 }
5222
5223 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5224 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5225 if (modeFlags == 0) {
5226 return;
5227 }
5228
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005229 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230
5231 final String authority = uri.getAuthority();
5232 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005233 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 if (cpr != null) {
5235 pi = cpr.info;
5236 } else {
5237 try {
5238 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005239 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 } catch (RemoteException ex) {
5241 }
5242 }
5243 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005244 Slog.w(TAG, "No content provider found for permission revoke: "
5245 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 return;
5247 }
5248
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005249 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 }
5251 }
5252
Dianne Hackborn7e269642010-08-25 19:50:20 -07005253 @Override
5254 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005255 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005256 synchronized(this) {
5257 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5258 return owner.getExternalTokenLocked();
5259 }
5260 }
5261
5262 @Override
5263 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5264 Uri uri, int modeFlags) {
5265 synchronized(this) {
5266 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5267 if (owner == null) {
5268 throw new IllegalArgumentException("Unknown owner: " + token);
5269 }
5270 if (fromUid != Binder.getCallingUid()) {
5271 if (Binder.getCallingUid() != Process.myUid()) {
5272 // Only system code can grant URI permissions on behalf
5273 // of other users.
5274 throw new SecurityException("nice try");
5275 }
5276 }
5277 if (targetPkg == null) {
5278 throw new IllegalArgumentException("null target");
5279 }
5280 if (uri == null) {
5281 throw new IllegalArgumentException("null uri");
5282 }
5283
5284 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5285 }
5286 }
5287
5288 @Override
5289 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5290 synchronized(this) {
5291 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5292 if (owner == null) {
5293 throw new IllegalArgumentException("Unknown owner: " + token);
5294 }
5295
5296 if (uri == null) {
5297 owner.removeUriPermissionsLocked(mode);
5298 } else {
5299 owner.removeUriPermissionLocked(uri, mode);
5300 }
5301 }
5302 }
5303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5305 synchronized (this) {
5306 ProcessRecord app =
5307 who != null ? getRecordForAppLocked(who) : null;
5308 if (app == null) return;
5309
5310 Message msg = Message.obtain();
5311 msg.what = WAIT_FOR_DEBUGGER_MSG;
5312 msg.obj = app;
5313 msg.arg1 = waiting ? 1 : 0;
5314 mHandler.sendMessage(msg);
5315 }
5316 }
5317
5318 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005319 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5320 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005322 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005323 outInfo.threshold = homeAppMem;
5324 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5325 outInfo.hiddenAppThreshold = hiddenAppMem;
5326 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005327 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005328 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5329 ProcessList.VISIBLE_APP_ADJ);
5330 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5331 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333
5334 // =========================================================
5335 // TASK MANAGEMENT
5336 // =========================================================
5337
5338 public List getTasks(int maxNum, int flags,
5339 IThumbnailReceiver receiver) {
5340 ArrayList list = new ArrayList();
5341
5342 PendingThumbnailsRecord pending = null;
5343 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005344 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345
5346 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005347 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5349 + ", receiver=" + receiver);
5350
5351 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5352 != PackageManager.PERMISSION_GRANTED) {
5353 if (receiver != null) {
5354 // If the caller wants to wait for pending thumbnails,
5355 // it ain't gonna get them.
5356 try {
5357 receiver.finished();
5358 } catch (RemoteException ex) {
5359 }
5360 }
5361 String msg = "Permission Denial: getTasks() from pid="
5362 + Binder.getCallingPid()
5363 + ", uid=" + Binder.getCallingUid()
5364 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005365 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 throw new SecurityException(msg);
5367 }
5368
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005369 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005370 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005371 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005372 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 TaskRecord curTask = null;
5374 int numActivities = 0;
5375 int numRunning = 0;
5376 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005377 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005379 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380
5381 // Initialize state for next task if needed.
5382 if (top == null ||
5383 (top.state == ActivityState.INITIALIZING
5384 && top.task == r.task)) {
5385 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 curTask = r.task;
5387 numActivities = numRunning = 0;
5388 }
5389
5390 // Add 'r' into the current task.
5391 numActivities++;
5392 if (r.app != null && r.app.thread != null) {
5393 numRunning++;
5394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395
Joe Onorato8a9b2202010-02-26 18:56:32 -08005396 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 TAG, r.intent.getComponent().flattenToShortString()
5398 + ": task=" + r.task);
5399
5400 // If the next one is a different task, generate a new
5401 // TaskInfo entry for what we have.
5402 if (next == null || next.task != curTask) {
5403 ActivityManager.RunningTaskInfo ci
5404 = new ActivityManager.RunningTaskInfo();
5405 ci.id = curTask.taskId;
5406 ci.baseActivity = r.intent.getComponent();
5407 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005408 if (top.thumbHolder != null) {
5409 ci.description = top.thumbHolder.lastDescription;
5410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 ci.numActivities = numActivities;
5412 ci.numRunning = numRunning;
5413 //System.out.println(
5414 // "#" + maxNum + ": " + " descr=" + ci.description);
5415 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005416 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 TAG, "State=" + top.state + "Idle=" + top.idle
5418 + " app=" + top.app
5419 + " thr=" + (top.app != null ? top.app.thread : null));
5420 if (top.state == ActivityState.RESUMED
5421 || top.state == ActivityState.PAUSING) {
5422 if (top.idle && top.app != null
5423 && top.app.thread != null) {
5424 topRecord = top;
5425 topThumbnail = top.app.thread;
5426 } else {
5427 top.thumbnailNeeded = true;
5428 }
5429 }
5430 if (pending == null) {
5431 pending = new PendingThumbnailsRecord(receiver);
5432 }
5433 pending.pendingRecords.add(top);
5434 }
5435 list.add(ci);
5436 maxNum--;
5437 top = null;
5438 }
5439 }
5440
5441 if (pending != null) {
5442 mPendingThumbnails.add(pending);
5443 }
5444 }
5445
Joe Onorato8a9b2202010-02-26 18:56:32 -08005446 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447
5448 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005449 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005451 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005453 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005454 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 }
5456 }
5457
5458 if (pending == null && receiver != null) {
5459 // In this case all thumbnails were available and the client
5460 // is being asked to be told when the remaining ones come in...
5461 // which is unusually, since the top-most currently running
5462 // activity should never have a canned thumbnail! Oh well.
5463 try {
5464 receiver.finished();
5465 } catch (RemoteException ex) {
5466 }
5467 }
5468
5469 return list;
5470 }
5471
5472 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5473 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005474 final int callingUid = Binder.getCallingUid();
5475 // If it's the system uid asking, then use the current user id.
5476 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5477 // require the entire list.
5478 final int callingUserId = callingUid == Process.SYSTEM_UID
5479 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 synchronized (this) {
5481 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5482 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005483 final boolean detailed = checkCallingPermission(
5484 android.Manifest.permission.GET_DETAILED_TASKS)
5485 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005487 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 final int N = mRecentTasks.size();
5490 ArrayList<ActivityManager.RecentTaskInfo> res
5491 = new ArrayList<ActivityManager.RecentTaskInfo>(
5492 maxNum < N ? maxNum : N);
5493 for (int i=0; i<N && maxNum > 0; i++) {
5494 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005495 // Only add calling user's recent tasks
5496 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005497 // Return the entry if desired by the caller. We always return
5498 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005499 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005500 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5501 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005502
Dianne Hackborn905577f2011-09-07 18:31:28 -07005503 if (i == 0
5504 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 || (tr.intent == null)
5506 || ((tr.intent.getFlags()
5507 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5508 ActivityManager.RecentTaskInfo rti
5509 = new ActivityManager.RecentTaskInfo();
5510 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005511 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 rti.baseIntent = new Intent(
5513 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005514 if (!detailed) {
5515 rti.baseIntent.replaceExtras((Bundle)null);
5516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005518 rti.description = tr.lastDescription;
5519
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005520 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5521 // Check whether this activity is currently available.
5522 try {
5523 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005524 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5525 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005526 continue;
5527 }
5528 } else if (rti.baseIntent != null) {
5529 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005530 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005531 continue;
5532 }
5533 }
5534 } catch (RemoteException e) {
5535 // Will never happen.
5536 }
5537 }
5538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 res.add(rti);
5540 maxNum--;
5541 }
5542 }
5543 return res;
5544 }
5545 }
5546
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005547 private TaskRecord taskForIdLocked(int id) {
5548 final int N = mRecentTasks.size();
5549 for (int i=0; i<N; i++) {
5550 TaskRecord tr = mRecentTasks.get(i);
5551 if (tr.taskId == id) {
5552 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005553 }
5554 }
5555 return null;
5556 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005557
5558 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5559 synchronized (this) {
5560 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5561 "getTaskThumbnails()");
5562 TaskRecord tr = taskForIdLocked(id);
5563 if (tr != null) {
5564 return mMainStack.getTaskThumbnailsLocked(tr);
5565 }
5566 }
5567 return null;
5568 }
5569
5570 public boolean removeSubTask(int taskId, int subTaskIndex) {
5571 synchronized (this) {
5572 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5573 "removeSubTask()");
5574 long ident = Binder.clearCallingIdentity();
5575 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005576 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5577 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005578 } finally {
5579 Binder.restoreCallingIdentity(ident);
5580 }
5581 }
5582 }
5583
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005584 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5585 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005586 Intent baseIntent = new Intent(
5587 tr.intent != null ? tr.intent : tr.affinityIntent);
5588 ComponentName component = baseIntent.getComponent();
5589 if (component == null) {
5590 Slog.w(TAG, "Now component for base intent of task: " + tr);
5591 return;
5592 }
5593
5594 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005595 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005596
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005597 if (killProcesses) {
5598 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005599 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005600 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005601 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5602 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5603 for (int i=0; i<uids.size(); i++) {
5604 ProcessRecord proc = uids.valueAt(i);
5605 if (proc.userId != tr.userId) {
5606 continue;
5607 }
5608 if (!proc.pkgList.contains(pkg)) {
5609 continue;
5610 }
5611 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005612 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005613 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005614
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005615 // Kill the running processes.
5616 for (int i=0; i<procs.size(); i++) {
5617 ProcessRecord pr = procs.get(i);
5618 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5619 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5620 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5621 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005622 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005623 Process.killProcessQuiet(pr.pid);
5624 } else {
5625 pr.waitingToKill = "remove task";
5626 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005627 }
5628 }
5629 }
5630
5631 public boolean removeTask(int taskId, int flags) {
5632 synchronized (this) {
5633 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5634 "removeTask()");
5635 long ident = Binder.clearCallingIdentity();
5636 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005637 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5638 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005639 if (r != null) {
5640 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005641 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005642 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005643 } else {
5644 TaskRecord tr = null;
5645 int i=0;
5646 while (i < mRecentTasks.size()) {
5647 TaskRecord t = mRecentTasks.get(i);
5648 if (t.taskId == taskId) {
5649 tr = t;
5650 break;
5651 }
5652 i++;
5653 }
5654 if (tr != null) {
5655 if (tr.numActivities <= 0) {
5656 // Caller is just removing a recent task that is
5657 // not actively running. That is easy!
5658 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005659 cleanUpRemovedTaskLocked(tr, flags);
5660 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005661 } else {
5662 Slog.w(TAG, "removeTask: task " + taskId
5663 + " does not have activities to remove, "
5664 + " but numActivities=" + tr.numActivities
5665 + ": " + tr);
5666 }
5667 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005668 }
5669 } finally {
5670 Binder.restoreCallingIdentity(ident);
5671 }
5672 }
5673 return false;
5674 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5677 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005678 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 TaskRecord jt = startTask;
5680
5681 // First look backwards
5682 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005683 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 if (r.task != jt) {
5685 jt = r.task;
5686 if (affinity.equals(jt.affinity)) {
5687 return j;
5688 }
5689 }
5690 }
5691
5692 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005693 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 jt = startTask;
5695 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005696 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 if (r.task != jt) {
5698 if (affinity.equals(jt.affinity)) {
5699 return j;
5700 }
5701 jt = r.task;
5702 }
5703 }
5704
5705 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005706 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 return N-1;
5708 }
5709
5710 return -1;
5711 }
5712
5713 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005714 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005716 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5718 "moveTaskToFront()");
5719
5720 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005721 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5722 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005723 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005724 return;
5725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 final long origId = Binder.clearCallingIdentity();
5727 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005728 TaskRecord tr = taskForIdLocked(task);
5729 if (tr != null) {
5730 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5731 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005733 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5734 // Caller wants the home activity moved with it. To accomplish this,
5735 // we'll just move the home task to the top first.
5736 mMainStack.moveHomeToFrontLocked();
5737 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005738 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005739 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005741 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5742 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005744 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5745 mMainStack.mUserLeaving = true;
5746 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005747 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5748 // Caller wants the home activity moved with it. To accomplish this,
5749 // we'll just move the home task to the top first.
5750 mMainStack.moveHomeToFrontLocked();
5751 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005752 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 return;
5754 }
5755 }
5756 } finally {
5757 Binder.restoreCallingIdentity(origId);
5758 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005759 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 }
5761 }
5762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 public void moveTaskToBack(int task) {
5764 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5765 "moveTaskToBack()");
5766
5767 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005768 if (mMainStack.mResumedActivity != null
5769 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005770 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5771 Binder.getCallingUid(), "Task to back")) {
5772 return;
5773 }
5774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005776 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 Binder.restoreCallingIdentity(origId);
5778 }
5779 }
5780
5781 /**
5782 * Moves an activity, and all of the other activities within the same task, to the bottom
5783 * of the history stack. The activity's order within the task is unchanged.
5784 *
5785 * @param token A reference to the activity we wish to move
5786 * @param nonRoot If false then this only works if the activity is the root
5787 * of a task; if true it will work for any activity in a task.
5788 * @return Returns true if the move completed, false if not.
5789 */
5790 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005791 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 synchronized(this) {
5793 final long origId = Binder.clearCallingIdentity();
5794 int taskId = getTaskForActivityLocked(token, !nonRoot);
5795 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005796 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 }
5798 Binder.restoreCallingIdentity(origId);
5799 }
5800 return false;
5801 }
5802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 public void moveTaskBackwards(int task) {
5804 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5805 "moveTaskBackwards()");
5806
5807 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005808 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5809 Binder.getCallingUid(), "Task backwards")) {
5810 return;
5811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 final long origId = Binder.clearCallingIdentity();
5813 moveTaskBackwardsLocked(task);
5814 Binder.restoreCallingIdentity(origId);
5815 }
5816 }
5817
5818 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005819 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 }
5821
5822 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5823 synchronized(this) {
5824 return getTaskForActivityLocked(token, onlyRoot);
5825 }
5826 }
5827
5828 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005829 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 TaskRecord lastTask = null;
5831 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005832 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005833 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 if (!onlyRoot || lastTask != r.task) {
5835 return r.task.taskId;
5836 }
5837 return -1;
5838 }
5839 lastTask = r.task;
5840 }
5841
5842 return -1;
5843 }
5844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 // =========================================================
5846 // THUMBNAILS
5847 // =========================================================
5848
5849 public void reportThumbnail(IBinder token,
5850 Bitmap thumbnail, CharSequence description) {
5851 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5852 final long origId = Binder.clearCallingIdentity();
5853 sendPendingThumbnail(null, token, thumbnail, description, true);
5854 Binder.restoreCallingIdentity(origId);
5855 }
5856
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005857 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 Bitmap thumbnail, CharSequence description, boolean always) {
5859 TaskRecord task = null;
5860 ArrayList receivers = null;
5861
5862 //System.out.println("Send pending thumbnail: " + r);
5863
5864 synchronized(this) {
5865 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005866 r = mMainStack.isInStackLocked(token);
5867 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 return;
5869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005871 if (thumbnail == null && r.thumbHolder != null) {
5872 thumbnail = r.thumbHolder.lastThumbnail;
5873 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875 if (thumbnail == null && !always) {
5876 // If there is no thumbnail, and this entry is not actually
5877 // going away, then abort for now and pick up the next
5878 // thumbnail we get.
5879 return;
5880 }
5881 task = r.task;
5882
5883 int N = mPendingThumbnails.size();
5884 int i=0;
5885 while (i<N) {
5886 PendingThumbnailsRecord pr =
5887 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5888 //System.out.println("Looking in " + pr.pendingRecords);
5889 if (pr.pendingRecords.remove(r)) {
5890 if (receivers == null) {
5891 receivers = new ArrayList();
5892 }
5893 receivers.add(pr);
5894 if (pr.pendingRecords.size() == 0) {
5895 pr.finished = true;
5896 mPendingThumbnails.remove(i);
5897 N--;
5898 continue;
5899 }
5900 }
5901 i++;
5902 }
5903 }
5904
5905 if (receivers != null) {
5906 final int N = receivers.size();
5907 for (int i=0; i<N; i++) {
5908 try {
5909 PendingThumbnailsRecord pr =
5910 (PendingThumbnailsRecord)receivers.get(i);
5911 pr.receiver.newThumbnail(
5912 task != null ? task.taskId : -1, thumbnail, description);
5913 if (pr.finished) {
5914 pr.receiver.finished();
5915 }
5916 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005917 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 }
5919 }
5920 }
5921 }
5922
5923 // =========================================================
5924 // CONTENT PROVIDERS
5925 // =========================================================
5926
Jeff Brown10e89712011-07-08 18:52:57 -07005927 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5928 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005930 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005931 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005932 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 } catch (RemoteException ex) {
5934 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005935 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005936 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5937 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 if (providers != null) {
5939 final int N = providers.size();
5940 for (int i=0; i<N; i++) {
5941 ProviderInfo cpi =
5942 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005943
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005944 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005945 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005947 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005948 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005950 if (DEBUG_MU)
5951 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 app.pubProviders.put(cpi.name, cpr);
5953 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005954 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 }
5956 }
5957 return providers;
5958 }
5959
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005960 /**
5961 * Check if {@link ProcessRecord} has a possible chance at accessing the
5962 * given {@link ProviderInfo}. Final permission checking is always done
5963 * in {@link ContentProvider}.
5964 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005966 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005968 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005970 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005971 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 return null;
5973 }
5974 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005975 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 == PackageManager.PERMISSION_GRANTED) {
5977 return null;
5978 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005979
5980 PathPermission[] pps = cpi.pathPermissions;
5981 if (pps != null) {
5982 int i = pps.length;
5983 while (i > 0) {
5984 i--;
5985 PathPermission pp = pps[i];
5986 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005987 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005988 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005989 return null;
5990 }
5991 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005992 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005993 == PackageManager.PERMISSION_GRANTED) {
5994 return null;
5995 }
5996 }
5997 }
5998
Dianne Hackbornb424b632010-08-18 15:59:05 -07005999 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6000 if (perms != null) {
6001 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6002 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6003 return null;
6004 }
6005 }
6006 }
6007
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006008 String msg;
6009 if (!cpi.exported) {
6010 msg = "Permission Denial: opening provider " + cpi.name
6011 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6012 + ", uid=" + callingUid + ") that is not exported from uid "
6013 + cpi.applicationInfo.uid;
6014 } else {
6015 msg = "Permission Denial: opening provider " + cpi.name
6016 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6017 + ", uid=" + callingUid + ") requires "
6018 + cpi.readPermission + " or " + cpi.writePermission;
6019 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006020 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 return msg;
6022 }
6023
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006024 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6025 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006026 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006027 for (int i=0; i<r.conProviders.size(); i++) {
6028 ContentProviderConnection conn = r.conProviders.get(i);
6029 if (conn.provider == cpr) {
6030 if (DEBUG_PROVIDER) Slog.v(TAG,
6031 "Adding provider requested by "
6032 + r.processName + " from process "
6033 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6034 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6035 if (stable) {
6036 conn.stableCount++;
6037 conn.numStableIncs++;
6038 } else {
6039 conn.unstableCount++;
6040 conn.numUnstableIncs++;
6041 }
6042 return conn;
6043 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006044 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006045 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6046 if (stable) {
6047 conn.stableCount = 1;
6048 conn.numStableIncs = 1;
6049 } else {
6050 conn.unstableCount = 1;
6051 conn.numUnstableIncs = 1;
6052 }
6053 cpr.connections.add(conn);
6054 r.conProviders.add(conn);
6055 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006056 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006057 cpr.addExternalProcessHandleLocked(externalProcessToken);
6058 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006059 }
6060
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006061 boolean decProviderCountLocked(ContentProviderConnection conn,
6062 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6063 if (conn != null) {
6064 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006065 if (DEBUG_PROVIDER) Slog.v(TAG,
6066 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006067 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006068 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006069 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6070 if (stable) {
6071 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006072 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006073 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006074 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006075 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6076 cpr.connections.remove(conn);
6077 conn.client.conProviders.remove(conn);
6078 return true;
6079 }
6080 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006081 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006082 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006083 return false;
6084 }
6085
Amith Yamasani742a6712011-05-04 14:49:28 -07006086 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006087 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006089 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 ProviderInfo cpi = null;
6091
6092 synchronized(this) {
6093 ProcessRecord r = null;
6094 if (caller != null) {
6095 r = getRecordForAppLocked(caller);
6096 if (r == null) {
6097 throw new SecurityException(
6098 "Unable to find app for caller " + caller
6099 + " (pid=" + Binder.getCallingPid()
6100 + ") when getting content provider " + name);
6101 }
6102 }
6103
6104 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006105 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006106 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006107 boolean providerRunning = cpr != null;
6108 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006110 String msg;
6111 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6112 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 }
6114
6115 if (r != null && cpr.canRunHere(r)) {
6116 // This provider has been published or is in the process
6117 // of being published... but it is also allowed to run
6118 // in the caller's process, so don't make a connection
6119 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006120 ContentProviderHolder holder = cpr.newHolder(null);
6121 // don't give caller the provider object, it needs
6122 // to make its own.
6123 holder.provider = null;
6124 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
6126
6127 final long origId = Binder.clearCallingIdentity();
6128
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006129 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006131 conn = incProviderCountLocked(r, cpr, token, stable);
6132 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006133 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006134 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006135 // make sure to count it as being accessed and thus
6136 // back up on the LRU list. This is good because
6137 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006138 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006139 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006140 }
6141
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006142 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 if (false) {
6144 if (cpr.name.flattenToShortString().equals(
6145 "com.android.providers.calendar/.CalendarProvider2")) {
6146 Slog.v(TAG, "****************** KILLING "
6147 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006148 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006149 }
6150 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006151 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006152 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6153 // NOTE: there is still a race here where a signal could be
6154 // pending on the process even though we managed to update its
6155 // adj level. Not sure what to do about this, but at least
6156 // the race is now smaller.
6157 if (!success) {
6158 // Uh oh... it looks like the provider's process
6159 // has been killed on us. We need to wait for a new
6160 // process to be started, and make sure its death
6161 // doesn't kill our process.
6162 Slog.i(TAG,
6163 "Existing provider " + cpr.name.flattenToShortString()
6164 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006166 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006167 if (!lastRef) {
6168 // This wasn't the last ref our process had on
6169 // the provider... we have now been killed, bail.
6170 return null;
6171 }
6172 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006173 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 }
6176
6177 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006180 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006182 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006183 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006184 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 } catch (RemoteException ex) {
6186 }
6187 if (cpi == null) {
6188 return null;
6189 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006190 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6191 userId = 0;
6192 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006193 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006194
Dianne Hackbornb424b632010-08-18 15:59:05 -07006195 String msg;
6196 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6197 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 }
6199
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006200 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006201 && !cpi.processName.equals("system")) {
6202 // If this content provider does not run in the system
6203 // process, and the system is not yet ready to run other
6204 // processes, then fail fast instead of hanging.
6205 throw new IllegalArgumentException(
6206 "Attempt to launch content provider before system ready");
6207 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006208
6209 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006210 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 final boolean firstClass = cpr == null;
6212 if (firstClass) {
6213 try {
6214 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006215 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 getApplicationInfo(
6217 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006218 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006220 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 + cpi.name);
6222 return null;
6223 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006224 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006225 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 } catch (RemoteException ex) {
6227 // pm is in same process, this will never happen.
6228 }
6229 }
6230
6231 if (r != null && cpr.canRunHere(r)) {
6232 // If this is a multiprocess provider, then just return its
6233 // info and allow the caller to instantiate it. Only do
6234 // this if the provider is the same user as the caller's
6235 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006236 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 }
6238
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006239 if (DEBUG_PROVIDER) {
6240 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006241 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006242 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
6244
6245 // This is single process, and our app is now connecting to it.
6246 // See if we are already in the process of launching this
6247 // provider.
6248 final int N = mLaunchingProviders.size();
6249 int i;
6250 for (i=0; i<N; i++) {
6251 if (mLaunchingProviders.get(i) == cpr) {
6252 break;
6253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
6255
6256 // If the provider is not already being launched, then get it
6257 // started.
6258 if (i >= N) {
6259 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006260
6261 try {
6262 // Content provider is now in use, its package can't be stopped.
6263 try {
6264 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006265 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006266 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006267 } catch (IllegalArgumentException e) {
6268 Slog.w(TAG, "Failed trying to unstop package "
6269 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006270 }
6271
6272 ProcessRecord proc = startProcessLocked(cpi.processName,
6273 cpr.appInfo, false, 0, "content provider",
6274 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006275 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006276 if (proc == null) {
6277 Slog.w(TAG, "Unable to launch app "
6278 + cpi.applicationInfo.packageName + "/"
6279 + cpi.applicationInfo.uid + " for provider "
6280 + name + ": process is bad");
6281 return null;
6282 }
6283 cpr.launchingApp = proc;
6284 mLaunchingProviders.add(cpr);
6285 } finally {
6286 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
6290 // Make sure the provider is published (the same provider class
6291 // may be published under multiple names).
6292 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006293 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006295
Amith Yamasani742a6712011-05-04 14:49:28 -07006296 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006297 conn = incProviderCountLocked(r, cpr, token, stable);
6298 if (conn != null) {
6299 conn.waiting = true;
6300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 }
6302 }
6303
6304 // Wait for the provider to be published...
6305 synchronized (cpr) {
6306 while (cpr.provider == null) {
6307 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006308 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 + cpi.applicationInfo.packageName + "/"
6310 + cpi.applicationInfo.uid + " for provider "
6311 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006312 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 cpi.applicationInfo.packageName,
6314 cpi.applicationInfo.uid, name);
6315 return null;
6316 }
6317 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006318 if (DEBUG_MU) {
6319 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6320 + cpr.launchingApp);
6321 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 if (conn != null) {
6323 conn.waiting = true;
6324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 cpr.wait();
6326 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006327 } finally {
6328 if (conn != null) {
6329 conn.waiting = false;
6330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 }
6332 }
6333 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006334 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 }
6336
6337 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006338 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006339 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 if (caller == null) {
6341 String msg = "null IApplicationThread when getting content provider "
6342 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006343 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 throw new SecurityException(msg);
6345 }
6346
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006347 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006350 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6351 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6352 "Do not have permission in call getContentProviderExternal()");
6353 return getContentProviderExternalUnchecked(name, token);
6354 }
6355
6356 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006357 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359
6360 /**
6361 * Drop a content provider from a ProcessRecord's bookkeeping
6362 * @param cpr
6363 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006364 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006365 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006367 ContentProviderConnection conn;
6368 try {
6369 conn = (ContentProviderConnection)connection;
6370 } catch (ClassCastException e) {
6371 String msg ="removeContentProvider: " + connection
6372 + " not a ContentProviderConnection";
6373 Slog.w(TAG, msg);
6374 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006376 if (conn == null) {
6377 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006379 if (decProviderCountLocked(conn, null, null, stable)) {
6380 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 }
6383 }
6384
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006385 public void removeContentProviderExternal(String name, IBinder token) {
6386 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6387 "Do not have permission in call removeContentProviderExternal()");
6388 removeContentProviderExternalUnchecked(name, token);
6389 }
6390
6391 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006393 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6394 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 if(cpr == null) {
6396 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006397 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return;
6399 }
6400
6401 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006402 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006403 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6404 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006405 if (localCpr.hasExternalProcessHandles()) {
6406 if (localCpr.removeExternalProcessHandleLocked(token)) {
6407 updateOomAdjLocked();
6408 } else {
6409 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6410 + " with no external reference for token: "
6411 + token + ".");
6412 }
6413 } else {
6414 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6415 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 }
6418 }
6419
6420 public final void publishContentProviders(IApplicationThread caller,
6421 List<ContentProviderHolder> providers) {
6422 if (providers == null) {
6423 return;
6424 }
6425
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006426 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006427 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006429 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006430 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 if (r == null) {
6432 throw new SecurityException(
6433 "Unable to find app for caller " + caller
6434 + " (pid=" + Binder.getCallingPid()
6435 + ") when publishing content providers");
6436 }
6437
6438 final long origId = Binder.clearCallingIdentity();
6439
6440 final int N = providers.size();
6441 for (int i=0; i<N; i++) {
6442 ContentProviderHolder src = providers.get(i);
6443 if (src == null || src.info == null || src.provider == null) {
6444 continue;
6445 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006446 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006447 if (DEBUG_MU)
6448 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006450 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006451 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 String names[] = dst.info.authority.split(";");
6453 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006454 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 }
6456
6457 int NL = mLaunchingProviders.size();
6458 int j;
6459 for (j=0; j<NL; j++) {
6460 if (mLaunchingProviders.get(j) == dst) {
6461 mLaunchingProviders.remove(j);
6462 j--;
6463 NL--;
6464 }
6465 }
6466 synchronized (dst) {
6467 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006468 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 dst.notifyAll();
6470 }
6471 updateOomAdjLocked(r);
6472 }
6473 }
6474
6475 Binder.restoreCallingIdentity(origId);
6476 }
6477 }
6478
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006479 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6480 ContentProviderConnection conn;
6481 try {
6482 conn = (ContentProviderConnection)connection;
6483 } catch (ClassCastException e) {
6484 String msg ="refContentProvider: " + connection
6485 + " not a ContentProviderConnection";
6486 Slog.w(TAG, msg);
6487 throw new IllegalArgumentException(msg);
6488 }
6489 if (conn == null) {
6490 throw new NullPointerException("connection is null");
6491 }
6492
6493 synchronized (this) {
6494 if (stable > 0) {
6495 conn.numStableIncs += stable;
6496 }
6497 stable = conn.stableCount + stable;
6498 if (stable < 0) {
6499 throw new IllegalStateException("stableCount < 0: " + stable);
6500 }
6501
6502 if (unstable > 0) {
6503 conn.numUnstableIncs += unstable;
6504 }
6505 unstable = conn.unstableCount + unstable;
6506 if (unstable < 0) {
6507 throw new IllegalStateException("unstableCount < 0: " + unstable);
6508 }
6509
6510 if ((stable+unstable) <= 0) {
6511 throw new IllegalStateException("ref counts can't go to zero here: stable="
6512 + stable + " unstable=" + unstable);
6513 }
6514 conn.stableCount = stable;
6515 conn.unstableCount = unstable;
6516 return !conn.dead;
6517 }
6518 }
6519
6520 public void unstableProviderDied(IBinder connection) {
6521 ContentProviderConnection conn;
6522 try {
6523 conn = (ContentProviderConnection)connection;
6524 } catch (ClassCastException e) {
6525 String msg ="refContentProvider: " + connection
6526 + " not a ContentProviderConnection";
6527 Slog.w(TAG, msg);
6528 throw new IllegalArgumentException(msg);
6529 }
6530 if (conn == null) {
6531 throw new NullPointerException("connection is null");
6532 }
6533
6534 // Safely retrieve the content provider associated with the connection.
6535 IContentProvider provider;
6536 synchronized (this) {
6537 provider = conn.provider.provider;
6538 }
6539
6540 if (provider == null) {
6541 // Um, yeah, we're way ahead of you.
6542 return;
6543 }
6544
6545 // Make sure the caller is being honest with us.
6546 if (provider.asBinder().pingBinder()) {
6547 // Er, no, still looks good to us.
6548 synchronized (this) {
6549 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6550 + " says " + conn + " died, but we don't agree");
6551 return;
6552 }
6553 }
6554
6555 // Well look at that! It's dead!
6556 synchronized (this) {
6557 if (conn.provider.provider != provider) {
6558 // But something changed... good enough.
6559 return;
6560 }
6561
6562 ProcessRecord proc = conn.provider.proc;
6563 if (proc == null || proc.thread == null) {
6564 // Seems like the process is already cleaned up.
6565 return;
6566 }
6567
6568 // As far as we're concerned, this is just like receiving a
6569 // death notification... just a bit prematurely.
6570 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6571 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006572 final long ident = Binder.clearCallingIdentity();
6573 try {
6574 appDiedLocked(proc, proc.pid, proc.thread);
6575 } finally {
6576 Binder.restoreCallingIdentity(ident);
6577 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006578 }
6579 }
6580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006582 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006583 synchronized (mSelf) {
6584 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6585 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006586 if (providers != null) {
6587 for (int i=providers.size()-1; i>=0; i--) {
6588 ProviderInfo pi = (ProviderInfo)providers.get(i);
6589 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6590 Slog.w(TAG, "Not installing system proc provider " + pi.name
6591 + ": not system .apk");
6592 providers.remove(i);
6593 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006594 }
6595 }
6596 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006597 if (providers != null) {
6598 mSystemThread.installSystemProviders(providers);
6599 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006600
6601 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006602
6603 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006606 /**
6607 * Allows app to retrieve the MIME type of a URI without having permission
6608 * to access its content provider.
6609 *
6610 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6611 *
6612 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6613 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6614 */
6615 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006616 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006617 final String name = uri.getAuthority();
6618 final long ident = Binder.clearCallingIdentity();
6619 ContentProviderHolder holder = null;
6620
6621 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006622 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006623 if (holder != null) {
6624 return holder.provider.getType(uri);
6625 }
6626 } catch (RemoteException e) {
6627 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6628 return null;
6629 } finally {
6630 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006631 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006632 }
6633 Binder.restoreCallingIdentity(ident);
6634 }
6635
6636 return null;
6637 }
6638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 // =========================================================
6640 // GLOBAL MANAGEMENT
6641 // =========================================================
6642
6643 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006644 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 String proc = customProcess != null ? customProcess : info.processName;
6646 BatteryStatsImpl.Uid.Proc ps = null;
6647 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006648 int uid = info.uid;
6649 if (isolated) {
6650 int userId = UserId.getUserId(uid);
6651 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6652 uid = 0;
6653 while (true) {
6654 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6655 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6656 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6657 }
6658 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6659 mNextIsolatedProcessUid++;
6660 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6661 // No process for this uid, use it.
6662 break;
6663 }
6664 stepsLeft--;
6665 if (stepsLeft <= 0) {
6666 return null;
6667 }
6668 }
6669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 synchronized (stats) {
6671 ps = stats.getProcessStatsLocked(info.uid, proc);
6672 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006673 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
6675
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006676 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6677 ProcessRecord app;
6678 if (!isolated) {
6679 app = getProcessRecordLocked(info.processName, info.uid);
6680 } else {
6681 app = null;
6682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683
6684 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006685 app = newProcessRecordLocked(null, info, null, isolated);
6686 mProcessNames.put(info.processName, app.uid, app);
6687 if (isolated) {
6688 mIsolatedProcesses.put(app.uid, app);
6689 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006690 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 }
6692
Dianne Hackborne7f97212011-02-24 14:40:20 -08006693 // This package really, really can not be stopped.
6694 try {
6695 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006696 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006697 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006698 } catch (IllegalArgumentException e) {
6699 Slog.w(TAG, "Failed trying to unstop package "
6700 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006701 }
6702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6704 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6705 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006706 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
6708 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6709 mPersistentStartingProcesses.add(app);
6710 startProcessLocked(app, "added application", app.processName);
6711 }
6712
6713 return app;
6714 }
6715
6716 public void unhandledBack() {
6717 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6718 "unhandledBack()");
6719
6720 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006721 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006722 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 TAG, "Performing unhandledBack(): stack size = " + count);
6724 if (count > 1) {
6725 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006726 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6728 Binder.restoreCallingIdentity(origId);
6729 }
6730 }
6731 }
6732
6733 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006734 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006736 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 ParcelFileDescriptor pfd = null;
6738 if (cph != null) {
6739 // We record the binder invoker's uid in thread-local storage before
6740 // going to the content provider to open the file. Later, in the code
6741 // that handles all permissions checks, we look for this uid and use
6742 // that rather than the Activity Manager's own uid. The effect is that
6743 // we do the check against the caller's permissions even though it looks
6744 // to the content provider like the Activity Manager itself is making
6745 // the request.
6746 sCallerIdentity.set(new Identity(
6747 Binder.getCallingPid(), Binder.getCallingUid()));
6748 try {
6749 pfd = cph.provider.openFile(uri, "r");
6750 } catch (FileNotFoundException e) {
6751 // do nothing; pfd will be returned null
6752 } finally {
6753 // Ensure that whatever happens, we clean up the identity state
6754 sCallerIdentity.remove();
6755 }
6756
6757 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006758 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006760 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 }
6762 return pfd;
6763 }
6764
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006765 // Actually is sleeping or shutting down or whatever else in the future
6766 // is an inactive state.
6767 public boolean isSleeping() {
6768 return mSleeping || mShuttingDown;
6769 }
6770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006772 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6773 != PackageManager.PERMISSION_GRANTED) {
6774 throw new SecurityException("Requires permission "
6775 + android.Manifest.permission.DEVICE_POWER);
6776 }
6777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006779 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006780 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006782 if (!mSleeping) {
6783 mSleeping = true;
6784 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006785
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006786 // Initialize the wake times of all processes.
6787 checkExcessivePowerUsageLocked(false);
6788 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6789 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6790 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 }
6793 }
6794
Dianne Hackborn55280a92009-05-07 15:53:46 -07006795 public boolean shutdown(int timeout) {
6796 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6797 != PackageManager.PERMISSION_GRANTED) {
6798 throw new SecurityException("Requires permission "
6799 + android.Manifest.permission.SHUTDOWN);
6800 }
6801
6802 boolean timedout = false;
6803
6804 synchronized(this) {
6805 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006806 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006807
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006808 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006809 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006810 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006811 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006812 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006813 long delay = endTime - System.currentTimeMillis();
6814 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006815 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006816 timedout = true;
6817 break;
6818 }
6819 try {
6820 this.wait();
6821 } catch (InterruptedException e) {
6822 }
6823 }
6824 }
6825 }
6826
6827 mUsageStatsService.shutdown();
6828 mBatteryStatsService.shutdown();
6829
6830 return timedout;
6831 }
6832
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006833 public final void activitySlept(IBinder token) {
6834 if (localLOGV) Slog.v(
6835 TAG, "Activity slept: token=" + token);
6836
6837 ActivityRecord r = null;
6838
6839 final long origId = Binder.clearCallingIdentity();
6840
6841 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006842 r = mMainStack.isInStackLocked(token);
6843 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006844 mMainStack.activitySleptLocked(r);
6845 }
6846 }
6847
6848 Binder.restoreCallingIdentity(origId);
6849 }
6850
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006851 private void comeOutOfSleepIfNeededLocked() {
6852 if (!mWentToSleep && !mLockScreenShown) {
6853 if (mSleeping) {
6854 mSleeping = false;
6855 mMainStack.awakeFromSleepingLocked();
6856 mMainStack.resumeTopActivityLocked(null);
6857 }
6858 }
6859 }
6860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006862 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6863 != PackageManager.PERMISSION_GRANTED) {
6864 throw new SecurityException("Requires permission "
6865 + android.Manifest.permission.DEVICE_POWER);
6866 }
6867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006869 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006870 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006871 comeOutOfSleepIfNeededLocked();
6872 }
6873 }
6874
Jeff Brownc042ee22012-05-08 13:03:42 -07006875 private void updateEventDispatchingLocked() {
6876 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6877 }
6878
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006879 public void setLockScreenShown(boolean shown) {
6880 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6881 != PackageManager.PERMISSION_GRANTED) {
6882 throw new SecurityException("Requires permission "
6883 + android.Manifest.permission.DEVICE_POWER);
6884 }
6885
6886 synchronized(this) {
6887 mLockScreenShown = shown;
6888 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 }
6890 }
6891
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006892 public void stopAppSwitches() {
6893 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6894 != PackageManager.PERMISSION_GRANTED) {
6895 throw new SecurityException("Requires permission "
6896 + android.Manifest.permission.STOP_APP_SWITCHES);
6897 }
6898
6899 synchronized(this) {
6900 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6901 + APP_SWITCH_DELAY_TIME;
6902 mDidAppSwitch = false;
6903 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6904 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6905 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6906 }
6907 }
6908
6909 public void resumeAppSwitches() {
6910 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6911 != PackageManager.PERMISSION_GRANTED) {
6912 throw new SecurityException("Requires permission "
6913 + android.Manifest.permission.STOP_APP_SWITCHES);
6914 }
6915
6916 synchronized(this) {
6917 // Note that we don't execute any pending app switches... we will
6918 // let those wait until either the timeout, or the next start
6919 // activity request.
6920 mAppSwitchesAllowedTime = 0;
6921 }
6922 }
6923
6924 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6925 String name) {
6926 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6927 return true;
6928 }
6929
6930 final int perm = checkComponentPermission(
6931 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006932 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006933 if (perm == PackageManager.PERMISSION_GRANTED) {
6934 return true;
6935 }
6936
Joe Onorato8a9b2202010-02-26 18:56:32 -08006937 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006938 return false;
6939 }
6940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 public void setDebugApp(String packageName, boolean waitForDebugger,
6942 boolean persistent) {
6943 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6944 "setDebugApp()");
6945
6946 // Note that this is not really thread safe if there are multiple
6947 // callers into it at the same time, but that's not a situation we
6948 // care about.
6949 if (persistent) {
6950 final ContentResolver resolver = mContext.getContentResolver();
6951 Settings.System.putString(
6952 resolver, Settings.System.DEBUG_APP,
6953 packageName);
6954 Settings.System.putInt(
6955 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6956 waitForDebugger ? 1 : 0);
6957 }
6958
6959 synchronized (this) {
6960 if (!persistent) {
6961 mOrigDebugApp = mDebugApp;
6962 mOrigWaitForDebugger = mWaitForDebugger;
6963 }
6964 mDebugApp = packageName;
6965 mWaitForDebugger = waitForDebugger;
6966 mDebugTransient = !persistent;
6967 if (packageName != null) {
6968 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006969 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 Binder.restoreCallingIdentity(origId);
6971 }
6972 }
6973 }
6974
Siva Velusamy92a8b222012-03-09 16:24:04 -08006975 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6976 synchronized (this) {
6977 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6978 if (!isDebuggable) {
6979 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6980 throw new SecurityException("Process not debuggable: " + app.packageName);
6981 }
6982 }
6983
6984 mOpenGlTraceApp = processName;
6985 }
6986 }
6987
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006988 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6989 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6990 synchronized (this) {
6991 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6992 if (!isDebuggable) {
6993 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6994 throw new SecurityException("Process not debuggable: " + app.packageName);
6995 }
6996 }
6997 mProfileApp = processName;
6998 mProfileFile = profileFile;
6999 if (mProfileFd != null) {
7000 try {
7001 mProfileFd.close();
7002 } catch (IOException e) {
7003 }
7004 mProfileFd = null;
7005 }
7006 mProfileFd = profileFd;
7007 mProfileType = 0;
7008 mAutoStopProfiler = autoStopProfiler;
7009 }
7010 }
7011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 public void setAlwaysFinish(boolean enabled) {
7013 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7014 "setAlwaysFinish()");
7015
7016 Settings.System.putInt(
7017 mContext.getContentResolver(),
7018 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7019
7020 synchronized (this) {
7021 mAlwaysFinishActivities = enabled;
7022 }
7023 }
7024
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007025 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007027 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007029 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 }
7031 }
7032
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007033 public boolean isUserAMonkey() {
7034 // For now the fact that there is a controller implies
7035 // we have a monkey.
7036 synchronized (this) {
7037 return mController != null;
7038 }
7039 }
7040
Jeff Sharkeya4620792011-05-20 15:29:23 -07007041 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007042 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7043 "registerProcessObserver()");
7044 synchronized (this) {
7045 mProcessObservers.register(observer);
7046 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007047 }
7048
7049 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007050 synchronized (this) {
7051 mProcessObservers.unregister(observer);
7052 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007053 }
7054
Daniel Sandler69a48172010-06-23 16:29:36 -04007055 public void setImmersive(IBinder token, boolean immersive) {
7056 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007057 ActivityRecord r = mMainStack.isInStackLocked(token);
7058 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007059 throw new IllegalArgumentException();
7060 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007061 r.immersive = immersive;
7062 }
7063 }
7064
7065 public boolean isImmersive(IBinder token) {
7066 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007067 ActivityRecord r = mMainStack.isInStackLocked(token);
7068 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007069 throw new IllegalArgumentException();
7070 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007071 return r.immersive;
7072 }
7073 }
7074
7075 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007076 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007077 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007078 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007079 return (r != null) ? r.immersive : false;
7080 }
7081 }
7082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 public final void enterSafeMode() {
7084 synchronized(this) {
7085 // It only makes sense to do this before the system is ready
7086 // and started launching other packages.
7087 if (!mSystemReady) {
7088 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007089 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 } catch (RemoteException e) {
7091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093 }
7094 }
7095
Jeff Brownb09abc12011-01-13 21:08:27 -08007096 public final void showSafeModeOverlay() {
7097 View v = LayoutInflater.from(mContext).inflate(
7098 com.android.internal.R.layout.safe_mode, null);
7099 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7100 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7101 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7102 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007103 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007104 lp.format = v.getBackground().getOpacity();
7105 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7106 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7107 ((WindowManager)mContext.getSystemService(
7108 Context.WINDOW_SERVICE)).addView(v, lp);
7109 }
7110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 public void noteWakeupAlarm(IIntentSender sender) {
7112 if (!(sender instanceof PendingIntentRecord)) {
7113 return;
7114 }
7115 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7116 synchronized (stats) {
7117 if (mBatteryStatsService.isOnBattery()) {
7118 mBatteryStatsService.enforceCallingPermission();
7119 PendingIntentRecord rec = (PendingIntentRecord)sender;
7120 int MY_UID = Binder.getCallingUid();
7121 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7122 BatteryStatsImpl.Uid.Pkg pkg =
7123 stats.getPackageStatsLocked(uid, rec.key.packageName);
7124 pkg.incWakeupsLocked();
7125 }
7126 }
7127 }
7128
Dianne Hackborn64825172011-03-02 21:32:58 -08007129 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007131 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007133 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 // XXX Note: don't acquire main activity lock here, because the window
7135 // manager calls in with its locks held.
7136
7137 boolean killed = false;
7138 synchronized (mPidsSelfLocked) {
7139 int[] types = new int[pids.length];
7140 int worstType = 0;
7141 for (int i=0; i<pids.length; i++) {
7142 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7143 if (proc != null) {
7144 int type = proc.setAdj;
7145 types[i] = type;
7146 if (type > worstType) {
7147 worstType = type;
7148 }
7149 }
7150 }
7151
Dianne Hackborn64825172011-03-02 21:32:58 -08007152 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007154 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7155 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007156 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007158
7159 // If this is not a secure call, don't let it kill processes that
7160 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007161 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7162 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007163 }
7164
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007165 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 for (int i=0; i<pids.length; i++) {
7167 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7168 if (proc == null) {
7169 continue;
7170 }
7171 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007172 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007173 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007174 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7175 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007177 proc.killedBackground = true;
7178 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 }
7180 }
7181 }
7182 return killed;
7183 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007184
7185 @Override
7186 public boolean killProcessesBelowForeground(String reason) {
7187 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7188 throw new SecurityException("killProcessesBelowForeground() only available to system");
7189 }
7190
7191 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7192 }
7193
7194 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7195 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7196 throw new SecurityException("killProcessesBelowAdj() only available to system");
7197 }
7198
7199 boolean killed = false;
7200 synchronized (mPidsSelfLocked) {
7201 final int size = mPidsSelfLocked.size();
7202 for (int i = 0; i < size; i++) {
7203 final int pid = mPidsSelfLocked.keyAt(i);
7204 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7205 if (proc == null) continue;
7206
7207 final int adj = proc.setAdj;
7208 if (adj > belowAdj && !proc.killedBackground) {
7209 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7210 EventLog.writeEvent(
7211 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7212 killed = true;
7213 proc.killedBackground = true;
7214 Process.killProcessQuiet(pid);
7215 }
7216 }
7217 }
7218 return killed;
7219 }
7220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 public final void startRunning(String pkg, String cls, String action,
7222 String data) {
7223 synchronized(this) {
7224 if (mStartRunning) {
7225 return;
7226 }
7227 mStartRunning = true;
7228 mTopComponent = pkg != null && cls != null
7229 ? new ComponentName(pkg, cls) : null;
7230 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7231 mTopData = data;
7232 if (!mSystemReady) {
7233 return;
7234 }
7235 }
7236
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007237 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238 }
7239
7240 private void retrieveSettings() {
7241 final ContentResolver resolver = mContext.getContentResolver();
7242 String debugApp = Settings.System.getString(
7243 resolver, Settings.System.DEBUG_APP);
7244 boolean waitForDebugger = Settings.System.getInt(
7245 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7246 boolean alwaysFinishActivities = Settings.System.getInt(
7247 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7248
7249 Configuration configuration = new Configuration();
7250 Settings.System.getConfiguration(resolver, configuration);
7251
7252 synchronized (this) {
7253 mDebugApp = mOrigDebugApp = debugApp;
7254 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7255 mAlwaysFinishActivities = alwaysFinishActivities;
7256 // This happens before any activities are started, so we can
7257 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007258 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007259 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 }
7261 }
7262
7263 public boolean testIsSystemReady() {
7264 // no need to synchronize(this) just to read & return the value
7265 return mSystemReady;
7266 }
7267
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007268 private static File getCalledPreBootReceiversFile() {
7269 File dataDir = Environment.getDataDirectory();
7270 File systemDir = new File(dataDir, "system");
7271 File fname = new File(systemDir, "called_pre_boots.dat");
7272 return fname;
7273 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007274
7275 static final int LAST_DONE_VERSION = 10000;
7276
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007277 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7278 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7279 File file = getCalledPreBootReceiversFile();
7280 FileInputStream fis = null;
7281 try {
7282 fis = new FileInputStream(file);
7283 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007284 int fvers = dis.readInt();
7285 if (fvers == LAST_DONE_VERSION) {
7286 String vers = dis.readUTF();
7287 String codename = dis.readUTF();
7288 String build = dis.readUTF();
7289 if (android.os.Build.VERSION.RELEASE.equals(vers)
7290 && android.os.Build.VERSION.CODENAME.equals(codename)
7291 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7292 int num = dis.readInt();
7293 while (num > 0) {
7294 num--;
7295 String pkg = dis.readUTF();
7296 String cls = dis.readUTF();
7297 lastDoneReceivers.add(new ComponentName(pkg, cls));
7298 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007299 }
7300 }
7301 } catch (FileNotFoundException e) {
7302 } catch (IOException e) {
7303 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7304 } finally {
7305 if (fis != null) {
7306 try {
7307 fis.close();
7308 } catch (IOException e) {
7309 }
7310 }
7311 }
7312 return lastDoneReceivers;
7313 }
7314
7315 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7316 File file = getCalledPreBootReceiversFile();
7317 FileOutputStream fos = null;
7318 DataOutputStream dos = null;
7319 try {
7320 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7321 fos = new FileOutputStream(file);
7322 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007323 dos.writeInt(LAST_DONE_VERSION);
7324 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007325 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007326 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007327 dos.writeInt(list.size());
7328 for (int i=0; i<list.size(); i++) {
7329 dos.writeUTF(list.get(i).getPackageName());
7330 dos.writeUTF(list.get(i).getClassName());
7331 }
7332 } catch (IOException e) {
7333 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7334 file.delete();
7335 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007336 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007337 if (dos != null) {
7338 try {
7339 dos.close();
7340 } catch (IOException e) {
7341 // TODO Auto-generated catch block
7342 e.printStackTrace();
7343 }
7344 }
7345 }
7346 }
7347
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007348 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 synchronized(this) {
7350 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007351 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 return;
7353 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007354
7355 // Check to see if there are any update receivers to run.
7356 if (!mDidUpdate) {
7357 if (mWaitingUpdate) {
7358 return;
7359 }
7360 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7361 List<ResolveInfo> ris = null;
7362 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007363 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007364 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007365 } catch (RemoteException e) {
7366 }
7367 if (ris != null) {
7368 for (int i=ris.size()-1; i>=0; i--) {
7369 if ((ris.get(i).activityInfo.applicationInfo.flags
7370 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7371 ris.remove(i);
7372 }
7373 }
7374 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007375
7376 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7377
7378 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007379 for (int i=0; i<ris.size(); i++) {
7380 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007381 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7382 if (lastDoneReceivers.contains(comp)) {
7383 ris.remove(i);
7384 i--;
7385 }
7386 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007387
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007388 for (int i=0; i<ris.size(); i++) {
7389 ActivityInfo ai = ris.get(i).activityInfo;
7390 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7391 doneReceivers.add(comp);
7392 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007393 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007394 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007395 finisher = new IIntentReceiver.Stub() {
7396 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007397 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007398 boolean sticky) {
7399 // The raw IIntentReceiver interface is called
7400 // with the AM lock held, so redispatch to
7401 // execute our code without the lock.
7402 mHandler.post(new Runnable() {
7403 public void run() {
7404 synchronized (ActivityManagerService.this) {
7405 mDidUpdate = true;
7406 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007407 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007408 showBootMessage(mContext.getText(
7409 R.string.android_upgrading_complete),
7410 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007411 systemReady(goingCallback);
7412 }
7413 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007414 }
7415 };
7416 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007417 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007418 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007419 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007420 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007421 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007422 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007423 mWaitingUpdate = true;
7424 }
7425 }
7426 }
7427 if (mWaitingUpdate) {
7428 return;
7429 }
7430 mDidUpdate = true;
7431 }
7432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 mSystemReady = true;
7434 if (!mStartRunning) {
7435 return;
7436 }
7437 }
7438
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007439 ArrayList<ProcessRecord> procsToKill = null;
7440 synchronized(mPidsSelfLocked) {
7441 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7442 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7443 if (!isAllowedWhileBooting(proc.info)){
7444 if (procsToKill == null) {
7445 procsToKill = new ArrayList<ProcessRecord>();
7446 }
7447 procsToKill.add(proc);
7448 }
7449 }
7450 }
7451
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007452 synchronized(this) {
7453 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007454 for (int i=procsToKill.size()-1; i>=0; i--) {
7455 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007456 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007457 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007458 }
7459 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007460
7461 // Now that we have cleaned up any update processes, we
7462 // are ready to start launching real processes and know that
7463 // we won't trample on them any more.
7464 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007465 }
7466
Joe Onorato8a9b2202010-02-26 18:56:32 -08007467 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007468 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 SystemClock.uptimeMillis());
7470
7471 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007472 // Make sure we have no pre-ready processes sitting around.
7473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7475 ResolveInfo ri = mContext.getPackageManager()
7476 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007477 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 CharSequence errorMsg = null;
7479 if (ri != null) {
7480 ActivityInfo ai = ri.activityInfo;
7481 ApplicationInfo app = ai.applicationInfo;
7482 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7483 mTopAction = Intent.ACTION_FACTORY_TEST;
7484 mTopData = null;
7485 mTopComponent = new ComponentName(app.packageName,
7486 ai.name);
7487 } else {
7488 errorMsg = mContext.getResources().getText(
7489 com.android.internal.R.string.factorytest_not_system);
7490 }
7491 } else {
7492 errorMsg = mContext.getResources().getText(
7493 com.android.internal.R.string.factorytest_no_action);
7494 }
7495 if (errorMsg != null) {
7496 mTopAction = null;
7497 mTopData = null;
7498 mTopComponent = null;
7499 Message msg = Message.obtain();
7500 msg.what = SHOW_FACTORY_ERROR_MSG;
7501 msg.getData().putCharSequence("msg", errorMsg);
7502 mHandler.sendMessage(msg);
7503 }
7504 }
7505 }
7506
7507 retrieveSettings();
7508
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007509 if (goingCallback != null) goingCallback.run();
7510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 synchronized (this) {
7512 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7513 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007514 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007515 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 if (apps != null) {
7517 int N = apps.size();
7518 int i;
7519 for (i=0; i<N; i++) {
7520 ApplicationInfo info
7521 = (ApplicationInfo)apps.get(i);
7522 if (info != null &&
7523 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007524 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 }
7526 }
7527 }
7528 } catch (RemoteException ex) {
7529 // pm is in same process, this will never happen.
7530 }
7531 }
7532
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007533 // Start up initial activity.
7534 mBooting = true;
7535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007537 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 Message msg = Message.obtain();
7539 msg.what = SHOW_UID_ERROR_MSG;
7540 mHandler.sendMessage(msg);
7541 }
7542 } catch (RemoteException e) {
7543 }
7544
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007545 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 }
7547 }
7548
Dan Egnorb7f03672009-12-09 16:22:32 -08007549 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007550 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007552 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007553 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 startAppProblemLocked(app);
7555 app.stopFreezingAllLocked();
7556 return handleAppCrashLocked(app);
7557 }
7558
Dan Egnorb7f03672009-12-09 16:22:32 -08007559 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007560 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007562 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007563 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7564 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 startAppProblemLocked(app);
7566 app.stopFreezingAllLocked();
7567 }
7568
7569 /**
7570 * Generate a process error record, suitable for attachment to a ProcessRecord.
7571 *
7572 * @param app The ProcessRecord in which the error occurred.
7573 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7574 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007575 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 * @param shortMsg Short message describing the crash.
7577 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007578 * @param stackTrace Full crash stack trace, may be null.
7579 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 * @return Returns a fully-formed AppErrorStateInfo record.
7581 */
7582 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007583 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 report.condition = condition;
7587 report.processName = app.processName;
7588 report.pid = app.pid;
7589 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007590 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 report.shortMsg = shortMsg;
7592 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007593 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594
7595 return report;
7596 }
7597
Dan Egnor42471dd2010-01-07 17:25:22 -08007598 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 synchronized (this) {
7600 app.crashing = false;
7601 app.crashingReport = null;
7602 app.notResponding = false;
7603 app.notRespondingReport = null;
7604 if (app.anrDialog == fromDialog) {
7605 app.anrDialog = null;
7606 }
7607 if (app.waitDialog == fromDialog) {
7608 app.waitDialog = null;
7609 }
7610 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007611 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007612 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007613 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7614 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007615 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 }
7618 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007619
Dan Egnorb7f03672009-12-09 16:22:32 -08007620 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007621 if (mHeadless) {
7622 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7623 return false;
7624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 long now = SystemClock.uptimeMillis();
7626
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007627 Long crashTime;
7628 if (!app.isolated) {
7629 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7630 } else {
7631 crashTime = null;
7632 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007633 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007635 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007637 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007638 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007639 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7640 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007642 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007644 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 }
7646 }
7647 if (!app.persistent) {
7648 // We don't want to start this process again until the user
7649 // explicitly does so... but for persistent process, we really
7650 // need to keep it running. If a persistent process is actually
7651 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007652 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007654 if (!app.isolated) {
7655 // XXX We don't have a way to mark isolated processes
7656 // as bad, since they don't have a peristent identity.
7657 mBadProcesses.put(app.info.processName, app.uid, now);
7658 mProcessCrashTimes.remove(app.info.processName, app.uid);
7659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007662 // Don't let services in this process be restarted and potentially
7663 // annoy the user repeatedly. Unless it is persistent, since those
7664 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007665 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007666 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 return false;
7668 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007669 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007670 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007671 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007672 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007673 // If the top running activity is from this crashing
7674 // process, then terminate it to avoid getting in a loop.
7675 Slog.w(TAG, " Force finishing activity "
7676 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007677 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007678 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007679 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007680 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007681 // stopped, to avoid a situation where one will get
7682 // re-start our crashing activity once it gets resumed again.
7683 index--;
7684 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007685 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007686 if (r.state == ActivityState.RESUMED
7687 || r.state == ActivityState.PAUSING
7688 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007689 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007690 Slog.w(TAG, " Force finishing activity "
7691 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007692 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007693 Activity.RESULT_CANCELED, null, "crashed");
7694 }
7695 }
7696 }
7697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 }
7699
7700 // Bump up the crash count of any services currently running in the proc.
7701 if (app.services.size() != 0) {
7702 // Any services running in the application need to be placed
7703 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007704 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007706 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 sr.crashCount++;
7708 }
7709 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007710
7711 // If the crashing process is what we consider to be the "home process" and it has been
7712 // replaced by a third-party app, clear the package preferred activities from packages
7713 // with a home activity running in the process to prevent a repeatedly crashing app
7714 // from blocking the user to manually clear the list.
7715 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7716 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7717 Iterator it = mHomeProcess.activities.iterator();
7718 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007719 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007720 if (r.isHomeActivity) {
7721 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7722 try {
7723 ActivityThread.getPackageManager()
7724 .clearPackagePreferredActivities(r.packageName);
7725 } catch (RemoteException c) {
7726 // pm is in same process, this will never happen.
7727 }
7728 }
7729 }
7730 }
7731
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007732 if (!app.isolated) {
7733 // XXX Can't keep track of crash times for isolated processes,
7734 // because they don't have a perisistent identity.
7735 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7736 }
7737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 return true;
7739 }
7740
7741 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007742 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7743 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 skipCurrentReceiverLocked(app);
7745 }
7746
7747 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007748 for (BroadcastQueue queue : mBroadcastQueues) {
7749 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 }
7751 }
7752
Dan Egnor60d87622009-12-16 16:32:58 -08007753 /**
7754 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7755 * The application process will exit immediately after this call returns.
7756 * @param app object of the crashing app, null for the system server
7757 * @param crashInfo describing the exception
7758 */
7759 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007760 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007761 final String processName = app == null ? "system_server"
7762 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007763
7764 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007765 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007766 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007767 crashInfo.exceptionClassName,
7768 crashInfo.exceptionMessage,
7769 crashInfo.throwFileName,
7770 crashInfo.throwLineNumber);
7771
Jeff Sharkeya353d262011-10-28 11:12:06 -07007772 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007773
7774 crashApplication(r, crashInfo);
7775 }
7776
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007777 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007778 IBinder app,
7779 int violationMask,
7780 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007781 ProcessRecord r = findAppProcess(app, "StrictMode");
7782 if (r == null) {
7783 return;
7784 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007785
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007786 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007787 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007788 boolean logIt = true;
7789 synchronized (mAlreadyLoggedViolatedStacks) {
7790 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7791 logIt = false;
7792 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007793 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007794 // the relative pain numbers, without logging all
7795 // the stack traces repeatedly. We'd want to do
7796 // likewise in the client code, which also does
7797 // dup suppression, before the Binder call.
7798 } else {
7799 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7800 mAlreadyLoggedViolatedStacks.clear();
7801 }
7802 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7803 }
7804 }
7805 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007806 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007807 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007808 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007809
7810 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7811 AppErrorResult result = new AppErrorResult();
7812 synchronized (this) {
7813 final long origId = Binder.clearCallingIdentity();
7814
7815 Message msg = Message.obtain();
7816 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7817 HashMap<String, Object> data = new HashMap<String, Object>();
7818 data.put("result", result);
7819 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007820 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007821 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007822 msg.obj = data;
7823 mHandler.sendMessage(msg);
7824
7825 Binder.restoreCallingIdentity(origId);
7826 }
7827 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007828 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007829 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007830 }
7831
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007832 // Depending on the policy in effect, there could be a bunch of
7833 // these in quick succession so we try to batch these together to
7834 // minimize disk writes, number of dropbox entries, and maximize
7835 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007836 private void logStrictModeViolationToDropBox(
7837 ProcessRecord process,
7838 StrictMode.ViolationInfo info) {
7839 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007840 return;
7841 }
7842 final boolean isSystemApp = process == null ||
7843 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7844 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007845 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007846 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7847 final DropBoxManager dbox = (DropBoxManager)
7848 mContext.getSystemService(Context.DROPBOX_SERVICE);
7849
7850 // Exit early if the dropbox isn't configured to accept this report type.
7851 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7852
7853 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007854 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007855 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7856 synchronized (sb) {
7857 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007858 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007859 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7860 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007861 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7862 if (info.violationNumThisLoop != 0) {
7863 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7864 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007865 if (info.numAnimationsRunning != 0) {
7866 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7867 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007868 if (info.broadcastIntentAction != null) {
7869 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7870 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007871 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007872 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007873 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007874 if (info.numInstances != -1) {
7875 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7876 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007877 if (info.tags != null) {
7878 for (String tag : info.tags) {
7879 sb.append("Span-Tag: ").append(tag).append("\n");
7880 }
7881 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007882 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007883 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7884 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007885 }
7886 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007887
7888 // Only buffer up to ~64k. Various logging bits truncate
7889 // things at 128k.
7890 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007891 }
7892
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007893 // Flush immediately if the buffer's grown too large, or this
7894 // is a non-system app. Non-system apps are isolated with a
7895 // different tag & policy and not batched.
7896 //
7897 // Batching is useful during internal testing with
7898 // StrictMode settings turned up high. Without batching,
7899 // thousands of separate files could be created on boot.
7900 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007901 new Thread("Error dump: " + dropboxTag) {
7902 @Override
7903 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007904 String report;
7905 synchronized (sb) {
7906 report = sb.toString();
7907 sb.delete(0, sb.length());
7908 sb.trimToSize();
7909 }
7910 if (report.length() != 0) {
7911 dbox.addText(dropboxTag, report);
7912 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007913 }
7914 }.start();
7915 return;
7916 }
7917
7918 // System app batching:
7919 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007920 // An existing dropbox-writing thread is outstanding, so
7921 // we don't need to start it up. The existing thread will
7922 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007923 return;
7924 }
7925
7926 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7927 // (After this point, we shouldn't access AMS internal data structures.)
7928 new Thread("Error dump: " + dropboxTag) {
7929 @Override
7930 public void run() {
7931 // 5 second sleep to let stacks arrive and be batched together
7932 try {
7933 Thread.sleep(5000); // 5 seconds
7934 } catch (InterruptedException e) {}
7935
7936 String errorReport;
7937 synchronized (mStrictModeBuffer) {
7938 errorReport = mStrictModeBuffer.toString();
7939 if (errorReport.length() == 0) {
7940 return;
7941 }
7942 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7943 mStrictModeBuffer.trimToSize();
7944 }
7945 dbox.addText(dropboxTag, errorReport);
7946 }
7947 }.start();
7948 }
7949
Dan Egnor60d87622009-12-16 16:32:58 -08007950 /**
7951 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7952 * @param app object of the crashing app, null for the system server
7953 * @param tag reported by the caller
7954 * @param crashInfo describing the context of the error
7955 * @return true if the process should exit immediately (WTF is fatal)
7956 */
7957 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007959 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007960 final String processName = app == null ? "system_server"
7961 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007962
7963 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007964 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007965 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007966 tag, crashInfo.exceptionMessage);
7967
Jeff Sharkeya353d262011-10-28 11:12:06 -07007968 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007969
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007970 if (r != null && r.pid != Process.myPid() &&
7971 Settings.Secure.getInt(mContext.getContentResolver(),
7972 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007973 crashApplication(r, crashInfo);
7974 return true;
7975 } else {
7976 return false;
7977 }
7978 }
7979
7980 /**
7981 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7982 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7983 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007984 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007985 if (app == null) {
7986 return null;
7987 }
7988
7989 synchronized (this) {
7990 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7991 final int NA = apps.size();
7992 for (int ia=0; ia<NA; ia++) {
7993 ProcessRecord p = apps.valueAt(ia);
7994 if (p.thread != null && p.thread.asBinder() == app) {
7995 return p;
7996 }
7997 }
7998 }
7999
Dianne Hackborncb44d962011-03-10 17:02:27 -08008000 Slog.w(TAG, "Can't find mystery application for " + reason
8001 + " from pid=" + Binder.getCallingPid()
8002 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008003 return null;
8004 }
8005 }
8006
8007 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008008 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8009 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008010 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008011 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8012 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008013 // Watchdog thread ends up invoking this function (with
8014 // a null ProcessRecord) to add the stack file to dropbox.
8015 // Do not acquire a lock on this (am) in such cases, as it
8016 // could cause a potential deadlock, if and when watchdog
8017 // is invoked due to unavailability of lock on am and it
8018 // would prevent watchdog from killing system_server.
8019 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008020 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008021 return;
8022 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008023 // Note: ProcessRecord 'process' is guarded by the service
8024 // instance. (notably process.pkgList, which could otherwise change
8025 // concurrently during execution of this method)
8026 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008027 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008028 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008029 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008030 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8031 for (String pkg : process.pkgList) {
8032 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008033 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008034 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008035 if (pi != null) {
8036 sb.append(" v").append(pi.versionCode);
8037 if (pi.versionName != null) {
8038 sb.append(" (").append(pi.versionName).append(")");
8039 }
8040 }
8041 } catch (RemoteException e) {
8042 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008043 }
Dan Egnora455d192010-03-12 08:52:28 -08008044 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008045 }
Dan Egnora455d192010-03-12 08:52:28 -08008046 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008047 }
8048
8049 private static String processClass(ProcessRecord process) {
8050 if (process == null || process.pid == MY_PID) {
8051 return "system_server";
8052 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8053 return "system_app";
8054 } else {
8055 return "data_app";
8056 }
8057 }
8058
8059 /**
8060 * Write a description of an error (crash, WTF, ANR) to the drop box.
8061 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8062 * @param process which caused the error, null means the system server
8063 * @param activity which triggered the error, null if unknown
8064 * @param parent activity related to the error, null if unknown
8065 * @param subject line related to the error, null if absent
8066 * @param report in long form describing the error, null if absent
8067 * @param logFile to include in the report, null if none
8068 * @param crashInfo giving an application stack trace, null if absent
8069 */
8070 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008071 ProcessRecord process, String processName, ActivityRecord activity,
8072 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008073 final String report, final File logFile,
8074 final ApplicationErrorReport.CrashInfo crashInfo) {
8075 // NOTE -- this must never acquire the ActivityManagerService lock,
8076 // otherwise the watchdog may be prevented from resetting the system.
8077
8078 final String dropboxTag = processClass(process) + "_" + eventType;
8079 final DropBoxManager dbox = (DropBoxManager)
8080 mContext.getSystemService(Context.DROPBOX_SERVICE);
8081
8082 // Exit early if the dropbox isn't configured to accept this report type.
8083 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8084
8085 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008086 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008087 if (activity != null) {
8088 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8089 }
8090 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8091 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8092 }
8093 if (parent != null && parent != activity) {
8094 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8095 }
8096 if (subject != null) {
8097 sb.append("Subject: ").append(subject).append("\n");
8098 }
8099 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008100 if (Debug.isDebuggerConnected()) {
8101 sb.append("Debugger: Connected\n");
8102 }
Dan Egnora455d192010-03-12 08:52:28 -08008103 sb.append("\n");
8104
8105 // Do the rest in a worker thread to avoid blocking the caller on I/O
8106 // (After this point, we shouldn't access AMS internal data structures.)
8107 Thread worker = new Thread("Error dump: " + dropboxTag) {
8108 @Override
8109 public void run() {
8110 if (report != null) {
8111 sb.append(report);
8112 }
8113 if (logFile != null) {
8114 try {
8115 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8116 } catch (IOException e) {
8117 Slog.e(TAG, "Error reading " + logFile, e);
8118 }
8119 }
8120 if (crashInfo != null && crashInfo.stackTrace != null) {
8121 sb.append(crashInfo.stackTrace);
8122 }
8123
8124 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8125 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8126 if (lines > 0) {
8127 sb.append("\n");
8128
8129 // Merge several logcat streams, and take the last N lines
8130 InputStreamReader input = null;
8131 try {
8132 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8133 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8134 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8135
8136 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8137 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8138 input = new InputStreamReader(logcat.getInputStream());
8139
8140 int num;
8141 char[] buf = new char[8192];
8142 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8143 } catch (IOException e) {
8144 Slog.e(TAG, "Error running logcat", e);
8145 } finally {
8146 if (input != null) try { input.close(); } catch (IOException e) {}
8147 }
8148 }
8149
8150 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008151 }
Dan Egnora455d192010-03-12 08:52:28 -08008152 };
8153
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008154 if (process == null) {
8155 // If process is null, we are being called from some internal code
8156 // and may be about to die -- run this synchronously.
8157 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008158 } else {
8159 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008160 }
8161 }
8162
8163 /**
8164 * Bring up the "unexpected error" dialog box for a crashing app.
8165 * Deal with edge cases (intercepts from instrumented applications,
8166 * ActivityController, error intent receivers, that sort of thing).
8167 * @param r the application crashing
8168 * @param crashInfo describing the failure
8169 */
8170 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008171 long timeMillis = System.currentTimeMillis();
8172 String shortMsg = crashInfo.exceptionClassName;
8173 String longMsg = crashInfo.exceptionMessage;
8174 String stackTrace = crashInfo.stackTrace;
8175 if (shortMsg != null && longMsg != null) {
8176 longMsg = shortMsg + ": " + longMsg;
8177 } else if (shortMsg != null) {
8178 longMsg = shortMsg;
8179 }
8180
Dan Egnor60d87622009-12-16 16:32:58 -08008181 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008183 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 try {
8185 String name = r != null ? r.processName : null;
8186 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008187 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008188 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008189 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 + " at watcher's request");
8191 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008192 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008195 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 }
8197 }
8198
8199 final long origId = Binder.clearCallingIdentity();
8200
8201 // If this process is running instrumentation, finish it.
8202 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008203 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008205 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8206 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008207 Bundle info = new Bundle();
8208 info.putString("shortMsg", shortMsg);
8209 info.putString("longMsg", longMsg);
8210 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8211 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008212 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 }
8214
Dan Egnor60d87622009-12-16 16:32:58 -08008215 // If we can't identify the process or it's already exceeded its crash quota,
8216 // quit right away without showing a crash dialog.
8217 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008219 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 }
8221
8222 Message msg = Message.obtain();
8223 msg.what = SHOW_ERROR_MSG;
8224 HashMap data = new HashMap();
8225 data.put("result", result);
8226 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 msg.obj = data;
8228 mHandler.sendMessage(msg);
8229
8230 Binder.restoreCallingIdentity(origId);
8231 }
8232
8233 int res = result.get();
8234
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008235 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008237 if (r != null && !r.isolated) {
8238 // XXX Can't keep track of crash time for isolated processes,
8239 // since they don't have a persistent identity.
8240 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008241 SystemClock.uptimeMillis());
8242 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008243 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008244 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008245 }
8246 }
8247
8248 if (appErrorIntent != null) {
8249 try {
8250 mContext.startActivity(appErrorIntent);
8251 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008252 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008256
8257 Intent createAppErrorIntentLocked(ProcessRecord r,
8258 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8259 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008260 if (report == null) {
8261 return null;
8262 }
8263 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8264 result.setComponent(r.errorReportReceiver);
8265 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8266 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8267 return result;
8268 }
8269
Dan Egnorb7f03672009-12-09 16:22:32 -08008270 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8271 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008272 if (r.errorReportReceiver == null) {
8273 return null;
8274 }
8275
8276 if (!r.crashing && !r.notResponding) {
8277 return null;
8278 }
8279
Dan Egnorb7f03672009-12-09 16:22:32 -08008280 ApplicationErrorReport report = new ApplicationErrorReport();
8281 report.packageName = r.info.packageName;
8282 report.installerPackageName = r.errorReportReceiver.getPackageName();
8283 report.processName = r.processName;
8284 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008285 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008286
Dan Egnorb7f03672009-12-09 16:22:32 -08008287 if (r.crashing) {
8288 report.type = ApplicationErrorReport.TYPE_CRASH;
8289 report.crashInfo = crashInfo;
8290 } else if (r.notResponding) {
8291 report.type = ApplicationErrorReport.TYPE_ANR;
8292 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008293
Dan Egnorb7f03672009-12-09 16:22:32 -08008294 report.anrInfo.activity = r.notRespondingReport.tag;
8295 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8296 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008297 }
8298
Dan Egnorb7f03672009-12-09 16:22:32 -08008299 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008300 }
8301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008303 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 // assume our apps are happy - lazy create the list
8305 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8306
8307 synchronized (this) {
8308
8309 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008310 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8311 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8313 // This one's in trouble, so we'll generate a report for it
8314 // crashes are higher priority (in case there's a crash *and* an anr)
8315 ActivityManager.ProcessErrorStateInfo report = null;
8316 if (app.crashing) {
8317 report = app.crashingReport;
8318 } else if (app.notResponding) {
8319 report = app.notRespondingReport;
8320 }
8321
8322 if (report != null) {
8323 if (errList == null) {
8324 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8325 }
8326 errList.add(report);
8327 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008328 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 " crashing = " + app.crashing +
8330 " notResponding = " + app.notResponding);
8331 }
8332 }
8333 }
8334 }
8335
8336 return errList;
8337 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008338
8339 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008340 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008341 if (currApp != null) {
8342 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8343 }
8344 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008345 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8346 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008347 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8348 if (currApp != null) {
8349 currApp.lru = 0;
8350 }
8351 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008352 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008353 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8354 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8355 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8356 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8357 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8358 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8359 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8360 } else {
8361 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8362 }
8363 }
8364
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008365 private void fillInProcMemInfo(ProcessRecord app,
8366 ActivityManager.RunningAppProcessInfo outInfo) {
8367 outInfo.pid = app.pid;
8368 outInfo.uid = app.info.uid;
8369 if (mHeavyWeightProcess == app) {
8370 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8371 }
8372 if (app.persistent) {
8373 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8374 }
8375 outInfo.lastTrimLevel = app.trimMemoryLevel;
8376 int adj = app.curAdj;
8377 outInfo.importance = oomAdjToImportance(adj, outInfo);
8378 outInfo.importanceReasonCode = app.adjTypeCode;
8379 }
8380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008382 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 // Lazy instantiation of list
8384 List<ActivityManager.RunningAppProcessInfo> runList = null;
8385 synchronized (this) {
8386 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008387 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8388 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8390 // Generate process state info for running application
8391 ActivityManager.RunningAppProcessInfo currApp =
8392 new ActivityManager.RunningAppProcessInfo(app.processName,
8393 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008394 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008395 if (app.adjSource instanceof ProcessRecord) {
8396 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008397 currApp.importanceReasonImportance = oomAdjToImportance(
8398 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008399 } else if (app.adjSource instanceof ActivityRecord) {
8400 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008401 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8402 }
8403 if (app.adjTarget instanceof ComponentName) {
8404 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8405 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008406 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 // + " lru=" + currApp.lru);
8408 if (runList == null) {
8409 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8410 }
8411 runList.add(currApp);
8412 }
8413 }
8414 }
8415 return runList;
8416 }
8417
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008418 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008419 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008420 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8421 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8422 if (runningApps != null && runningApps.size() > 0) {
8423 Set<String> extList = new HashSet<String>();
8424 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8425 if (app.pkgList != null) {
8426 for (String pkg : app.pkgList) {
8427 extList.add(pkg);
8428 }
8429 }
8430 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008431 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008432 for (String pkg : extList) {
8433 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008434 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008435 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8436 retList.add(info);
8437 }
8438 } catch (RemoteException e) {
8439 }
8440 }
8441 }
8442 return retList;
8443 }
8444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008446 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8447 enforceNotIsolatedCaller("getMyMemoryState");
8448 synchronized (this) {
8449 ProcessRecord proc;
8450 synchronized (mPidsSelfLocked) {
8451 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8452 }
8453 fillInProcMemInfo(proc, outInfo);
8454 }
8455 }
8456
8457 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008459 if (checkCallingPermission(android.Manifest.permission.DUMP)
8460 != PackageManager.PERMISSION_GRANTED) {
8461 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8462 + Binder.getCallingPid()
8463 + ", uid=" + Binder.getCallingUid()
8464 + " without permission "
8465 + android.Manifest.permission.DUMP);
8466 return;
8467 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008468
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008469 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008470 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008471 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008472
8473 int opti = 0;
8474 while (opti < args.length) {
8475 String opt = args[opti];
8476 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8477 break;
8478 }
8479 opti++;
8480 if ("-a".equals(opt)) {
8481 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008482 } else if ("-c".equals(opt)) {
8483 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 } else if ("-h".equals(opt)) {
8485 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008486 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008487 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008488 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008489 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8490 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8491 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008492 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008493 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008494 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008495 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008496 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008498 pw.println(" all: dump all activities");
8499 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008500 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008501 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8502 pw.println(" a partial substring in a component name, a");
8503 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008504 pw.println(" -a: include all available server state.");
8505 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 } else {
8508 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008511
8512 long origId = Binder.clearCallingIdentity();
8513 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008514 // Is the caller requesting to dump a particular piece of data?
8515 if (opti < args.length) {
8516 String cmd = args[opti];
8517 opti++;
8518 if ("activities".equals(cmd) || "a".equals(cmd)) {
8519 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008520 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008522 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008523 String[] newArgs;
8524 String name;
8525 if (opti >= args.length) {
8526 name = null;
8527 newArgs = EMPTY_STRING_ARRAY;
8528 } else {
8529 name = args[opti];
8530 opti++;
8531 newArgs = new String[args.length - opti];
8532 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8533 args.length - opti);
8534 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008535 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008536 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008538 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008539 String[] newArgs;
8540 String name;
8541 if (opti >= args.length) {
8542 name = null;
8543 newArgs = EMPTY_STRING_ARRAY;
8544 } else {
8545 name = args[opti];
8546 opti++;
8547 newArgs = new String[args.length - opti];
8548 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8549 args.length - opti);
8550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008552 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008553 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008554 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 String[] newArgs;
8556 String name;
8557 if (opti >= args.length) {
8558 name = null;
8559 newArgs = EMPTY_STRING_ARRAY;
8560 } else {
8561 name = args[opti];
8562 opti++;
8563 newArgs = new String[args.length - opti];
8564 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8565 args.length - opti);
8566 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008567 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008568 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008569 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008570 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8571 synchronized (this) {
8572 dumpOomLocked(fd, pw, args, opti, true);
8573 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008574 } else if ("provider".equals(cmd)) {
8575 String[] newArgs;
8576 String name;
8577 if (opti >= args.length) {
8578 name = null;
8579 newArgs = EMPTY_STRING_ARRAY;
8580 } else {
8581 name = args[opti];
8582 opti++;
8583 newArgs = new String[args.length - opti];
8584 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8585 }
8586 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8587 pw.println("No providers match: " + name);
8588 pw.println("Use -h for help.");
8589 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008590 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8591 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008592 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008595 String[] newArgs;
8596 String name;
8597 if (opti >= args.length) {
8598 name = null;
8599 newArgs = EMPTY_STRING_ARRAY;
8600 } else {
8601 name = args[opti];
8602 opti++;
8603 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008604 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8605 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008606 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008607 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008608 pw.println("No services match: " + name);
8609 pw.println("Use -h for help.");
8610 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008611 } else if ("package".equals(cmd)) {
8612 String[] newArgs;
8613 if (opti >= args.length) {
8614 pw.println("package: no package name specified");
8615 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008616 } else {
8617 dumpPackage = args[opti];
8618 opti++;
8619 newArgs = new String[args.length - opti];
8620 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8621 args.length - opti);
8622 args = newArgs;
8623 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008624 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008625 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008626 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8627 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008628 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008629 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008630 } else {
8631 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008632 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8633 pw.println("Bad activity command, or no activities match: " + cmd);
8634 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008635 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008636 }
8637 if (!more) {
8638 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008639 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008642
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 // No piece of data specified, dump everything.
8644 synchronized (this) {
8645 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008646 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 if (needSep) {
8648 pw.println(" ");
8649 }
8650 if (dumpAll) {
8651 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008652 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008653 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008654 if (needSep) {
8655 pw.println(" ");
8656 }
8657 if (dumpAll) {
8658 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008660 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008661 if (needSep) {
8662 pw.println(" ");
8663 }
8664 if (dumpAll) {
8665 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008666 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008667 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 if (needSep) {
8669 pw.println(" ");
8670 }
8671 if (dumpAll) {
8672 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008673 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008674 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008675 if (needSep) {
8676 pw.println(" ");
8677 }
8678 if (dumpAll) {
8679 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008680 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008681 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008683 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008684 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008685
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008687 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008688 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8689 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008690 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8691 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 pw.println(" ");
8693 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008694 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8695 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008696 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008699 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008700 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008701 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008702 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008704 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008705 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008706 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008708 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8709 pw.println(" ");
8710 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008711 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008712 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008713 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008714 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008715 pw.println(" ");
8716 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008717 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008721 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008722 if (mMainStack.mPausingActivity != null) {
8723 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008724 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008725 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008727 if (dumpAll) {
8728 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8729 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008730 pw.println(" mDismissKeyguardOnNextActivity: "
8731 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008734 if (mRecentTasks.size() > 0) {
8735 pw.println();
8736 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737
8738 final int N = mRecentTasks.size();
8739 for (int i=0; i<N; i++) {
8740 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008741 if (dumpPackage != null) {
8742 if (tr.realActivity == null ||
8743 !dumpPackage.equals(tr.realActivity)) {
8744 continue;
8745 }
8746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8748 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008749 if (dumpAll) {
8750 mRecentTasks.get(i).dump(pw, " ");
8751 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 }
8753 }
8754
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008755 if (dumpAll) {
8756 pw.println(" ");
8757 pw.println(" mCurTask: " + mCurTask);
8758 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008759
8760 return true;
8761 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008762
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 boolean needSep = false;
8766 int numPers = 0;
8767
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008768 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8769
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008770 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8772 final int NA = procs.size();
8773 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008774 ProcessRecord r = procs.valueAt(ia);
8775 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8776 continue;
8777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 if (!needSep) {
8779 pw.println(" All known processes:");
8780 needSep = true;
8781 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008782 pw.print(r.persistent ? " *PERS*" : " *APP*");
8783 pw.print(" UID "); pw.print(procs.keyAt(ia));
8784 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 r.dump(pw, " ");
8786 if (r.persistent) {
8787 numPers++;
8788 }
8789 }
8790 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008791 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008792
8793 if (mIsolatedProcesses.size() > 0) {
8794 if (needSep) pw.println(" ");
8795 needSep = true;
8796 pw.println(" Isolated process list (sorted by uid):");
8797 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8798 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8799 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8800 continue;
8801 }
8802 pw.println(String.format("%sIsolated #%2d: %s",
8803 " ", i, r.toString()));
8804 }
8805 }
8806
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008807 if (mLruProcesses.size() > 0) {
8808 if (needSep) pw.println(" ");
8809 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008810 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008811 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008812 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 needSep = true;
8814 }
8815
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008816 if (dumpAll) {
8817 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008818 boolean printed = false;
8819 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8820 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8821 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8822 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008823 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008824 if (!printed) {
8825 if (needSep) pw.println(" ");
8826 needSep = true;
8827 pw.println(" PID mappings:");
8828 printed = true;
8829 }
8830 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8831 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 }
8833 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 }
8835
8836 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008837 synchronized (mPidsSelfLocked) {
8838 boolean printed = false;
8839 for (int i=0; i<mForegroundProcesses.size(); i++) {
8840 ProcessRecord r = mPidsSelfLocked.get(
8841 mForegroundProcesses.valueAt(i).pid);
8842 if (dumpPackage != null && (r == null
8843 || !dumpPackage.equals(r.info.packageName))) {
8844 continue;
8845 }
8846 if (!printed) {
8847 if (needSep) pw.println(" ");
8848 needSep = true;
8849 pw.println(" Foreground Processes:");
8850 printed = true;
8851 }
8852 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8853 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 }
8857
8858 if (mPersistentStartingProcesses.size() > 0) {
8859 if (needSep) pw.println(" ");
8860 needSep = true;
8861 pw.println(" Persisent processes that are starting:");
8862 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008863 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 if (mRemovedProcesses.size() > 0) {
8867 if (needSep) pw.println(" ");
8868 needSep = true;
8869 pw.println(" Processes that are being removed:");
8870 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008871 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008872 }
8873
8874 if (mProcessesOnHold.size() > 0) {
8875 if (needSep) pw.println(" ");
8876 needSep = true;
8877 pw.println(" Processes that are on old until the system is ready:");
8878 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008879 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008882 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883
8884 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008885 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008886 long now = SystemClock.uptimeMillis();
8887 for (Map.Entry<String, SparseArray<Long>> procs
8888 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008889 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008890 SparseArray<Long> uids = procs.getValue();
8891 final int N = uids.size();
8892 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008893 int puid = uids.keyAt(i);
8894 ProcessRecord r = mProcessNames.get(pname, puid);
8895 if (dumpPackage != null && (r == null
8896 || !dumpPackage.equals(r.info.packageName))) {
8897 continue;
8898 }
8899 if (!printed) {
8900 if (needSep) pw.println(" ");
8901 needSep = true;
8902 pw.println(" Time since processes crashed:");
8903 printed = true;
8904 }
8905 pw.print(" Process "); pw.print(pname);
8906 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008907 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008908 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8909 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008910 }
8911 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008915 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008916 for (Map.Entry<String, SparseArray<Long>> procs
8917 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008918 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008919 SparseArray<Long> uids = procs.getValue();
8920 final int N = uids.size();
8921 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008922 int puid = uids.keyAt(i);
8923 ProcessRecord r = mProcessNames.get(pname, puid);
8924 if (dumpPackage != null && (r == null
8925 || !dumpPackage.equals(r.info.packageName))) {
8926 continue;
8927 }
8928 if (!printed) {
8929 if (needSep) pw.println(" ");
8930 needSep = true;
8931 pw.println(" Bad processes:");
8932 }
8933 pw.print(" Bad process "); pw.print(pname);
8934 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 pw.print(": crashed at time ");
8936 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 }
8938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008941 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008943 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008944 if (dumpAll) {
8945 StringBuilder sb = new StringBuilder(128);
8946 sb.append(" mPreviousProcessVisibleTime: ");
8947 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8948 pw.println(sb);
8949 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008950 if (mHeavyWeightProcess != null) {
8951 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8952 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008953 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008954 if (dumpAll) {
8955 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008956 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008957 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008958 for (Map.Entry<String, Integer> entry
8959 : mCompatModePackages.getPackages().entrySet()) {
8960 String pkg = entry.getKey();
8961 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008962 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8963 continue;
8964 }
8965 if (!printed) {
8966 pw.println(" mScreenCompatPackages:");
8967 printed = true;
8968 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008969 pw.print(" "); pw.print(pkg); pw.print(": ");
8970 pw.print(mode); pw.println();
8971 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008972 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008973 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07008974 if (mSleeping || mWentToSleep || mLockScreenShown) {
8975 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
8976 + " mLockScreenShown " + mLockScreenShown);
8977 }
8978 if (mShuttingDown) {
8979 pw.println(" mShuttingDown=" + mShuttingDown);
8980 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008981 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8982 || mOrigWaitForDebugger) {
8983 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8984 + " mDebugTransient=" + mDebugTransient
8985 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8986 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008987 if (mOpenGlTraceApp != null) {
8988 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008990 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8991 || mProfileFd != null) {
8992 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8993 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8994 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8995 + mAutoStopProfiler);
8996 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 if (mAlwaysFinishActivities || mController != null) {
8998 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8999 + " mController=" + mController);
9000 }
9001 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009004 + " mProcessesReady=" + mProcessesReady
9005 + " mSystemReady=" + mSystemReady);
9006 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 + " mBooted=" + mBooted
9008 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009009 pw.print(" mLastPowerCheckRealtime=");
9010 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9011 pw.println("");
9012 pw.print(" mLastPowerCheckUptime=");
9013 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9014 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009015 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9016 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009017 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009018 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9019 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009021
9022 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 }
9024
Dianne Hackborn287952c2010-09-22 22:34:31 -07009025 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009026 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009027 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009028 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009029 long now = SystemClock.uptimeMillis();
9030 for (int i=0; i<mProcessesToGc.size(); i++) {
9031 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009032 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9033 continue;
9034 }
9035 if (!printed) {
9036 if (needSep) pw.println(" ");
9037 needSep = true;
9038 pw.println(" Processes that are waiting to GC:");
9039 printed = true;
9040 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009041 pw.print(" Process "); pw.println(proc);
9042 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9043 pw.print(", last gced=");
9044 pw.print(now-proc.lastRequestedGc);
9045 pw.print(" ms ago, last lowMem=");
9046 pw.print(now-proc.lastLowMemory);
9047 pw.println(" ms ago");
9048
9049 }
9050 }
9051 return needSep;
9052 }
9053
9054 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9055 int opti, boolean dumpAll) {
9056 boolean needSep = false;
9057
9058 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009059 if (needSep) pw.println(" ");
9060 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009061 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009062 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009063 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009064 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9065 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9066 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9067 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9068 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009069 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009070 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009071 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009072 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009073 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009074 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009075
9076 if (needSep) pw.println(" ");
9077 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009078 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009079 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009081 needSep = true;
9082 }
9083
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009084 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009085
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009086 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009087 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009088 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009089 if (mHeavyWeightProcess != null) {
9090 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9091 }
9092
9093 return true;
9094 }
9095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 /**
9097 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009098 * - no provider specified: dump all the providers
9099 * - a flattened component name that matched an existing provider was specified as the
9100 * first arg: dump that one provider
9101 * - the first arg isn't the flattened component name of an existing provider:
9102 * dump all providers whose component contains the first arg as a substring
9103 */
9104 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9105 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009106 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009107 }
9108
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009109 static class ItemMatcher {
9110 ArrayList<ComponentName> components;
9111 ArrayList<String> strings;
9112 ArrayList<Integer> objects;
9113 boolean all;
9114
9115 ItemMatcher() {
9116 all = true;
9117 }
9118
9119 void build(String name) {
9120 ComponentName componentName = ComponentName.unflattenFromString(name);
9121 if (componentName != null) {
9122 if (components == null) {
9123 components = new ArrayList<ComponentName>();
9124 }
9125 components.add(componentName);
9126 all = false;
9127 } else {
9128 int objectId = 0;
9129 // Not a '/' separated full component name; maybe an object ID?
9130 try {
9131 objectId = Integer.parseInt(name, 16);
9132 if (objects == null) {
9133 objects = new ArrayList<Integer>();
9134 }
9135 objects.add(objectId);
9136 all = false;
9137 } catch (RuntimeException e) {
9138 // Not an integer; just do string match.
9139 if (strings == null) {
9140 strings = new ArrayList<String>();
9141 }
9142 strings.add(name);
9143 all = false;
9144 }
9145 }
9146 }
9147
9148 int build(String[] args, int opti) {
9149 for (; opti<args.length; opti++) {
9150 String name = args[opti];
9151 if ("--".equals(name)) {
9152 return opti+1;
9153 }
9154 build(name);
9155 }
9156 return opti;
9157 }
9158
9159 boolean match(Object object, ComponentName comp) {
9160 if (all) {
9161 return true;
9162 }
9163 if (components != null) {
9164 for (int i=0; i<components.size(); i++) {
9165 if (components.get(i).equals(comp)) {
9166 return true;
9167 }
9168 }
9169 }
9170 if (objects != null) {
9171 for (int i=0; i<objects.size(); i++) {
9172 if (System.identityHashCode(object) == objects.get(i)) {
9173 return true;
9174 }
9175 }
9176 }
9177 if (strings != null) {
9178 String flat = comp.flattenToString();
9179 for (int i=0; i<strings.size(); i++) {
9180 if (flat.contains(strings.get(i))) {
9181 return true;
9182 }
9183 }
9184 }
9185 return false;
9186 }
9187 }
9188
Dianne Hackborn625ac272010-09-17 18:29:22 -07009189 /**
9190 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009191 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009192 * - the cmd arg isn't the flattened component name of an existing activity:
9193 * dump all activity whose component contains the cmd as a substring
9194 * - A hex number of the ActivityRecord object instance.
9195 */
9196 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9197 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009198 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009199
9200 if ("all".equals(name)) {
9201 synchronized (this) {
9202 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009203 activities.add(r1);
9204 }
9205 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009206 } else if ("top".equals(name)) {
9207 synchronized (this) {
9208 final int N = mMainStack.mHistory.size();
9209 if (N > 0) {
9210 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9211 }
9212 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009213 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009214 ItemMatcher matcher = new ItemMatcher();
9215 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009216
9217 synchronized (this) {
9218 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009219 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009220 activities.add(r1);
9221 }
9222 }
9223 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009224 }
9225
9226 if (activities.size() <= 0) {
9227 return false;
9228 }
9229
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009230 String[] newArgs = new String[args.length - opti];
9231 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9232
Dianne Hackborn30d71892010-12-11 10:37:55 -08009233 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009234 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009235 for (int i=activities.size()-1; i>=0; i--) {
9236 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009237 if (needSep) {
9238 pw.println();
9239 }
9240 needSep = true;
9241 synchronized (this) {
9242 if (lastTask != r.task) {
9243 lastTask = r.task;
9244 pw.print("TASK "); pw.print(lastTask.affinity);
9245 pw.print(" id="); pw.println(lastTask.taskId);
9246 if (dumpAll) {
9247 lastTask.dump(pw, " ");
9248 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009249 }
9250 }
9251 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009252 }
9253 return true;
9254 }
9255
9256 /**
9257 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9258 * there is a thread associated with the activity.
9259 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009260 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009261 final ActivityRecord r, String[] args, boolean dumpAll) {
9262 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009263 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009264 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9265 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9266 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009267 if (r.app != null) pw.println(r.app.pid);
9268 else pw.println("(not running)");
9269 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009271 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009272 }
9273 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274 // flush anything that is already in the PrintWriter since the thread is going
9275 // to write to the file descriptor directly
9276 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009277 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009278 TransferPipe tp = new TransferPipe();
9279 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009280 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9281 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009282 tp.go(fd);
9283 } finally {
9284 tp.kill();
9285 }
9286 } catch (IOException e) {
9287 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009288 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009289 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009290 }
9291 }
9292 }
9293
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009294 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009295 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296 boolean needSep = false;
9297
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009298 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009299 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009301 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 Iterator it = mRegisteredReceivers.values().iterator();
9303 while (it.hasNext()) {
9304 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009305 if (dumpPackage != null && (r.app == null ||
9306 !dumpPackage.equals(r.app.info.packageName))) {
9307 continue;
9308 }
9309 if (!printed) {
9310 pw.println(" Registered Receivers:");
9311 needSep = true;
9312 printed = true;
9313 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009314 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 r.dump(pw, " ");
9316 }
9317 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009318
9319 if (mReceiverResolver.dump(pw, needSep ?
9320 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9321 " ", dumpPackage, false)) {
9322 needSep = true;
9323 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009324 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009325
9326 for (BroadcastQueue q : mBroadcastQueues) {
9327 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009330 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009332 if (mStickyBroadcasts != null && dumpPackage == null) {
9333 if (needSep) {
9334 pw.println();
9335 }
9336 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 pw.println(" Sticky broadcasts:");
9338 StringBuilder sb = new StringBuilder(128);
9339 for (Map.Entry<String, ArrayList<Intent>> ent
9340 : mStickyBroadcasts.entrySet()) {
9341 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009342 if (dumpAll) {
9343 pw.println(":");
9344 ArrayList<Intent> intents = ent.getValue();
9345 final int N = intents.size();
9346 for (int i=0; i<N; i++) {
9347 sb.setLength(0);
9348 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009349 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009350 pw.println(sb.toString());
9351 Bundle bundle = intents.get(i).getExtras();
9352 if (bundle != null) {
9353 pw.print(" ");
9354 pw.println(bundle.toString());
9355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009357 } else {
9358 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 }
9360 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 needSep = true;
9362 }
9363
9364 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009365 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009366 for (BroadcastQueue queue : mBroadcastQueues) {
9367 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9368 + queue.mBroadcastsScheduled);
9369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 pw.println(" mHandler:");
9371 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374
9375 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 }
9377
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009378 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009379 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009380 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009382 ItemMatcher matcher = new ItemMatcher();
9383 matcher.build(args, opti);
9384
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009385 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009386
9387 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388
9389 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009391 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009392 ContentProviderRecord r = mLaunchingProviders.get(i);
9393 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9394 continue;
9395 }
9396 if (!printed) {
9397 if (needSep) pw.println(" ");
9398 needSep = true;
9399 pw.println(" Launching content providers:");
9400 printed = true;
9401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009403 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009404 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405 }
9406
9407 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009408 if (needSep) pw.println();
9409 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009410 pw.println("Granted Uri Permissions:");
9411 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9412 int uid = mGrantedUriPermissions.keyAt(i);
9413 HashMap<Uri, UriPermission> perms
9414 = mGrantedUriPermissions.valueAt(i);
9415 pw.print(" * UID "); pw.print(uid);
9416 pw.println(" holds:");
9417 for (UriPermission perm : perms.values()) {
9418 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 if (dumpAll) {
9420 perm.dump(pw, " ");
9421 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009422 }
9423 }
9424 needSep = true;
9425 }
9426
9427 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 }
9429
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009431 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432 boolean needSep = false;
9433
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009434 if (mIntentSenderRecords.size() > 0) {
9435 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009436 Iterator<WeakReference<PendingIntentRecord>> it
9437 = mIntentSenderRecords.values().iterator();
9438 while (it.hasNext()) {
9439 WeakReference<PendingIntentRecord> ref = it.next();
9440 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009441 if (dumpPackage != null && (rec == null
9442 || !dumpPackage.equals(rec.key.packageName))) {
9443 continue;
9444 }
9445 if (!printed) {
9446 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9447 printed = true;
9448 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009449 needSep = true;
9450 if (rec != null) {
9451 pw.print(" * "); pw.println(rec);
9452 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009455 } else {
9456 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457 }
9458 }
9459 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460
9461 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462 }
9463
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009464 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009465 String prefix, String label, boolean complete, boolean brief, boolean client,
9466 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009468 boolean needNL = false;
9469 final String innerPrefix = prefix + " ";
9470 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009472 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009473 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9474 continue;
9475 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009476 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009477 if (needNL) {
9478 pw.println(" ");
9479 needNL = false;
9480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481 if (lastTask != r.task) {
9482 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009483 pw.print(prefix);
9484 pw.print(full ? "* " : " ");
9485 pw.println(lastTask);
9486 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009487 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009488 } else if (complete) {
9489 // Complete + brief == give a summary. Isn't that obvious?!?
9490 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009491 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009492 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009495 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009496 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9497 pw.print(" #"); pw.print(i); pw.print(": ");
9498 pw.println(r);
9499 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009500 r.dump(pw, innerPrefix);
9501 } else if (complete) {
9502 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009503 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009504 if (r.app != null) {
9505 pw.print(innerPrefix); pw.println(r.app);
9506 }
9507 }
9508 if (client && r.app != null && r.app.thread != null) {
9509 // flush anything that is already in the PrintWriter since the thread is going
9510 // to write to the file descriptor directly
9511 pw.flush();
9512 try {
9513 TransferPipe tp = new TransferPipe();
9514 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009515 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9516 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009517 // Short timeout, since blocking here can
9518 // deadlock with the application.
9519 tp.go(fd, 2000);
9520 } finally {
9521 tp.kill();
9522 }
9523 } catch (IOException e) {
9524 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9525 } catch (RemoteException e) {
9526 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9527 }
9528 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009530 }
9531 }
9532
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009533 private static String buildOomTag(String prefix, String space, int val, int base) {
9534 if (val == base) {
9535 if (space == null) return prefix;
9536 return prefix + " ";
9537 }
9538 return prefix + "+" + Integer.toString(val-base);
9539 }
9540
9541 private static final int dumpProcessList(PrintWriter pw,
9542 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009543 String prefix, String normalLabel, String persistentLabel,
9544 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009545 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009546 final int N = list.size()-1;
9547 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009549 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9550 continue;
9551 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009552 pw.println(String.format("%s%s #%2d: %s",
9553 prefix, (r.persistent ? persistentLabel : normalLabel),
9554 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 if (r.persistent) {
9556 numPers++;
9557 }
9558 }
9559 return numPers;
9560 }
9561
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009562 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009563 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009564 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009565 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009566
Dianne Hackborn905577f2011-09-07 18:31:28 -07009567 ArrayList<Pair<ProcessRecord, Integer>> list
9568 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9569 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009570 ProcessRecord r = origList.get(i);
9571 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9572 continue;
9573 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009574 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9575 }
9576
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009577 if (list.size() <= 0) {
9578 return false;
9579 }
9580
Dianne Hackborn905577f2011-09-07 18:31:28 -07009581 Comparator<Pair<ProcessRecord, Integer>> comparator
9582 = new Comparator<Pair<ProcessRecord, Integer>>() {
9583 @Override
9584 public int compare(Pair<ProcessRecord, Integer> object1,
9585 Pair<ProcessRecord, Integer> object2) {
9586 if (object1.first.setAdj != object2.first.setAdj) {
9587 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9588 }
9589 if (object1.second.intValue() != object2.second.intValue()) {
9590 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9591 }
9592 return 0;
9593 }
9594 };
9595
9596 Collections.sort(list, comparator);
9597
Dianne Hackborn287952c2010-09-22 22:34:31 -07009598 final long curRealtime = SystemClock.elapsedRealtime();
9599 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9600 final long curUptime = SystemClock.uptimeMillis();
9601 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9602
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009603 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009604 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009605 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009606 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009607 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009608 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9609 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009610 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9611 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009612 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9613 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009614 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9615 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009616 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009617 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009618 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9619 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9620 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9621 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9622 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9623 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9624 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9625 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009626 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9627 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009628 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9629 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009630 } else {
9631 oomAdj = Integer.toString(r.setAdj);
9632 }
9633 String schedGroup;
9634 switch (r.setSchedGroup) {
9635 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9636 schedGroup = "B";
9637 break;
9638 case Process.THREAD_GROUP_DEFAULT:
9639 schedGroup = "F";
9640 break;
9641 default:
9642 schedGroup = Integer.toString(r.setSchedGroup);
9643 break;
9644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009645 String foreground;
9646 if (r.foregroundActivities) {
9647 foreground = "A";
9648 } else if (r.foregroundServices) {
9649 foreground = "S";
9650 } else {
9651 foreground = " ";
9652 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009653 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009654 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009655 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9656 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009657 if (r.adjSource != null || r.adjTarget != null) {
9658 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009659 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009660 if (r.adjTarget instanceof ComponentName) {
9661 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9662 } else if (r.adjTarget != null) {
9663 pw.print(r.adjTarget.toString());
9664 } else {
9665 pw.print("{null}");
9666 }
9667 pw.print("<=");
9668 if (r.adjSource instanceof ProcessRecord) {
9669 pw.print("Proc{");
9670 pw.print(((ProcessRecord)r.adjSource).toShortString());
9671 pw.println("}");
9672 } else if (r.adjSource != null) {
9673 pw.println(r.adjSource.toString());
9674 } else {
9675 pw.println("{null}");
9676 }
9677 }
9678 if (inclDetails) {
9679 pw.print(prefix);
9680 pw.print(" ");
9681 pw.print("oom: max="); pw.print(r.maxAdj);
9682 pw.print(" hidden="); pw.print(r.hiddenAdj);
9683 pw.print(" curRaw="); pw.print(r.curRawAdj);
9684 pw.print(" setRaw="); pw.print(r.setRawAdj);
9685 pw.print(" cur="); pw.print(r.curAdj);
9686 pw.print(" set="); pw.println(r.setAdj);
9687 pw.print(prefix);
9688 pw.print(" ");
9689 pw.print("keeping="); pw.print(r.keeping);
9690 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009691 pw.print(" empty="); pw.print(r.empty);
9692 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009693
9694 if (!r.keeping) {
9695 if (r.lastWakeTime != 0) {
9696 long wtime;
9697 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9698 synchronized (stats) {
9699 wtime = stats.getProcessWakeTime(r.info.uid,
9700 r.pid, curRealtime);
9701 }
9702 long timeUsed = wtime - r.lastWakeTime;
9703 pw.print(prefix);
9704 pw.print(" ");
9705 pw.print("keep awake over ");
9706 TimeUtils.formatDuration(realtimeSince, pw);
9707 pw.print(" used ");
9708 TimeUtils.formatDuration(timeUsed, pw);
9709 pw.print(" (");
9710 pw.print((timeUsed*100)/realtimeSince);
9711 pw.println("%)");
9712 }
9713 if (r.lastCpuTime != 0) {
9714 long timeUsed = r.curCpuTime - r.lastCpuTime;
9715 pw.print(prefix);
9716 pw.print(" ");
9717 pw.print("run cpu over ");
9718 TimeUtils.formatDuration(uptimeSince, pw);
9719 pw.print(" used ");
9720 TimeUtils.formatDuration(timeUsed, pw);
9721 pw.print(" (");
9722 pw.print((timeUsed*100)/uptimeSince);
9723 pw.println("%)");
9724 }
9725 }
9726 }
9727 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009728 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009729 }
9730
Dianne Hackbornb437e092011-08-05 17:50:29 -07009731 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009732 ArrayList<ProcessRecord> procs;
9733 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009734 if (args != null && args.length > start
9735 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009736 procs = new ArrayList<ProcessRecord>();
9737 int pid = -1;
9738 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009739 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009740 } catch (NumberFormatException e) {
9741
9742 }
9743 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9744 ProcessRecord proc = mLruProcesses.get(i);
9745 if (proc.pid == pid) {
9746 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009747 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009748 procs.add(proc);
9749 }
9750 }
9751 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009752 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009753 return null;
9754 }
9755 } else {
9756 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9757 }
9758 }
9759 return procs;
9760 }
9761
9762 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9763 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009764 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 if (procs == null) {
9766 return;
9767 }
9768
9769 long uptime = SystemClock.uptimeMillis();
9770 long realtime = SystemClock.elapsedRealtime();
9771 pw.println("Applications Graphics Acceleration Info:");
9772 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9773
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009774 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9775 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009776 if (r.thread != null) {
9777 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9778 pw.flush();
9779 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009780 TransferPipe tp = new TransferPipe();
9781 try {
9782 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9783 tp.go(fd);
9784 } finally {
9785 tp.kill();
9786 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009787 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009788 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009789 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009790 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009791 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009792 pw.flush();
9793 }
9794 }
9795 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009796 }
9797
Jeff Brown6754ba22011-12-14 20:20:01 -08009798 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9799 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9800 if (procs == null) {
9801 return;
9802 }
9803
9804 pw.println("Applications Database Info:");
9805
9806 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9807 ProcessRecord r = procs.get(i);
9808 if (r.thread != null) {
9809 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9810 pw.flush();
9811 try {
9812 TransferPipe tp = new TransferPipe();
9813 try {
9814 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9815 tp.go(fd);
9816 } finally {
9817 tp.kill();
9818 }
9819 } catch (IOException e) {
9820 pw.println("Failure while dumping the app: " + r);
9821 pw.flush();
9822 } catch (RemoteException e) {
9823 pw.println("Got a RemoteException while dumping the app " + r);
9824 pw.flush();
9825 }
9826 }
9827 }
9828 }
9829
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009830 final static class MemItem {
9831 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009832 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009833 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009834 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009835 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009836
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009837 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009838 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009839 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009840 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009841 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009842 }
9843 }
9844
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009845 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009846 boolean sort) {
9847 if (sort) {
9848 Collections.sort(items, new Comparator<MemItem>() {
9849 @Override
9850 public int compare(MemItem lhs, MemItem rhs) {
9851 if (lhs.pss < rhs.pss) {
9852 return 1;
9853 } else if (lhs.pss > rhs.pss) {
9854 return -1;
9855 }
9856 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009857 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009858 });
9859 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009860
9861 for (int i=0; i<items.size(); i++) {
9862 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009863 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009864 if (mi.subitems != null) {
9865 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9866 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009867 }
9868 }
9869
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009870 // These are in KB.
9871 static final long[] DUMP_MEM_BUCKETS = new long[] {
9872 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9873 120*1024, 160*1024, 200*1024,
9874 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9875 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9876 };
9877
Dianne Hackborn672342c2011-11-29 11:29:02 -08009878 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9879 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009880 int start = label.lastIndexOf('.');
9881 if (start >= 0) start++;
9882 else start = 0;
9883 int end = label.length();
9884 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9885 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9886 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9887 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009888 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009889 out.append(label, start, end);
9890 return;
9891 }
9892 }
9893 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009894 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009895 out.append(label, start, end);
9896 }
9897
9898 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9899 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9900 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9901 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9902 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9903 };
9904 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9905 "System", "Persistent", "Foreground",
9906 "Visible", "Perceptible", "Heavy Weight",
9907 "Backup", "A Services", "Home", "Previous",
9908 "B Services", "Background"
9909 };
9910
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009911 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009912 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009913 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009914 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009915 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009916
9917 int opti = 0;
9918 while (opti < args.length) {
9919 String opt = args[opti];
9920 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9921 break;
9922 }
9923 opti++;
9924 if ("-a".equals(opt)) {
9925 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009926 } else if ("--oom".equals(opt)) {
9927 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009928 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009929 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009930 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009931 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009932 pw.println("If [process] is specified it can be the name or ");
9933 pw.println("pid of a specific process to dump.");
9934 return;
9935 } else {
9936 pw.println("Unknown argument: " + opt + "; use -h for help");
9937 }
9938 }
9939
9940 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009941 if (procs == null) {
9942 return;
9943 }
9944
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009945 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009946 long uptime = SystemClock.uptimeMillis();
9947 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009948
9949 if (procs.size() == 1 || isCheckinRequest) {
9950 dumpAll = true;
9951 }
9952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009953 if (isCheckinRequest) {
9954 // short checkin version
9955 pw.println(uptime + "," + realtime);
9956 pw.flush();
9957 } else {
9958 pw.println("Applications Memory Usage (kB):");
9959 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9960 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009961
Dianne Hackbornb437e092011-08-05 17:50:29 -07009962 String[] innerArgs = new String[args.length-opti];
9963 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9964
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009965 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9966 long nativePss=0, dalvikPss=0, otherPss=0;
9967 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9968
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9970 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9971 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009972
9973 long totalPss = 0;
9974
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009975 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9976 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009977 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009978 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9980 pw.flush();
9981 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009982 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009983 if (dumpAll) {
9984 try {
9985 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9986 } catch (RemoteException e) {
9987 if (!isCheckinRequest) {
9988 pw.println("Got RemoteException!");
9989 pw.flush();
9990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009992 } else {
9993 mi = new Debug.MemoryInfo();
9994 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009995 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009996
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009997 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009998 long myTotalPss = mi.getTotalPss();
9999 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010000 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010001 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010002 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010003
10004 nativePss += mi.nativePss;
10005 dalvikPss += mi.dalvikPss;
10006 otherPss += mi.otherPss;
10007 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10008 long mem = mi.getOtherPss(j);
10009 miscPss[j] += mem;
10010 otherPss -= mem;
10011 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010012
10013 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010014 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10015 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010016 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010017 if (oomProcs[oomIndex] == null) {
10018 oomProcs[oomIndex] = new ArrayList<MemItem>();
10019 }
10020 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010021 break;
10022 }
10023 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010025 }
10026 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010027
10028 if (!isCheckinRequest && procs.size() > 1) {
10029 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10030
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010031 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10032 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10033 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010034 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010035 String label = Debug.MemoryInfo.getOtherLabel(j);
10036 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010037 }
10038
Dianne Hackbornb437e092011-08-05 17:50:29 -070010039 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10040 for (int j=0; j<oomPss.length; j++) {
10041 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010042 String label = DUMP_MEM_OOM_LABEL[j];
10043 MemItem item = new MemItem(label, label, oomPss[j],
10044 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010045 item.subitems = oomProcs[j];
10046 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010047 }
10048 }
10049
Dianne Hackborn672342c2011-11-29 11:29:02 -080010050 if (outTag != null || outStack != null) {
10051 if (outTag != null) {
10052 appendMemBucket(outTag, totalPss, "total", false);
10053 }
10054 if (outStack != null) {
10055 appendMemBucket(outStack, totalPss, "total", true);
10056 }
10057 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010058 for (int i=0; i<oomMems.size(); i++) {
10059 MemItem miCat = oomMems.get(i);
10060 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10061 continue;
10062 }
10063 if (miCat.id < ProcessList.SERVICE_ADJ
10064 || miCat.id == ProcessList.HOME_APP_ADJ
10065 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010066 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10067 outTag.append(" / ");
10068 }
10069 if (outStack != null) {
10070 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10071 if (firstLine) {
10072 outStack.append(":");
10073 firstLine = false;
10074 }
10075 outStack.append("\n\t at ");
10076 } else {
10077 outStack.append("$");
10078 }
10079 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010080 for (int j=0; j<miCat.subitems.size(); j++) {
10081 MemItem mi = miCat.subitems.get(j);
10082 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010083 if (outTag != null) {
10084 outTag.append(" ");
10085 }
10086 if (outStack != null) {
10087 outStack.append("$");
10088 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010089 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010090 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10091 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10092 }
10093 if (outStack != null) {
10094 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10095 }
10096 }
10097 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10098 outStack.append("(");
10099 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10100 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10101 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10102 outStack.append(":");
10103 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10104 }
10105 }
10106 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010107 }
10108 }
10109 }
10110 }
10111
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010112 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010113 pw.println();
10114 pw.println("Total PSS by process:");
10115 dumpMemItems(pw, " ", procMems, true);
10116 pw.println();
10117 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118 pw.println("Total PSS by OOM adjustment:");
10119 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010120 if (!oomOnly) {
10121 PrintWriter out = categoryPw != null ? categoryPw : pw;
10122 out.println();
10123 out.println("Total PSS by category:");
10124 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010125 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010127 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010128 final int[] SINGLE_LONG_FORMAT = new int[] {
10129 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10130 };
10131 long[] longOut = new long[1];
10132 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10133 SINGLE_LONG_FORMAT, null, longOut, null);
10134 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10135 longOut[0] = 0;
10136 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10137 SINGLE_LONG_FORMAT, null, longOut, null);
10138 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10139 longOut[0] = 0;
10140 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10141 SINGLE_LONG_FORMAT, null, longOut, null);
10142 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10143 longOut[0] = 0;
10144 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10145 SINGLE_LONG_FORMAT, null, longOut, null);
10146 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10147 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10148 pw.print(shared); pw.println(" kB");
10149 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10150 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010152 }
10153
10154 /**
10155 * Searches array of arguments for the specified string
10156 * @param args array of argument strings
10157 * @param value value to search for
10158 * @return true if the value is contained in the array
10159 */
10160 private static boolean scanArgs(String[] args, String value) {
10161 if (args != null) {
10162 for (String arg : args) {
10163 if (value.equals(arg)) {
10164 return true;
10165 }
10166 }
10167 }
10168 return false;
10169 }
10170
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010171 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10172 ContentProviderRecord cpr, boolean always) {
10173 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10174
10175 if (!inLaunching || always) {
10176 synchronized (cpr) {
10177 cpr.launchingApp = null;
10178 cpr.notifyAll();
10179 }
10180 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
10181 String names[] = cpr.info.authority.split(";");
10182 for (int j = 0; j < names.length; j++) {
10183 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184 }
10185 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010186
10187 for (int i=0; i<cpr.connections.size(); i++) {
10188 ContentProviderConnection conn = cpr.connections.get(i);
10189 if (conn.waiting) {
10190 // If this connection is waiting for the provider, then we don't
10191 // need to mess with its process unless we are always removing
10192 // or for some reason the provider is not currently launching.
10193 if (inLaunching && !always) {
10194 continue;
10195 }
10196 }
10197 ProcessRecord capp = conn.client;
10198 conn.dead = true;
10199 if (conn.stableCount > 0) {
10200 if (!capp.persistent && capp.thread != null
10201 && capp.pid != 0
10202 && capp.pid != MY_PID) {
10203 Slog.i(TAG, "Kill " + capp.processName
10204 + " (pid " + capp.pid + "): provider " + cpr.info.name
10205 + " in dying process " + (proc != null ? proc.processName : "??"));
10206 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10207 capp.processName, capp.setAdj, "dying provider "
10208 + cpr.name.toShortString());
10209 Process.killProcessQuiet(capp.pid);
10210 }
10211 } else if (capp.thread != null && conn.provider.provider != null) {
10212 try {
10213 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10214 } catch (RemoteException e) {
10215 }
10216 // In the protocol here, we don't expect the client to correctly
10217 // clean up this connection, we'll just remove it.
10218 cpr.connections.remove(i);
10219 conn.client.conProviders.remove(conn);
10220 }
10221 }
10222
10223 if (inLaunching && always) {
10224 mLaunchingProviders.remove(cpr);
10225 }
10226 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010227 }
10228
10229 /**
10230 * Main code for cleaning up a process when it has gone away. This is
10231 * called both as a result of the process dying, or directly when stopping
10232 * a process when running in single process mode.
10233 */
10234 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010235 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010236 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010237 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 }
10239
Dianne Hackborn36124872009-10-08 16:22:03 -070010240 mProcessesToGc.remove(app);
10241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 // Dismiss any open dialogs.
10243 if (app.crashDialog != null) {
10244 app.crashDialog.dismiss();
10245 app.crashDialog = null;
10246 }
10247 if (app.anrDialog != null) {
10248 app.anrDialog.dismiss();
10249 app.anrDialog = null;
10250 }
10251 if (app.waitDialog != null) {
10252 app.waitDialog.dismiss();
10253 app.waitDialog = null;
10254 }
10255
10256 app.crashing = false;
10257 app.notResponding = false;
10258
10259 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010260 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 app.thread = null;
10262 app.forcingToForeground = null;
10263 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010264 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010265 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010266 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010267
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010268 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010269
10270 boolean restart = false;
10271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010272 // Remove published content providers.
10273 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010274 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010275 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010276 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010277
10278 final boolean always = app.bad || !allowRestart;
10279 if (removeDyingProviderLocked(app, cpr, always) || always) {
10280 // We left the provider in the launching list, need to
10281 // restart it.
10282 restart = true;
10283 }
10284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010286 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010287 }
10288 app.pubProviders.clear();
10289 }
10290
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010291 // Take care of any launching providers waiting for this process.
10292 if (checkAppInLaunchingProvidersLocked(app, false)) {
10293 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 // Unregister from connected content providers.
10297 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010298 for (int i=0; i<app.conProviders.size(); i++) {
10299 ContentProviderConnection conn = app.conProviders.get(i);
10300 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010301 }
10302 app.conProviders.clear();
10303 }
10304
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010305 // At this point there may be remaining entries in mLaunchingProviders
10306 // where we were the only one waiting, so they are no longer of use.
10307 // Look for these and clean up if found.
10308 // XXX Commented out for now. Trying to figure out a way to reproduce
10309 // the actual situation to identify what is actually going on.
10310 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010311 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010312 ContentProviderRecord cpr = (ContentProviderRecord)
10313 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010314 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010315 synchronized (cpr) {
10316 cpr.launchingApp = null;
10317 cpr.notifyAll();
10318 }
10319 }
10320 }
10321 }
10322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 skipCurrentReceiverLocked(app);
10324
10325 // Unregister any receivers.
10326 if (app.receivers.size() > 0) {
10327 Iterator<ReceiverList> it = app.receivers.iterator();
10328 while (it.hasNext()) {
10329 removeReceiverLocked(it.next());
10330 }
10331 app.receivers.clear();
10332 }
10333
Christopher Tate181fafa2009-05-14 11:12:14 -070010334 // If the app is undergoing backup, tell the backup manager about it
10335 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010336 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010337 try {
10338 IBackupManager bm = IBackupManager.Stub.asInterface(
10339 ServiceManager.getService(Context.BACKUP_SERVICE));
10340 bm.agentDisconnected(app.info.packageName);
10341 } catch (RemoteException e) {
10342 // can't happen; backup manager is local
10343 }
10344 }
10345
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010346 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10347 ProcessChangeItem item = mPendingProcessChanges.get(i);
10348 if (item.pid == app.pid) {
10349 mPendingProcessChanges.remove(i);
10350 mAvailProcessChanges.add(item);
10351 }
10352 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010353 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010355 // If the caller is restarting this app, then leave it in its
10356 // current lists and let the caller take care of it.
10357 if (restarting) {
10358 return;
10359 }
10360
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010361 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010362 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010364 mProcessNames.remove(app.processName, app.uid);
10365 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010366 if (mHeavyWeightProcess == app) {
10367 mHeavyWeightProcess = null;
10368 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010370 } else if (!app.removed) {
10371 // This app is persistent, so we need to keep its record around.
10372 // If it is not already on the pending app list, add it there
10373 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10375 mPersistentStartingProcesses.add(app);
10376 restart = true;
10377 }
10378 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010379 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10380 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 mProcessesOnHold.remove(app);
10382
The Android Open Source Project4df24232009-03-05 14:34:35 -080010383 if (app == mHomeProcess) {
10384 mHomeProcess = null;
10385 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010386 if (app == mPreviousProcess) {
10387 mPreviousProcess = null;
10388 }
10389
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010390 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010391 // We have components that still need to be running in the
10392 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010393 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 startProcessLocked(app, "restart", app.processName);
10395 } else if (app.pid > 0 && app.pid != MY_PID) {
10396 // Goodbye!
10397 synchronized (mPidsSelfLocked) {
10398 mPidsSelfLocked.remove(app.pid);
10399 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10400 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010401 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010402 }
10403 }
10404
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010405 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10406 // Look through the content providers we are waiting to have launched,
10407 // and if any run in this process then either schedule a restart of
10408 // the process or kill the client waiting for it if this process has
10409 // gone bad.
10410 int NL = mLaunchingProviders.size();
10411 boolean restart = false;
10412 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010413 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010414 if (cpr.launchingApp == app) {
10415 if (!alwaysBad && !app.bad) {
10416 restart = true;
10417 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010418 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010419 NL = mLaunchingProviders.size();
10420 }
10421 }
10422 }
10423 return restart;
10424 }
10425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 // =========================================================
10427 // SERVICES
10428 // =========================================================
10429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10431 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010432 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010433 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010434 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010435 }
10436 }
10437
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010438 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010439 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010440 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010441 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010442 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010443 }
10444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 public ComponentName startService(IApplicationThread caller, Intent service,
10446 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010447 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010448 // Refuse possible leaked file descriptors
10449 if (service != null && service.hasFileDescriptors() == true) {
10450 throw new IllegalArgumentException("File descriptors passed in Intent");
10451 }
10452
Amith Yamasani742a6712011-05-04 14:49:28 -070010453 if (DEBUG_SERVICE)
10454 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 synchronized(this) {
10456 final int callingPid = Binder.getCallingPid();
10457 final int callingUid = Binder.getCallingUid();
10458 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010459 ComponentName res = mServices.startServiceLocked(caller, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 resolvedType, callingPid, callingUid);
10461 Binder.restoreCallingIdentity(origId);
10462 return res;
10463 }
10464 }
10465
10466 ComponentName startServiceInPackage(int uid,
10467 Intent service, String resolvedType) {
10468 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010469 if (DEBUG_SERVICE)
10470 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010471 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010472 ComponentName res = mServices.startServiceLocked(null, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 resolvedType, -1, uid);
10474 Binder.restoreCallingIdentity(origId);
10475 return res;
10476 }
10477 }
10478
10479 public int stopService(IApplicationThread caller, Intent service,
10480 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010481 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010482 // Refuse possible leaked file descriptors
10483 if (service != null && service.hasFileDescriptors() == true) {
10484 throw new IllegalArgumentException("File descriptors passed in Intent");
10485 }
10486
10487 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010488 return mServices.stopServiceLocked(caller, service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010490 }
10491
10492 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010493 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 // Refuse possible leaked file descriptors
10495 if (service != null && service.hasFileDescriptors() == true) {
10496 throw new IllegalArgumentException("File descriptors passed in Intent");
10497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010499 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010501 }
10502
10503 public boolean stopServiceToken(ComponentName className, IBinder token,
10504 int startId) {
10505 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010506 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010508 }
10509
10510 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010511 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010512 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010513 mServices.setServiceForegroundLocked(className, token, id, notification,
10514 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010515 }
10516 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010517
10518 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
10519 boolean result = false;
10520 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
10521 result = false;
10522 } else if (componentProcessName == aInfo.packageName) {
10523 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10524 } else if ("system".equals(componentProcessName)) {
10525 result = true;
10526 }
10527 if (DEBUG_MU) {
10528 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
10529 }
10530 return result;
10531 }
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 public int bindService(IApplicationThread caller, IBinder token,
10534 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010535 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010536 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 // Refuse possible leaked file descriptors
10538 if (service != null && service.hasFileDescriptors() == true) {
10539 throw new IllegalArgumentException("File descriptors passed in Intent");
10540 }
10541
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010542 checkValidCaller(Binder.getCallingUid(), userId);
10543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010545 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10546 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547 }
10548 }
10549
10550 public boolean unbindService(IServiceConnection connection) {
10551 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010552 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010554 }
10555
10556 public void publishService(IBinder token, Intent intent, IBinder service) {
10557 // Refuse possible leaked file descriptors
10558 if (intent != null && intent.hasFileDescriptors() == true) {
10559 throw new IllegalArgumentException("File descriptors passed in Intent");
10560 }
10561
10562 synchronized(this) {
10563 if (!(token instanceof ServiceRecord)) {
10564 throw new IllegalArgumentException("Invalid service token");
10565 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010566 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 }
10568 }
10569
10570 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10571 // Refuse possible leaked file descriptors
10572 if (intent != null && intent.hasFileDescriptors() == true) {
10573 throw new IllegalArgumentException("File descriptors passed in Intent");
10574 }
10575
10576 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010577 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 }
10579 }
10580
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010581 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 synchronized(this) {
10583 if (!(token instanceof ServiceRecord)) {
10584 throw new IllegalArgumentException("Invalid service token");
10585 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010586 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 }
10589
10590 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010591 // BACKUP AND RESTORE
10592 // =========================================================
10593
10594 // Cause the target app to be launched if necessary and its backup agent
10595 // instantiated. The backup agent will invoke backupAgentCreated() on the
10596 // activity manager to announce its creation.
10597 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010598 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010599 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10600
10601 synchronized(this) {
10602 // !!! TODO: currently no check here that we're already bound
10603 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10604 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10605 synchronized (stats) {
10606 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10607 }
10608
Dianne Hackborne7f97212011-02-24 14:40:20 -080010609 // Backup agent is now in use, its package can't be stopped.
10610 try {
10611 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010612 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010613 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010614 } catch (IllegalArgumentException e) {
10615 Slog.w(TAG, "Failed trying to unstop package "
10616 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010617 }
10618
Christopher Tate181fafa2009-05-14 11:12:14 -070010619 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010620 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10621 ? new ComponentName(app.packageName, app.backupAgentName)
10622 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010623 // startProcessLocked() returns existing proc's record if it's already running
10624 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010625 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010626 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010627 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010628 return false;
10629 }
10630
10631 r.app = proc;
10632 mBackupTarget = r;
10633 mBackupAppName = app.packageName;
10634
Christopher Tate6fa95972009-06-05 18:43:55 -070010635 // Try not to kill the process during backup
10636 updateOomAdjLocked(proc);
10637
Christopher Tate181fafa2009-05-14 11:12:14 -070010638 // If the process is already attached, schedule the creation of the backup agent now.
10639 // If it is not yet live, this will be done when it attaches to the framework.
10640 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010641 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010642 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010643 proc.thread.scheduleCreateBackupAgent(app,
10644 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010645 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010646 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010647 }
10648 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010649 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010650 }
10651 // Invariants: at this point, the target app process exists and the application
10652 // is either already running or in the process of coming up. mBackupTarget and
10653 // mBackupAppName describe the app, so that when it binds back to the AM we
10654 // know that it's scheduled for a backup-agent operation.
10655 }
10656
10657 return true;
10658 }
10659
10660 // A backup agent has just come up
10661 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010662 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010663 + " = " + agent);
10664
10665 synchronized(this) {
10666 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010667 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010668 return;
10669 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010670 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010671
Dianne Hackborn06740692010-09-22 22:46:21 -070010672 long oldIdent = Binder.clearCallingIdentity();
10673 try {
10674 IBackupManager bm = IBackupManager.Stub.asInterface(
10675 ServiceManager.getService(Context.BACKUP_SERVICE));
10676 bm.agentConnected(agentPackageName, agent);
10677 } catch (RemoteException e) {
10678 // can't happen; the backup manager service is local
10679 } catch (Exception e) {
10680 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10681 e.printStackTrace();
10682 } finally {
10683 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010684 }
10685 }
10686
10687 // done with this agent
10688 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010689 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010690 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010691 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010692 return;
10693 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010694
10695 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010696 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010697 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010698 return;
10699 }
10700
Christopher Tate181fafa2009-05-14 11:12:14 -070010701 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010702 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010703 return;
10704 }
10705
Christopher Tate6fa95972009-06-05 18:43:55 -070010706 ProcessRecord proc = mBackupTarget.app;
10707 mBackupTarget = null;
10708 mBackupAppName = null;
10709
10710 // Not backing this app up any more; reset its OOM adjustment
10711 updateOomAdjLocked(proc);
10712
Christopher Tatec7b31e32009-06-10 15:49:30 -070010713 // If the app crashed during backup, 'thread' will be null here
10714 if (proc.thread != null) {
10715 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010716 proc.thread.scheduleDestroyBackupAgent(appInfo,
10717 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010718 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010719 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010720 e.printStackTrace();
10721 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010722 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010723 }
10724 }
10725 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 // BROADCASTS
10727 // =========================================================
10728
Josh Bartel7f208742010-02-25 11:01:44 -060010729 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010730 List cur) {
10731 final ContentResolver resolver = mContext.getContentResolver();
10732 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10733 if (list == null) {
10734 return cur;
10735 }
10736 int N = list.size();
10737 for (int i=0; i<N; i++) {
10738 Intent intent = list.get(i);
10739 if (filter.match(resolver, intent, true, TAG) >= 0) {
10740 if (cur == null) {
10741 cur = new ArrayList<Intent>();
10742 }
10743 cur.add(intent);
10744 }
10745 }
10746 return cur;
10747 }
10748
Christopher Tatef46723b2012-01-26 14:19:24 -080010749 boolean isPendingBroadcastProcessLocked(int pid) {
10750 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
10751 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
10752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753
Christopher Tatef46723b2012-01-26 14:19:24 -080010754 void skipPendingBroadcastLocked(int pid) {
10755 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
10756 for (BroadcastQueue queue : mBroadcastQueues) {
10757 queue.skipPendingBroadcastLocked(pid);
10758 }
10759 }
10760
10761 // The app just attached; send any pending broadcasts that it should receive
10762 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
10763 boolean didSomething = false;
10764 for (BroadcastQueue queue : mBroadcastQueues) {
10765 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010767 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 }
10769
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010770 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010772 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010773 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 synchronized(this) {
10775 ProcessRecord callerApp = null;
10776 if (caller != null) {
10777 callerApp = getRecordForAppLocked(caller);
10778 if (callerApp == null) {
10779 throw new SecurityException(
10780 "Unable to find app for caller " + caller
10781 + " (pid=" + Binder.getCallingPid()
10782 + ") when registering receiver " + receiver);
10783 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010784 if (callerApp.info.uid != Process.SYSTEM_UID &&
10785 !callerApp.pkgList.contains(callerPackage)) {
10786 throw new SecurityException("Given caller package " + callerPackage
10787 + " is not running in process " + callerApp);
10788 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010789 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010790 } else {
10791 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010792 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 }
10794
10795 List allSticky = null;
10796
10797 // Look for any matching sticky broadcasts...
10798 Iterator actions = filter.actionsIterator();
10799 if (actions != null) {
10800 while (actions.hasNext()) {
10801 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010802 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 }
10804 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010805 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 }
10807
10808 // The first sticky in the list is returned directly back to
10809 // the client.
10810 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10811
Joe Onorato8a9b2202010-02-26 18:56:32 -080010812 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 + ": " + sticky);
10814
10815 if (receiver == null) {
10816 return sticky;
10817 }
10818
10819 ReceiverList rl
10820 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10821 if (rl == null) {
10822 rl = new ReceiverList(this, callerApp,
10823 Binder.getCallingPid(),
10824 Binder.getCallingUid(), receiver);
10825 if (rl.app != null) {
10826 rl.app.receivers.add(rl);
10827 } else {
10828 try {
10829 receiver.asBinder().linkToDeath(rl, 0);
10830 } catch (RemoteException e) {
10831 return sticky;
10832 }
10833 rl.linkedToDeath = true;
10834 }
10835 mRegisteredReceivers.put(receiver.asBinder(), rl);
10836 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010837 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
10838 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 rl.add(bf);
10840 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010841 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 }
10843 mReceiverResolver.addFilter(bf);
10844
10845 // Enqueue broadcasts for all existing stickies that match
10846 // this filter.
10847 if (allSticky != null) {
10848 ArrayList receivers = new ArrayList();
10849 receivers.add(bf);
10850
10851 int N = allSticky.size();
10852 for (int i=0; i<N; i++) {
10853 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080010854 BroadcastQueue queue = broadcastQueueForIntent(intent);
10855 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010857 false, true, true, false);
Christopher Tatef46723b2012-01-26 14:19:24 -080010858 queue.enqueueParallelBroadcastLocked(r);
10859 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 }
10861 }
10862
10863 return sticky;
10864 }
10865 }
10866
10867 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010868 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869
Christopher Tatef46723b2012-01-26 14:19:24 -080010870 final long origId = Binder.clearCallingIdentity();
10871 try {
10872 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873
Christopher Tatef46723b2012-01-26 14:19:24 -080010874 synchronized(this) {
10875 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080010877 if (rl != null) {
10878 if (rl.curBroadcast != null) {
10879 BroadcastRecord r = rl.curBroadcast;
10880 final boolean doNext = finishReceiverLocked(
10881 receiver.asBinder(), r.resultCode, r.resultData,
10882 r.resultExtras, r.resultAbort, true);
10883 if (doNext) {
10884 doTrim = true;
10885 r.queue.processNextBroadcast(false);
10886 }
10887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888
Christopher Tatef46723b2012-01-26 14:19:24 -080010889 if (rl.app != null) {
10890 rl.app.receivers.remove(rl);
10891 }
10892 removeReceiverLocked(rl);
10893 if (rl.linkedToDeath) {
10894 rl.linkedToDeath = false;
10895 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 }
10898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899
Christopher Tatef46723b2012-01-26 14:19:24 -080010900 // If we actually concluded any broadcasts, we might now be able
10901 // to trim the recipients' apps from our working set
10902 if (doTrim) {
10903 trimApplications();
10904 return;
10905 }
10906
10907 } finally {
10908 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 }
10911
10912 void removeReceiverLocked(ReceiverList rl) {
10913 mRegisteredReceivers.remove(rl.receiver.asBinder());
10914 int N = rl.size();
10915 for (int i=0; i<N; i++) {
10916 mReceiverResolver.removeFilter(rl.get(i));
10917 }
10918 }
10919
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010920 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
10921 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10922 ProcessRecord r = mLruProcesses.get(i);
10923 if (r.thread != null) {
10924 try {
10925 r.thread.dispatchPackageBroadcast(cmd, packages);
10926 } catch (RemoteException ex) {
10927 }
10928 }
10929 }
10930 }
10931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932 private final int broadcastIntentLocked(ProcessRecord callerApp,
10933 String callerPackage, Intent intent, String resolvedType,
10934 IIntentReceiver resultTo, int resultCode, String resultData,
10935 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070010936 boolean ordered, boolean sticky, int callingPid, int callingUid,
10937 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 intent = new Intent(intent);
10939
Dianne Hackborne7f97212011-02-24 14:40:20 -080010940 // By default broadcasts do not go to stopped apps.
10941 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
10942
Joe Onorato8a9b2202010-02-26 18:56:32 -080010943 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070010945 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010946 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010947 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010949
10950 boolean onlySendToCaller = false;
10951
10952 // If the caller is trying to send this broadcast to a different
10953 // user, verify that is allowed.
10954 if (UserId.getUserId(callingUid) != userId) {
10955 if (checkComponentPermission(
10956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10957 callingPid, callingUid, -1, true)
10958 != PackageManager.PERMISSION_GRANTED) {
10959 if (checkComponentPermission(
10960 android.Manifest.permission.INTERACT_ACROSS_USERS,
10961 callingPid, callingUid, -1, true)
10962 == PackageManager.PERMISSION_GRANTED) {
10963 onlySendToCaller = true;
10964 } else {
10965 String msg = "Permission Denial: " + intent.getAction()
10966 + " broadcast from " + callerPackage
10967 + " asks to send as user " + userId
10968 + " but is calling from user " + UserId.getUserId(callingUid)
10969 + "; this requires "
10970 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10971 Slog.w(TAG, msg);
10972 throw new SecurityException(msg);
10973 }
10974 }
10975 }
10976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 // Handle special intents: if this broadcast is from the package
10978 // manager about a package being removed, we need to remove all of
10979 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070010980 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070010982 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
10983 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010984 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 || uidRemoved) {
10986 if (checkComponentPermission(
10987 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010988 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010989 == PackageManager.PERMISSION_GRANTED) {
10990 if (uidRemoved) {
10991 final Bundle intentExtras = intent.getExtras();
10992 final int uid = intentExtras != null
10993 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
10994 if (uid >= 0) {
10995 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
10996 synchronized (bs) {
10997 bs.removeUidStatsLocked(uid);
10998 }
10999 }
11000 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011001 // If resources are unvailble just force stop all
11002 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011003 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011004 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11005 if (list != null && (list.length > 0)) {
11006 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011007 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011008 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011009 sendPackageBroadcastLocked(
11010 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011011 }
11012 } else {
11013 Uri data = intent.getData();
11014 String ssp;
11015 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11016 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11017 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011018 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11019 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011020 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011021 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011022 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11023 new String[] {ssp});
11024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 }
11027 }
11028 } else {
11029 String msg = "Permission Denial: " + intent.getAction()
11030 + " broadcast from " + callerPackage + " (pid=" + callingPid
11031 + ", uid=" + callingUid + ")"
11032 + " requires "
11033 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011034 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 throw new SecurityException(msg);
11036 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011037
11038 // Special case for adding a package: by default turn on compatibility
11039 // mode.
11040 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011041 Uri data = intent.getData();
11042 String ssp;
11043 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11044 mCompatModePackages.handlePackageAddedLocked(ssp,
11045 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 }
11048
11049 /*
11050 * If this is the time zone changed action, queue up a message that will reset the timezone
11051 * of all currently running processes. This message will get queued up before the broadcast
11052 * happens.
11053 */
11054 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11055 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11056 }
11057
Robert Greenwalt03595d02010-11-02 14:08:23 -070011058 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11059 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11060 }
11061
Robert Greenwalt434203a2010-10-11 16:00:27 -070011062 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11063 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11064 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11065 }
11066
Dianne Hackborn854060af2009-07-09 18:14:31 -070011067 /*
11068 * Prevent non-system code (defined here to be non-persistent
11069 * processes) from sending protected broadcasts.
11070 */
11071 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070011072 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11073 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070011074 // Always okay.
11075 } else if (callerApp == null || !callerApp.persistent) {
11076 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011077 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011078 intent.getAction())) {
11079 String msg = "Permission Denial: not allowed to send broadcast "
11080 + intent.getAction() + " from pid="
11081 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011082 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011083 throw new SecurityException(msg);
11084 }
11085 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011086 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011087 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070011088 }
11089 }
11090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 // Add to the sticky list if requested.
11092 if (sticky) {
11093 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11094 callingPid, callingUid)
11095 != PackageManager.PERMISSION_GRANTED) {
11096 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11097 + callingPid + ", uid=" + callingUid
11098 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011099 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 throw new SecurityException(msg);
11101 }
11102 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011103 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011105 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 }
11107 if (intent.getComponent() != null) {
11108 throw new SecurityException(
11109 "Sticky broadcasts can't target a specific component");
11110 }
11111 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11112 if (list == null) {
11113 list = new ArrayList<Intent>();
11114 mStickyBroadcasts.put(intent.getAction(), list);
11115 }
11116 int N = list.size();
11117 int i;
11118 for (i=0; i<N; i++) {
11119 if (intent.filterEquals(list.get(i))) {
11120 // This sticky already exists, replace it.
11121 list.set(i, new Intent(intent));
11122 break;
11123 }
11124 }
11125 if (i >= N) {
11126 list.add(new Intent(intent));
11127 }
11128 }
11129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 // Figure out who all will receive this broadcast.
11131 List receivers = null;
11132 List<BroadcastFilter> registeredReceivers = null;
11133 try {
11134 if (intent.getComponent() != null) {
11135 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011136 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070011137 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 if (ai != null) {
11139 receivers = new ArrayList();
11140 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070011141 if (isSingleton(ai.processName, ai.applicationInfo)) {
11142 ri.activityInfo = getActivityInfoForUser(ai, 0);
11143 } else {
11144 ri.activityInfo = getActivityInfoForUser(ai, userId);
11145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 receivers.add(ri);
11147 }
11148 } else {
11149 // Need to resolve the intent to interested receivers...
11150 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11151 == 0) {
11152 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011153 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011154 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070011156 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
11157 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 }
11159 } catch (RemoteException ex) {
11160 // pm is in same process, this will never happen.
11161 }
11162
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011163 final boolean replacePending =
11164 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11165
Joe Onorato8a9b2202010-02-26 18:56:32 -080011166 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011167 + " replacePending=" + replacePending);
11168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11170 if (!ordered && NR > 0) {
11171 // If we are not serializing this broadcast, then send the
11172 // registered receivers separately so they don't wait for the
11173 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011174 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11175 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 callerPackage, callingPid, callingUid, requiredPermission,
11177 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011178 ordered, sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011179 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011180 TAG, "Enqueueing parallel broadcast " + r);
11181 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011182 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011183 queue.enqueueParallelBroadcastLocked(r);
11184 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 registeredReceivers = null;
11187 NR = 0;
11188 }
11189
11190 // Merge into one list.
11191 int ir = 0;
11192 if (receivers != null) {
11193 // A special case for PACKAGE_ADDED: do not allow the package
11194 // being added to see this broadcast. This prevents them from
11195 // using this as a back door to get run as soon as they are
11196 // installed. Maybe in the future we want to have a special install
11197 // broadcast or such for apps, but we'd like to deliberately make
11198 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011199 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011200 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11201 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11202 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011203 Uri data = intent.getData();
11204 if (data != null) {
11205 String pkgName = data.getSchemeSpecificPart();
11206 if (pkgName != null) {
11207 skipPackages = new String[] { pkgName };
11208 }
11209 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011210 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011211 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011212 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011213 if (skipPackages != null && (skipPackages.length > 0)) {
11214 for (String skipPackage : skipPackages) {
11215 if (skipPackage != null) {
11216 int NT = receivers.size();
11217 for (int it=0; it<NT; it++) {
11218 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11219 if (curt.activityInfo.packageName.equals(skipPackage)) {
11220 receivers.remove(it);
11221 it--;
11222 NT--;
11223 }
11224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 }
11226 }
11227 }
11228
11229 int NT = receivers != null ? receivers.size() : 0;
11230 int it = 0;
11231 ResolveInfo curt = null;
11232 BroadcastFilter curr = null;
11233 while (it < NT && ir < NR) {
11234 if (curt == null) {
11235 curt = (ResolveInfo)receivers.get(it);
11236 }
11237 if (curr == null) {
11238 curr = registeredReceivers.get(ir);
11239 }
11240 if (curr.getPriority() >= curt.priority) {
11241 // Insert this broadcast record into the final list.
11242 receivers.add(it, curr);
11243 ir++;
11244 curr = null;
11245 it++;
11246 NT++;
11247 } else {
11248 // Skip to the next ResolveInfo in the final list.
11249 it++;
11250 curt = null;
11251 }
11252 }
11253 }
11254 while (ir < NR) {
11255 if (receivers == null) {
11256 receivers = new ArrayList();
11257 }
11258 receivers.add(registeredReceivers.get(ir));
11259 ir++;
11260 }
11261
11262 if ((receivers != null && receivers.size() > 0)
11263 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011264 BroadcastQueue queue = broadcastQueueForIntent(intent);
11265 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011266 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011267 receivers, resultTo, resultCode, resultData, map, ordered,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011268 sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011269 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011271 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 if (DEBUG_BROADCAST) {
11273 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011274 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011276 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011277 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011278 queue.enqueueOrderedBroadcastLocked(r);
11279 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011281 }
11282
Dianne Hackborna4972e92012-03-14 10:38:05 -070011283 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 }
11285
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011286 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 // Refuse possible leaked file descriptors
11288 if (intent != null && intent.hasFileDescriptors() == true) {
11289 throw new IllegalArgumentException("File descriptors passed in Intent");
11290 }
11291
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011292 int flags = intent.getFlags();
11293
11294 if (!mProcessesReady) {
11295 // if the caller really truly claims to know what they're doing, go
11296 // ahead and allow the broadcast without launching any receivers
11297 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11298 intent = new Intent(intent);
11299 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11300 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11301 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11302 + " before boot completion");
11303 throw new IllegalStateException("Cannot broadcast before boot completed");
11304 }
11305 }
11306
11307 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11308 throw new IllegalArgumentException(
11309 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11310 }
11311
11312 return intent;
11313 }
11314
11315 public final int broadcastIntent(IApplicationThread caller,
11316 Intent intent, String resolvedType, IIntentReceiver resultTo,
11317 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011318 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011319 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011320 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011321 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11324 final int callingPid = Binder.getCallingPid();
11325 final int callingUid = Binder.getCallingUid();
11326 final long origId = Binder.clearCallingIdentity();
11327 int res = broadcastIntentLocked(callerApp,
11328 callerApp != null ? callerApp.info.packageName : null,
11329 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011330 resultCode, resultData, map, requiredPermission, serialized, sticky,
11331 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 Binder.restoreCallingIdentity(origId);
11333 return res;
11334 }
11335 }
11336
11337 int broadcastIntentInPackage(String packageName, int uid,
11338 Intent intent, String resolvedType, IIntentReceiver resultTo,
11339 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011340 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011342 intent = verifyBroadcastLocked(intent);
11343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 final long origId = Binder.clearCallingIdentity();
11345 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11346 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011347 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 Binder.restoreCallingIdentity(origId);
11349 return res;
11350 }
11351 }
11352
Amith Yamasani742a6712011-05-04 14:49:28 -070011353 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
11354 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 // Refuse possible leaked file descriptors
11356 if (intent != null && intent.hasFileDescriptors() == true) {
11357 throw new IllegalArgumentException("File descriptors passed in Intent");
11358 }
11359
11360 synchronized(this) {
11361 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11362 != PackageManager.PERMISSION_GRANTED) {
11363 String msg = "Permission Denial: unbroadcastIntent() from pid="
11364 + Binder.getCallingPid()
11365 + ", uid=" + Binder.getCallingUid()
11366 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011367 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 throw new SecurityException(msg);
11369 }
11370 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11371 if (list != null) {
11372 int N = list.size();
11373 int i;
11374 for (i=0; i<N; i++) {
11375 if (intent.filterEquals(list.get(i))) {
11376 list.remove(i);
11377 break;
11378 }
11379 }
11380 }
11381 }
11382 }
11383
11384 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11385 String resultData, Bundle resultExtras, boolean resultAbort,
11386 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011387 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11388 if (r == null) {
11389 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 return false;
11391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392
Christopher Tatef46723b2012-01-26 14:19:24 -080011393 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11394 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 }
11396
11397 public void finishReceiver(IBinder who, int resultCode, String resultData,
11398 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011399 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400
11401 // Refuse possible leaked file descriptors
11402 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11403 throw new IllegalArgumentException("File descriptors passed in Bundle");
11404 }
11405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011407 try {
11408 boolean doNext = false;
11409 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410
Christopher Tatef46723b2012-01-26 14:19:24 -080011411 synchronized(this) {
11412 r = broadcastRecordForReceiverLocked(who);
11413 if (r != null) {
11414 doNext = r.queue.finishReceiverLocked(r, resultCode,
11415 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011417 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011418
Christopher Tatef46723b2012-01-26 14:19:24 -080011419 if (doNext) {
11420 r.queue.processNextBroadcast(false);
11421 }
11422 trimApplications();
11423 } finally {
11424 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 // =========================================================
11429 // INSTRUMENTATION
11430 // =========================================================
11431
11432 public boolean startInstrumentation(ComponentName className,
11433 String profileFile, int flags, Bundle arguments,
11434 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011435 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 // Refuse possible leaked file descriptors
11437 if (arguments != null && arguments.hasFileDescriptors()) {
11438 throw new IllegalArgumentException("File descriptors passed in Bundle");
11439 }
11440
11441 synchronized(this) {
11442 InstrumentationInfo ii = null;
11443 ApplicationInfo ai = null;
11444 try {
11445 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011446 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011448 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 } catch (PackageManager.NameNotFoundException e) {
11450 }
11451 if (ii == null) {
11452 reportStartInstrumentationFailure(watcher, className,
11453 "Unable to find instrumentation info for: " + className);
11454 return false;
11455 }
11456 if (ai == null) {
11457 reportStartInstrumentationFailure(watcher, className,
11458 "Unable to find instrumentation target package: " + ii.targetPackage);
11459 return false;
11460 }
11461
11462 int match = mContext.getPackageManager().checkSignatures(
11463 ii.targetPackage, ii.packageName);
11464 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11465 String msg = "Permission Denial: starting instrumentation "
11466 + className + " from pid="
11467 + Binder.getCallingPid()
11468 + ", uid=" + Binder.getCallingPid()
11469 + " not allowed because package " + ii.packageName
11470 + " does not have a signature matching the target "
11471 + ii.targetPackage;
11472 reportStartInstrumentationFailure(watcher, className, msg);
11473 throw new SecurityException(msg);
11474 }
11475
Amith Yamasani483f3b02012-03-13 16:08:00 -070011476 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011478 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011479 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011480 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011482 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 app.instrumentationProfileFile = profileFile;
11484 app.instrumentationArguments = arguments;
11485 app.instrumentationWatcher = watcher;
11486 app.instrumentationResultClass = className;
11487 Binder.restoreCallingIdentity(origId);
11488 }
11489
11490 return true;
11491 }
11492
11493 /**
11494 * Report errors that occur while attempting to start Instrumentation. Always writes the
11495 * error to the logs, but if somebody is watching, send the report there too. This enables
11496 * the "am" command to report errors with more information.
11497 *
11498 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11499 * @param cn The component name of the instrumentation.
11500 * @param report The error report.
11501 */
11502 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11503 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011504 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 try {
11506 if (watcher != null) {
11507 Bundle results = new Bundle();
11508 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11509 results.putString("Error", report);
11510 watcher.instrumentationStatus(cn, -1, results);
11511 }
11512 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011513 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 }
11515 }
11516
11517 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11518 if (app.instrumentationWatcher != null) {
11519 try {
11520 // NOTE: IInstrumentationWatcher *must* be oneway here
11521 app.instrumentationWatcher.instrumentationFinished(
11522 app.instrumentationClass,
11523 resultCode,
11524 results);
11525 } catch (RemoteException e) {
11526 }
11527 }
11528 app.instrumentationWatcher = null;
11529 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011530 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 app.instrumentationProfileFile = null;
11532 app.instrumentationArguments = null;
11533
Amith Yamasani483f3b02012-03-13 16:08:00 -070011534 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011535 }
11536
11537 public void finishInstrumentation(IApplicationThread target,
11538 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011539 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 // Refuse possible leaked file descriptors
11541 if (results != null && results.hasFileDescriptors()) {
11542 throw new IllegalArgumentException("File descriptors passed in Intent");
11543 }
11544
11545 synchronized(this) {
11546 ProcessRecord app = getRecordForAppLocked(target);
11547 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011548 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011549 return;
11550 }
11551 final long origId = Binder.clearCallingIdentity();
11552 finishInstrumentationLocked(app, resultCode, results);
11553 Binder.restoreCallingIdentity(origId);
11554 }
11555 }
11556
11557 // =========================================================
11558 // CONFIGURATION
11559 // =========================================================
11560
11561 public ConfigurationInfo getDeviceConfigurationInfo() {
11562 ConfigurationInfo config = new ConfigurationInfo();
11563 synchronized (this) {
11564 config.reqTouchScreen = mConfiguration.touchscreen;
11565 config.reqKeyboardType = mConfiguration.keyboard;
11566 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011567 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11568 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11570 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011571 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11572 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11574 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011575 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 }
11577 return config;
11578 }
11579
11580 public Configuration getConfiguration() {
11581 Configuration ci;
11582 synchronized(this) {
11583 ci = new Configuration(mConfiguration);
11584 }
11585 return ci;
11586 }
11587
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011588 public void updatePersistentConfiguration(Configuration values) {
11589 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11590 "updateConfiguration()");
11591 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11592 "updateConfiguration()");
11593 if (values == null) {
11594 throw new NullPointerException("Configuration must not be null");
11595 }
11596
11597 synchronized(this) {
11598 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011599 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011600 Binder.restoreCallingIdentity(origId);
11601 }
11602 }
11603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 public void updateConfiguration(Configuration values) {
11605 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11606 "updateConfiguration()");
11607
11608 synchronized(this) {
11609 if (values == null && mWindowManager != null) {
11610 // sentinel: fetch the current configuration from the window manager
11611 values = mWindowManager.computeNewConfiguration();
11612 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011613
11614 if (mWindowManager != null) {
11615 mProcessList.applyDisplaySize(mWindowManager);
11616 }
11617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011619 if (values != null) {
11620 Settings.System.clearConfiguration(values);
11621 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011622 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 Binder.restoreCallingIdentity(origId);
11624 }
11625 }
11626
11627 /**
11628 * Do either or both things: (1) change the current configuration, and (2)
11629 * make sure the given activity is running with the (now) current
11630 * configuration. Returns true if the activity has been left running, or
11631 * false if <var>starting</var> is being destroyed to match the new
11632 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011633 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011635 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011636 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011637 // do nothing if we are headless
11638 if (mHeadless) return true;
11639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 int changes = 0;
11641
11642 boolean kept = true;
11643
11644 if (values != null) {
11645 Configuration newConfig = new Configuration(mConfiguration);
11646 changes = newConfig.updateFrom(values);
11647 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011648 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011649 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 }
11651
Doug Zongker2bec3d42009-12-04 12:52:44 -080011652 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653
Dianne Hackborn813075a62011-11-14 17:45:19 -080011654 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 saveLocaleLocked(values.locale,
11656 !values.locale.equals(mConfiguration.locale),
11657 values.userSetLocale);
11658 }
11659
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011660 mConfigurationSeq++;
11661 if (mConfigurationSeq <= 0) {
11662 mConfigurationSeq = 1;
11663 }
11664 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011666 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011667
11668 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070011669
11670 // TODO: If our config changes, should we auto dismiss any currently
11671 // showing dialogs?
11672 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011673
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011674 AttributeCache ac = AttributeCache.instance();
11675 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080011676 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011679 // Make sure all resources in our process are updated
11680 // right now, so that anyone who is going to retrieve
11681 // resource values after we return will be sure to get
11682 // the new ones. This is especially important during
11683 // boot, where the first config change needs to guarantee
11684 // all resources have that config before following boot
11685 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080011686 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011687
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011688 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011689 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011690 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011691 mHandler.sendMessage(msg);
11692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011694 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11695 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 try {
11697 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011698 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011699 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011700 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701 }
11702 } catch (Exception e) {
11703 }
11704 }
11705 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011706 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11707 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011708 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011709 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011710 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11711 broadcastIntentLocked(null, null,
11712 new Intent(Intent.ACTION_LOCALE_CHANGED),
11713 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011714 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 }
11717 }
11718
11719 if (changes != 0 && starting == null) {
11720 // If the configuration changed, and the caller is not already
11721 // in the process of starting an activity, then find the top
11722 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011723 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 }
11725
11726 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011727 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011728 // And we need to make sure at this point that all other activities
11729 // are made visible with the correct configuration.
11730 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011733 if (values != null && mWindowManager != null) {
11734 mWindowManager.setNewConfiguration(mConfiguration);
11735 }
11736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 return kept;
11738 }
Joe Onorato54a4a412011-11-02 20:50:08 -070011739
11740 /**
11741 * Decide based on the configuration whether we should shouw the ANR,
11742 * crash, etc dialogs. The idea is that if there is no affordnace to
11743 * press the on-screen buttons, we shouldn't show the dialog.
11744 *
11745 * A thought: SystemUI might also want to get told about this, the Power
11746 * dialog / global actions also might want different behaviors.
11747 */
11748 private static final boolean shouldShowDialogs(Configuration config) {
11749 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
11750 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
11751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752
11753 /**
11754 * Save the locale. You must be inside a synchronized (this) block.
11755 */
11756 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11757 if(isDiff) {
11758 SystemProperties.set("user.language", l.getLanguage());
11759 SystemProperties.set("user.region", l.getCountry());
11760 }
11761
11762 if(isPersist) {
11763 SystemProperties.set("persist.sys.language", l.getLanguage());
11764 SystemProperties.set("persist.sys.country", l.getCountry());
11765 SystemProperties.set("persist.sys.localevar", l.getVariant());
11766 }
11767 }
11768
Adam Powelldd8fab22012-03-22 17:47:27 -070011769 @Override
11770 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
11771 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011772 return srec != null && srec.task.affinity != null &&
11773 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070011774 }
11775
11776 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
11777 Intent resultData) {
11778 ComponentName dest = destIntent.getComponent();
11779
11780 synchronized (this) {
11781 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011782 if (srec == null) {
11783 return false;
11784 }
Adam Powelldd8fab22012-03-22 17:47:27 -070011785 ArrayList<ActivityRecord> history = srec.stack.mHistory;
11786 final int start = history.indexOf(srec);
11787 if (start < 0) {
11788 // Current activity is not in history stack; do nothing.
11789 return false;
11790 }
11791 int finishTo = start - 1;
11792 ActivityRecord parent = null;
11793 boolean foundParentInTask = false;
11794 if (dest != null) {
11795 TaskRecord tr = srec.task;
11796 for (int i = start - 1; i >= 0; i--) {
11797 ActivityRecord r = history.get(i);
11798 if (tr != r.task) {
11799 // Couldn't find parent in the same task; stop at the one above this.
11800 // (Root of current task; in-app "home" behavior)
11801 // Always at least finish the current activity.
11802 finishTo = Math.min(start - 1, i + 1);
11803 parent = history.get(finishTo);
11804 break;
11805 } else if (r.info.packageName.equals(dest.getPackageName()) &&
11806 r.info.name.equals(dest.getClassName())) {
11807 finishTo = i;
11808 parent = r;
11809 foundParentInTask = true;
11810 break;
11811 }
11812 }
11813 }
11814
11815 if (mController != null) {
11816 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
11817 if (next != null) {
11818 // ask watcher if this is allowed
11819 boolean resumeOK = true;
11820 try {
11821 resumeOK = mController.activityResuming(next.packageName);
11822 } catch (RemoteException e) {
11823 mController = null;
11824 }
11825
11826 if (!resumeOK) {
11827 return false;
11828 }
11829 }
11830 }
11831 final long origId = Binder.clearCallingIdentity();
11832 for (int i = start; i > finishTo; i--) {
11833 ActivityRecord r = history.get(i);
11834 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
11835 "navigate-up");
11836 // Only return the supplied result for the first activity finished
11837 resultCode = Activity.RESULT_CANCELED;
11838 resultData = null;
11839 }
11840
11841 if (parent != null && foundParentInTask) {
11842 final int parentLaunchMode = parent.info.launchMode;
11843 final int destIntentFlags = destIntent.getFlags();
11844 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
11845 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
11846 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
11847 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070011848 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070011849 } else {
11850 try {
11851 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
11852 destIntent.getComponent(), 0, UserId.getCallingUserId());
11853 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
11854 null, aInfo, parent.appToken, null,
11855 0, -1, parent.launchedFromUid, 0, null, true, null);
11856 foundParentInTask = res == ActivityManager.START_SUCCESS;
11857 } catch (RemoteException e) {
11858 foundParentInTask = false;
11859 }
11860 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
11861 resultData, "navigate-up");
11862 }
11863 }
11864 Binder.restoreCallingIdentity(origId);
11865 return foundParentInTask;
11866 }
11867 }
11868
Dianne Hackborn5320eb82012-05-18 12:05:04 -070011869 public int getLaunchedFromUid(IBinder activityToken) {
11870 ActivityRecord srec = ActivityRecord.forToken(activityToken);
11871 if (srec == null) {
11872 return -1;
11873 }
11874 return srec.launchedFromUid;
11875 }
11876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 // =========================================================
11878 // LIFETIME MANAGEMENT
11879 // =========================================================
11880
Christopher Tatef46723b2012-01-26 14:19:24 -080011881 // Returns which broadcast queue the app is the current [or imminent] receiver
11882 // on, or 'null' if the app is not an active broadcast recipient.
11883 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
11884 BroadcastRecord r = app.curReceiver;
11885 if (r != null) {
11886 return r.queue;
11887 }
11888
11889 // It's not the current receiver, but it might be starting up to become one
11890 synchronized (this) {
11891 for (BroadcastQueue queue : mBroadcastQueues) {
11892 r = queue.mPendingBroadcast;
11893 if (r != null && r.curApp == app) {
11894 // found it; report which queue it's in
11895 return queue;
11896 }
11897 }
11898 }
11899
11900 return null;
11901 }
11902
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011903 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070011904 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011905 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011906 // This adjustment has already been computed. If we are calling
11907 // from the top, we may have already computed our adjustment with
11908 // an earlier hidden adjustment that isn't really for us... if
11909 // so, use the new hidden adjustment.
11910 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070011911 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011912 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011913 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 }
11915
11916 if (app.thread == null) {
11917 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011918 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070011919 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 }
11921
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011922 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
11923 app.adjSource = null;
11924 app.adjTarget = null;
11925 app.empty = false;
11926 app.hidden = false;
11927
11928 final int activitiesSize = app.activities.size();
11929
Dianne Hackborn7d608422011-08-07 16:24:18 -070011930 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011931 // The max adjustment doesn't allow this app to be anything
11932 // below foreground, so it is not worth doing work for it.
11933 app.adjType = "fixed";
11934 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070011935 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011936 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011937 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011938 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011939 // System process can do UI, and when they do we want to have
11940 // them trim their memory after the user leaves the UI. To
11941 // facilitate this, here we need to determine whether or not it
11942 // is currently showing UI.
11943 app.systemNoUi = true;
11944 if (app == TOP_APP) {
11945 app.systemNoUi = false;
11946 } else if (activitiesSize > 0) {
11947 for (int j = 0; j < activitiesSize; j++) {
11948 final ActivityRecord r = app.activities.get(j);
11949 if (r.visible) {
11950 app.systemNoUi = false;
11951 break;
11952 }
11953 }
11954 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011955 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011956 }
11957
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011958 app.keeping = false;
11959 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011960
The Android Open Source Project4df24232009-03-05 14:34:35 -080011961 // Determine the importance of the process, starting with most
11962 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011963 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011964 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070011965 boolean foregroundActivities = false;
11966 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080011967 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011968 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070011970 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011971 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011972 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070011973 foregroundActivities = true;
11974 interesting = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011975 } else if (app.instrumentationClass != null) {
11976 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070011977 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011978 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011979 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070011980 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080011981 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080011983 // counts as being in the foreground for OOM killer purposes.
11984 // It's placed in a sched group based on the nature of the
11985 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070011986 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080011987 schedGroup = (queue == mFgBroadcastQueue)
11988 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011989 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 } else if (app.executingServices.size() > 0) {
11991 // An app that is currently executing a service callback also
11992 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070011993 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011994 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011995 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011996 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011998 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012000 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012001 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012002 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012004 // A very not-needed process. If this is lower in the lru list,
12005 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012006 adj = hiddenAdj;
12007 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012008 app.hidden = true;
12009 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012010 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012012
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012013 boolean hasStoppingActivities = false;
12014
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012015 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012016 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012017 for (int j = 0; j < activitiesSize; j++) {
12018 final ActivityRecord r = app.activities.get(j);
12019 if (r.visible) {
12020 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012021 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12022 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012023 app.adjType = "visible";
12024 }
12025 schedGroup = Process.THREAD_GROUP_DEFAULT;
12026 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012027 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012028 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012029 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012030 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12031 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012032 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012033 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012034 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012035 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012036 } else if (r.state == ActivityState.STOPPING) {
12037 // We will apply the actual adjustment later, because
12038 // we want to allow this process to immediately go through
12039 // any memory trimming that is in effect.
12040 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012041 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012042 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012043 }
12044 }
12045 }
12046
Dianne Hackborn7d608422011-08-07 16:24:18 -070012047 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012048 if (app.foregroundServices) {
12049 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012050 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012051 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012052 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012053 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012054 } else if (app.forcingToForeground != null) {
12055 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012056 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012057 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012058 app.adjType = "force-foreground";
12059 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012060 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012061 }
12062 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012063
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012064 if (app.foregroundServices) {
12065 interesting = true;
12066 }
12067
Dianne Hackborn7d608422011-08-07 16:24:18 -070012068 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012069 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012070 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012071 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012072 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012073 app.adjType = "heavy";
12074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075
Dianne Hackborn7d608422011-08-07 16:24:18 -070012076 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012077 // This process is hosting what we currently consider to be the
12078 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012079 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012080 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012081 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012082 app.adjType = "home";
12083 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012084
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012085 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12086 && app.activities.size() > 0) {
12087 // This was the previous process that showed UI to the user.
12088 // We want to try to keep it around more aggressively, to give
12089 // a good experience around switching between two apps.
12090 adj = ProcessList.PREVIOUS_APP_ADJ;
12091 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12092 app.hidden = false;
12093 app.adjType = "previous";
12094 }
12095
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012096 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12097 + " reason=" + app.adjType);
12098
The Android Open Source Project4df24232009-03-05 14:34:35 -080012099 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 // there are applications dependent on our services or providers, but
12101 // this gives us a baseline and makes sure we don't get into an
12102 // infinite recursion.
12103 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012104 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105
Christopher Tate6fa95972009-06-05 18:43:55 -070012106 if (mBackupTarget != null && app == mBackupTarget.app) {
12107 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012108 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012109 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012110 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012111 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012112 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012113 }
12114 }
12115
Dianne Hackborn7d608422011-08-07 16:24:18 -070012116 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012117 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012118 final long now = SystemClock.uptimeMillis();
12119 // This process is more important if the top activity is
12120 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012121 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012122 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012123 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012124 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012125 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012126 // If this process has shown some UI, let it immediately
12127 // go to the LRU list because it may be pretty heavy with
12128 // UI stuff. We'll tag it with a label just to help
12129 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012130 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012131 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012133 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012134 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012135 // This service has seen some activity within
12136 // recent memory, so we will keep its process ahead
12137 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012138 if (adj > ProcessList.SERVICE_ADJ) {
12139 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012140 app.adjType = "started-services";
12141 app.hidden = false;
12142 }
12143 }
12144 // If we have let the service slide into the background
12145 // state, still have some text describing what it is doing
12146 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012147 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012148 app.adjType = "started-bg-services";
12149 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012150 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012151 // Don't kill this process because it is doing work; it
12152 // has said it is doing work.
12153 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012154 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012155 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012156 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012157 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012158 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012159 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012160 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012161 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012162 // XXX should compute this based on the max of
12163 // all connected clients.
12164 ConnectionRecord cr = clist.get(i);
12165 if (cr.binding.client == app) {
12166 // Binding to ourself is not interesting.
12167 continue;
12168 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012169 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012170 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012171 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012172 int myHiddenAdj = hiddenAdj;
12173 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012174 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012175 myHiddenAdj = client.hiddenAdj;
12176 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012177 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012178 }
12179 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012180 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012181 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012182 String adjType = null;
12183 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12184 // Not doing bind OOM management, so treat
12185 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012186 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012187 // If this process has shown some UI, let it immediately
12188 // go to the LRU list because it may be pretty heavy with
12189 // UI stuff. We'll tag it with a label just to help
12190 // debug and understand what is going on.
12191 if (adj > clientAdj) {
12192 adjType = "bound-bg-ui-services";
12193 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012194 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012195 clientAdj = adj;
12196 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012197 if (now >= (s.lastActivity
12198 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012199 // This service has not seen activity within
12200 // recent memory, so allow it to drop to the
12201 // LRU list if there is no other reason to keep
12202 // it around. We'll also tag it with a label just
12203 // to help debug and undertand what is going on.
12204 if (adj > clientAdj) {
12205 adjType = "bound-bg-services";
12206 }
12207 clientAdj = adj;
12208 }
12209 }
12210 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012211 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012212 // If this process has recently shown UI, and
12213 // the process that is binding to it is less
12214 // important than being visible, then we don't
12215 // care about the binding as much as we care
12216 // about letting this process get into the LRU
12217 // list to be killed and restarted if needed for
12218 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012219 if (app.hasShownUi && app != mHomeProcess
12220 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012221 adjType = "bound-bg-ui-services";
12222 } else {
12223 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12224 |Context.BIND_IMPORTANT)) != 0) {
12225 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012226 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12227 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12228 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12229 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12230 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012231 adj = clientAdj;
12232 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012233 app.pendingUiClean = true;
12234 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12235 adj = ProcessList.VISIBLE_APP_ADJ;
12236 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012237 }
12238 if (!client.hidden) {
12239 app.hidden = false;
12240 }
12241 if (client.keeping) {
12242 app.keeping = true;
12243 }
12244 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012245 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012246 }
12247 if (adjType != null) {
12248 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012249 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12250 .REASON_SERVICE_IN_USE;
12251 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012252 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012253 app.adjTarget = s.name;
12254 }
12255 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12256 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12257 schedGroup = Process.THREAD_GROUP_DEFAULT;
12258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 }
12260 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012261 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12262 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012263 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012264 (a.visible || a.state == ActivityState.RESUMED
12265 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012266 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012267 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12268 schedGroup = Process.THREAD_GROUP_DEFAULT;
12269 }
12270 app.hidden = false;
12271 app.adjType = "service";
12272 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12273 .REASON_SERVICE_IN_USE;
12274 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012275 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012276 app.adjTarget = s.name;
12277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012279 }
12280 }
12281 }
12282 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012283
Dianne Hackborn287952c2010-09-22 22:34:31 -070012284 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012285 // would like to avoid killing it unless it would prevent the current
12286 // application from running. By default we put the process in
12287 // with the rest of the background processes; as we scan through
12288 // its services we may bump it up from there.
12289 if (adj > hiddenAdj) {
12290 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012291 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012292 app.adjType = "bg-services";
12293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012294 }
12295
Dianne Hackborn7d608422011-08-07 16:24:18 -070012296 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012297 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012298 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012299 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012300 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012301 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012302 for (int i = cpr.connections.size()-1;
12303 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12304 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12305 i--) {
12306 ContentProviderConnection conn = cpr.connections.get(i);
12307 ProcessRecord client = conn.client;
12308 if (client == app) {
12309 // Being our own client is not interesting.
12310 continue;
12311 }
12312 int myHiddenAdj = hiddenAdj;
12313 if (myHiddenAdj > client.hiddenAdj) {
12314 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12315 myHiddenAdj = client.hiddenAdj;
12316 } else {
12317 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012318 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012319 }
12320 int clientAdj = computeOomAdjLocked(
12321 client, myHiddenAdj, TOP_APP, true, doingAll);
12322 if (adj > clientAdj) {
12323 if (app.hasShownUi && app != mHomeProcess
12324 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12325 app.adjType = "bg-ui-provider";
12326 } else {
12327 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12328 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12329 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012331 if (!client.hidden) {
12332 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012333 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012334 if (client.keeping) {
12335 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012336 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012337 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12338 .REASON_PROVIDER_IN_USE;
12339 app.adjSource = client;
12340 app.adjSourceOom = clientAdj;
12341 app.adjTarget = cpr.name;
12342 }
12343 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12344 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 }
12346 }
12347 // If the provider has external (non-framework) process
12348 // dependencies, ensure that its adjustment is at least
12349 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012350 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012351 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12352 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012353 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012354 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012355 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012356 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012357 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 }
12359 }
12360 }
12361 }
12362
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012363 if (adj == ProcessList.SERVICE_ADJ) {
12364 if (doingAll) {
12365 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12366 mNewNumServiceProcs++;
12367 }
12368 if (app.serviceb) {
12369 adj = ProcessList.SERVICE_B_ADJ;
12370 }
12371 } else {
12372 app.serviceb = false;
12373 }
12374
12375 app.nonStoppingAdj = adj;
12376
12377 if (hasStoppingActivities) {
12378 // Only upgrade adjustment.
12379 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12380 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12381 app.adjType = "stopping";
12382 }
12383 }
12384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 app.curRawAdj = adj;
12386
Joe Onorato8a9b2202010-02-26 18:56:32 -080012387 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12389 if (adj > app.maxAdj) {
12390 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012391 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012392 schedGroup = Process.THREAD_GROUP_DEFAULT;
12393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012395 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012396 app.keeping = true;
12397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012398
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012399 if (app.hasAboveClient) {
12400 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12401 // then we need to drop its adjustment to be lower than the service's
12402 // in order to honor the request. We want to drop it by one adjustment
12403 // level... but there is special meaning applied to various levels so
12404 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012405 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012406 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012407 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12408 adj = ProcessList.VISIBLE_APP_ADJ;
12409 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12410 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12411 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12412 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012413 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012414 adj++;
12415 }
12416 }
12417
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012418 int importance = app.memImportance;
12419 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12420 app.curAdj = adj;
12421 app.curSchedGroup = schedGroup;
12422 if (!interesting) {
12423 // For this reporting, if there is not something explicitly
12424 // interesting in this process then we will push it to the
12425 // background importance.
12426 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12427 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12428 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12429 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12430 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12431 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12432 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12433 } else if (adj >= ProcessList.SERVICE_ADJ) {
12434 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12435 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12436 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12437 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12438 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12439 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12440 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12441 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12442 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12443 } else {
12444 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12445 }
12446 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012447
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012448 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12449 if (foregroundActivities != app.foregroundActivities) {
12450 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12451 }
12452 if (changes != 0) {
12453 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12454 app.memImportance = importance;
12455 app.foregroundActivities = foregroundActivities;
12456 int i = mPendingProcessChanges.size()-1;
12457 ProcessChangeItem item = null;
12458 while (i >= 0) {
12459 item = mPendingProcessChanges.get(i);
12460 if (item.pid == app.pid) {
12461 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12462 break;
12463 }
12464 i--;
12465 }
12466 if (i < 0) {
12467 // No existing item in pending changes; need a new one.
12468 final int NA = mAvailProcessChanges.size();
12469 if (NA > 0) {
12470 item = mAvailProcessChanges.remove(NA-1);
12471 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12472 } else {
12473 item = new ProcessChangeItem();
12474 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12475 }
12476 item.changes = 0;
12477 item.pid = app.pid;
12478 item.uid = app.info.uid;
12479 if (mPendingProcessChanges.size() == 0) {
12480 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12481 "*** Enqueueing dispatch processes changed!");
12482 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12483 }
12484 mPendingProcessChanges.add(item);
12485 }
12486 item.changes |= changes;
12487 item.importance = importance;
12488 item.foregroundActivities = foregroundActivities;
12489 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12490 + Integer.toHexString(System.identityHashCode(item))
12491 + " " + app.toShortString() + ": changes=" + item.changes
12492 + " importance=" + item.importance
12493 + " foreground=" + item.foregroundActivities
12494 + " type=" + app.adjType + " source=" + app.adjSource
12495 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012496 }
12497
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012498 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 }
12500
12501 /**
12502 * Ask a given process to GC right now.
12503 */
12504 final void performAppGcLocked(ProcessRecord app) {
12505 try {
12506 app.lastRequestedGc = SystemClock.uptimeMillis();
12507 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012508 if (app.reportLowMemory) {
12509 app.reportLowMemory = false;
12510 app.thread.scheduleLowMemory();
12511 } else {
12512 app.thread.processInBackground();
12513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 }
12515 } catch (Exception e) {
12516 // whatever.
12517 }
12518 }
12519
12520 /**
12521 * Returns true if things are idle enough to perform GCs.
12522 */
Josh Bartel7f208742010-02-25 11:01:44 -060012523 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012524 boolean processingBroadcasts = false;
12525 for (BroadcastQueue q : mBroadcastQueues) {
12526 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12527 processingBroadcasts = true;
12528 }
12529 }
12530 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012531 && (mSleeping || (mMainStack.mResumedActivity != null &&
12532 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012533 }
12534
12535 /**
12536 * Perform GCs on all processes that are waiting for it, but only
12537 * if things are idle.
12538 */
12539 final void performAppGcsLocked() {
12540 final int N = mProcessesToGc.size();
12541 if (N <= 0) {
12542 return;
12543 }
Josh Bartel7f208742010-02-25 11:01:44 -060012544 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545 while (mProcessesToGc.size() > 0) {
12546 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012547 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012548 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12549 <= SystemClock.uptimeMillis()) {
12550 // To avoid spamming the system, we will GC processes one
12551 // at a time, waiting a few seconds between each.
12552 performAppGcLocked(proc);
12553 scheduleAppGcsLocked();
12554 return;
12555 } else {
12556 // It hasn't been long enough since we last GCed this
12557 // process... put it in the list to wait for its time.
12558 addProcessToGcListLocked(proc);
12559 break;
12560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012561 }
12562 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012563
12564 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012565 }
12566 }
12567
12568 /**
12569 * If all looks good, perform GCs on all processes waiting for them.
12570 */
12571 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012572 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 performAppGcsLocked();
12574 return;
12575 }
12576 // Still not idle, wait some more.
12577 scheduleAppGcsLocked();
12578 }
12579
12580 /**
12581 * Schedule the execution of all pending app GCs.
12582 */
12583 final void scheduleAppGcsLocked() {
12584 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012585
12586 if (mProcessesToGc.size() > 0) {
12587 // Schedule a GC for the time to the next process.
12588 ProcessRecord proc = mProcessesToGc.get(0);
12589 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12590
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012591 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012592 long now = SystemClock.uptimeMillis();
12593 if (when < (now+GC_TIMEOUT)) {
12594 when = now + GC_TIMEOUT;
12595 }
12596 mHandler.sendMessageAtTime(msg, when);
12597 }
12598 }
12599
12600 /**
12601 * Add a process to the array of processes waiting to be GCed. Keeps the
12602 * list in sorted order by the last GC time. The process can't already be
12603 * on the list.
12604 */
12605 final void addProcessToGcListLocked(ProcessRecord proc) {
12606 boolean added = false;
12607 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12608 if (mProcessesToGc.get(i).lastRequestedGc <
12609 proc.lastRequestedGc) {
12610 added = true;
12611 mProcessesToGc.add(i+1, proc);
12612 break;
12613 }
12614 }
12615 if (!added) {
12616 mProcessesToGc.add(0, proc);
12617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 }
12619
12620 /**
12621 * Set up to ask a process to GC itself. This will either do it
12622 * immediately, or put it on the list of processes to gc the next
12623 * time things are idle.
12624 */
12625 final void scheduleAppGcLocked(ProcessRecord app) {
12626 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012627 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 return;
12629 }
12630 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012631 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 scheduleAppGcsLocked();
12633 }
12634 }
12635
Dianne Hackborn287952c2010-09-22 22:34:31 -070012636 final void checkExcessivePowerUsageLocked(boolean doKills) {
12637 updateCpuStatsNow();
12638
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012639 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012640 boolean doWakeKills = doKills;
12641 boolean doCpuKills = doKills;
12642 if (mLastPowerCheckRealtime == 0) {
12643 doWakeKills = false;
12644 }
12645 if (mLastPowerCheckUptime == 0) {
12646 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012647 }
12648 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012649 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012650 }
12651 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012652 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12653 final long curUptime = SystemClock.uptimeMillis();
12654 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12655 mLastPowerCheckRealtime = curRealtime;
12656 mLastPowerCheckUptime = curUptime;
12657 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12658 doWakeKills = false;
12659 }
12660 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12661 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012662 }
12663 int i = mLruProcesses.size();
12664 while (i > 0) {
12665 i--;
12666 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012667 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012668 long wtime;
12669 synchronized (stats) {
12670 wtime = stats.getProcessWakeTime(app.info.uid,
12671 app.pid, curRealtime);
12672 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012673 long wtimeUsed = wtime - app.lastWakeTime;
12674 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12675 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012676 StringBuilder sb = new StringBuilder(128);
12677 sb.append("Wake for ");
12678 app.toShortString(sb);
12679 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012680 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012681 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012682 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012683 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012684 sb.append((wtimeUsed*100)/realtimeSince);
12685 sb.append("%)");
12686 Slog.i(TAG, sb.toString());
12687 sb.setLength(0);
12688 sb.append("CPU for ");
12689 app.toShortString(sb);
12690 sb.append(": over ");
12691 TimeUtils.formatDuration(uptimeSince, sb);
12692 sb.append(" used ");
12693 TimeUtils.formatDuration(cputimeUsed, sb);
12694 sb.append(" (");
12695 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012696 sb.append("%)");
12697 Slog.i(TAG, sb.toString());
12698 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012699 // If a process has held a wake lock for more
12700 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012701 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012702 if (doWakeKills && realtimeSince > 0
12703 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12704 synchronized (stats) {
12705 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12706 realtimeSince, wtimeUsed);
12707 }
12708 Slog.w(TAG, "Excessive wake lock in " + app.processName
12709 + " (pid " + app.pid + "): held " + wtimeUsed
12710 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012711 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12712 app.processName, app.setAdj, "excessive wake lock");
12713 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012714 } else if (doCpuKills && uptimeSince > 0
12715 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12716 synchronized (stats) {
12717 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12718 uptimeSince, cputimeUsed);
12719 }
12720 Slog.w(TAG, "Excessive CPU in " + app.processName
12721 + " (pid " + app.pid + "): used " + cputimeUsed
12722 + " during " + uptimeSince);
12723 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12724 app.processName, app.setAdj, "excessive cpu");
12725 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012726 } else {
12727 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012728 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012729 }
12730 }
12731 }
12732 }
12733
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012734 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012735 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 app.hiddenAdj = hiddenAdj;
12737
12738 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012739 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 }
12741
Dianne Hackborn287952c2010-09-22 22:34:31 -070012742 final boolean wasKeeping = app.keeping;
12743
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012744 boolean success = true;
12745
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012746 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012747
Jeff Brown10e89712011-07-08 18:52:57 -070012748 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070012749 if (wasKeeping && !app.keeping) {
12750 // This app is no longer something we want to keep. Note
12751 // its current wake lock time to later know to kill it if
12752 // it is not behaving well.
12753 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12754 synchronized (stats) {
12755 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12756 app.pid, SystemClock.elapsedRealtime());
12757 }
12758 app.lastCpuTime = app.curCpuTime;
12759 }
12760
12761 app.setRawAdj = app.curRawAdj;
12762 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012763
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012764 if (app.curAdj != app.setAdj) {
12765 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080012766 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012767 TAG, "Set " + app.pid + " " + app.processName +
12768 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012769 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070012770 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012771 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012772 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070012773 }
12774 }
12775 if (app.setSchedGroup != app.curSchedGroup) {
12776 app.setSchedGroup = app.curSchedGroup;
12777 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
12778 "Setting process group of " + app.processName
12779 + " to " + app.curSchedGroup);
12780 if (app.waitingToKill != null &&
12781 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
12782 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
12783 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12784 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070012785 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070012786 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012787 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070012788 } else {
12789 if (true) {
12790 long oldId = Binder.clearCallingIdentity();
12791 try {
12792 Process.setProcessGroup(app.pid, app.curSchedGroup);
12793 } catch (Exception e) {
12794 Slog.w(TAG, "Failed setting process group of " + app.pid
12795 + " to " + app.curSchedGroup);
12796 e.printStackTrace();
12797 } finally {
12798 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012799 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012800 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070012801 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012802 try {
Jeff Brown10e89712011-07-08 18:52:57 -070012803 app.thread.setSchedulingGroup(app.curSchedGroup);
12804 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012805 }
12806 }
12807 }
12808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012809 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012810 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 }
12812
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012813 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012814 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080012816 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012818 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 }
12820 }
12821 return resumedActivity;
12822 }
12823
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012824 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012825 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012826 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12827 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012828 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12829 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012830
12831 mAdjSeq++;
12832
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012833 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012834 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12835 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012836 if (nowHidden != wasHidden) {
12837 // Changed to/from hidden state, so apps after it in the LRU
12838 // list may also be changed.
12839 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012840 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012841 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 }
12843
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012844 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012845 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12847
12848 if (false) {
12849 RuntimeException e = new RuntimeException();
12850 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012851 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012852 }
12853
12854 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012855 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012857 // Let's determine how many processes we have running vs.
12858 // how many slots we have for background processes; we may want
12859 // to put multiple processes in a slot of there are enough of
12860 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012861 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012862 int factor = (mLruProcesses.size()-4)/numSlots;
12863 if (factor < 1) factor = 1;
12864 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012865 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012866 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012867
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012868 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012870 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012871 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 while (i > 0) {
12873 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012874 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012875 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012876 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
12877 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012878 && app.curAdj == curHiddenAdj) {
12879 step++;
12880 if (step >= factor) {
12881 step = 0;
12882 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012883 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012884 }
12885 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012886 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012887 numHidden++;
12888 if (numHidden > mProcessLimit) {
12889 Slog.i(TAG, "No longer want " + app.processName
12890 + " (pid " + app.pid + "): hidden #" + numHidden);
12891 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12892 app.processName, app.setAdj, "too many background");
12893 app.killedBackground = true;
12894 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070012895 }
12896 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012897 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
12898 // If this is an isolated process, and there are no
12899 // services running in it, then the process is no longer
12900 // needed. We agressively kill these because we can by
12901 // definition not re-use the same process again, and it is
12902 // good to avoid having whatever code was running in them
12903 // left sitting around after no longer needed.
12904 Slog.i(TAG, "Isolated process " + app.processName
12905 + " (pid " + app.pid + ") no longer needed");
12906 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12907 app.processName, app.setAdj, "isolated not needed");
12908 app.killedBackground = true;
12909 Process.killProcessQuiet(app.pid);
12910 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012911 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
12912 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
12913 && !app.killedBackground) {
12914 numTrimming++;
12915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 }
12917 }
12918
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012919 mNumServiceProcs = mNewNumServiceProcs;
12920
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012921 // Now determine the memory trimming level of background processes.
12922 // Unfortunately we need to start at the back of the list to do this
12923 // properly. We only do this if the number of background apps we
12924 // are managing to keep around is less than half the maximum we desire;
12925 // if we are keeping a good number around, we'll let them use whatever
12926 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012927 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012928 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012929 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080012930 int minFactor = 2;
12931 if (mHomeProcess != null) minFactor++;
12932 if (mPreviousProcess != null) minFactor++;
12933 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012934 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080012935 int fgTrimLevel;
12936 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
12937 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
12938 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
12939 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
12940 } else {
12941 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
12942 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012943 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012944 for (i=0; i<N; i++) {
12945 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012946 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
12947 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080012948 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012949 if (app.trimMemoryLevel < curLevel && app.thread != null) {
12950 try {
12951 app.thread.scheduleTrimMemory(curLevel);
12952 } catch (RemoteException e) {
12953 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080012954 if (false) {
12955 // For now we won't do this; our memory trimming seems
12956 // to be good enough at this point that destroying
12957 // activities causes more harm than good.
12958 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
12959 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070012960 // Need to do this on its own message because the stack may not
12961 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080012962 // For these apps we will also finish their activities
12963 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070012964 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080012965 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012966 }
12967 }
12968 app.trimMemoryLevel = curLevel;
12969 step++;
12970 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080012971 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012972 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012973 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
12974 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012975 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012976 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
12977 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012978 break;
12979 }
12980 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012981 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012982 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012983 && app.thread != null) {
12984 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012985 app.thread.scheduleTrimMemory(
12986 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012987 } catch (RemoteException e) {
12988 }
12989 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012990 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080012991 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012992 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080012993 && app.pendingUiClean) {
12994 // If this application is now in the background and it
12995 // had done UI, then give it the special trim level to
12996 // have it free UI resources.
12997 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
12998 if (app.trimMemoryLevel < level && app.thread != null) {
12999 try {
13000 app.thread.scheduleTrimMemory(level);
13001 } catch (RemoteException e) {
13002 }
13003 }
13004 app.pendingUiClean = false;
13005 }
13006 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013007 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013008 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013009 } catch (RemoteException e) {
13010 }
13011 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013012 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013013 }
13014 }
13015 } else {
13016 final int N = mLruProcesses.size();
13017 for (i=0; i<N; i++) {
13018 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013019 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013020 && app.pendingUiClean) {
13021 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13022 && app.thread != null) {
13023 try {
13024 app.thread.scheduleTrimMemory(
13025 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13026 } catch (RemoteException e) {
13027 }
13028 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013029 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013030 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013031 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013032 }
13033 }
13034
13035 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013036 // Need to do this on its own message because the stack may not
13037 // be in a consistent state at this point.
13038 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 }
13041
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013042 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013043 synchronized (this) {
13044 int i;
13045
13046 // First remove any unused application processes whose package
13047 // has been removed.
13048 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13049 final ProcessRecord app = mRemovedProcesses.get(i);
13050 if (app.activities.size() == 0
13051 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013052 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 TAG, "Exiting empty application process "
13054 + app.processName + " ("
13055 + (app.thread != null ? app.thread.asBinder() : null)
13056 + ")\n");
13057 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013058 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13059 app.processName, app.setAdj, "empty");
13060 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 } else {
13062 try {
13063 app.thread.scheduleExit();
13064 } catch (Exception e) {
13065 // Ignore exceptions.
13066 }
13067 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013068 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 mRemovedProcesses.remove(i);
13070
13071 if (app.persistent) {
13072 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013073 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013074 }
13075 }
13076 }
13077 }
13078
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013079 // Now update the oom adj for all processes.
13080 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013081 }
13082 }
13083
13084 /** This method sends the specified signal to each of the persistent apps */
13085 public void signalPersistentProcesses(int sig) throws RemoteException {
13086 if (sig != Process.SIGNAL_USR1) {
13087 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13088 }
13089
13090 synchronized (this) {
13091 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13092 != PackageManager.PERMISSION_GRANTED) {
13093 throw new SecurityException("Requires permission "
13094 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13095 }
13096
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013097 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13098 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 if (r.thread != null && r.persistent) {
13100 Process.sendSignal(r.pid, sig);
13101 }
13102 }
13103 }
13104 }
13105
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013106 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13107 if (proc == null || proc == mProfileProc) {
13108 proc = mProfileProc;
13109 path = mProfileFile;
13110 profileType = mProfileType;
13111 clearProfilerLocked();
13112 }
13113 if (proc == null) {
13114 return;
13115 }
13116 try {
13117 proc.thread.profilerControl(false, path, null, profileType);
13118 } catch (RemoteException e) {
13119 throw new IllegalStateException("Process disappeared");
13120 }
13121 }
13122
13123 private void clearProfilerLocked() {
13124 if (mProfileFd != null) {
13125 try {
13126 mProfileFd.close();
13127 } catch (IOException e) {
13128 }
13129 }
13130 mProfileApp = null;
13131 mProfileProc = null;
13132 mProfileFile = null;
13133 mProfileType = 0;
13134 mAutoStopProfiler = false;
13135 }
13136
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013137 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013138 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013139
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013140 try {
13141 synchronized (this) {
13142 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13143 // its own permission.
13144 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13145 != PackageManager.PERMISSION_GRANTED) {
13146 throw new SecurityException("Requires permission "
13147 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013148 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013149
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013150 if (start && fd == null) {
13151 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013152 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013153
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013154 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013155 if (process != null) {
13156 try {
13157 int pid = Integer.parseInt(process);
13158 synchronized (mPidsSelfLocked) {
13159 proc = mPidsSelfLocked.get(pid);
13160 }
13161 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013162 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013163
13164 if (proc == null) {
13165 HashMap<String, SparseArray<ProcessRecord>> all
13166 = mProcessNames.getMap();
13167 SparseArray<ProcessRecord> procs = all.get(process);
13168 if (procs != null && procs.size() > 0) {
13169 proc = procs.valueAt(0);
13170 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013171 }
13172 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013173
13174 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013175 throw new IllegalArgumentException("Unknown process: " + process);
13176 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013177
13178 if (start) {
13179 stopProfilerLocked(null, null, 0);
13180 setProfileApp(proc.info, proc.processName, path, fd, false);
13181 mProfileProc = proc;
13182 mProfileType = profileType;
13183 try {
13184 fd = fd.dup();
13185 } catch (IOException e) {
13186 fd = null;
13187 }
13188 proc.thread.profilerControl(start, path, fd, profileType);
13189 fd = null;
13190 mProfileFd = null;
13191 } else {
13192 stopProfilerLocked(proc, path, profileType);
13193 if (fd != null) {
13194 try {
13195 fd.close();
13196 } catch (IOException e) {
13197 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013198 }
13199 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013200
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013201 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013202 }
13203 } catch (RemoteException e) {
13204 throw new IllegalStateException("Process disappeared");
13205 } finally {
13206 if (fd != null) {
13207 try {
13208 fd.close();
13209 } catch (IOException e) {
13210 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013211 }
13212 }
13213 }
Andy McFadden824c5102010-07-09 16:26:57 -070013214
13215 public boolean dumpHeap(String process, boolean managed,
13216 String path, ParcelFileDescriptor fd) throws RemoteException {
13217
13218 try {
13219 synchronized (this) {
13220 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13221 // its own permission (same as profileControl).
13222 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13223 != PackageManager.PERMISSION_GRANTED) {
13224 throw new SecurityException("Requires permission "
13225 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13226 }
13227
13228 if (fd == null) {
13229 throw new IllegalArgumentException("null fd");
13230 }
13231
13232 ProcessRecord proc = null;
13233 try {
13234 int pid = Integer.parseInt(process);
13235 synchronized (mPidsSelfLocked) {
13236 proc = mPidsSelfLocked.get(pid);
13237 }
13238 } catch (NumberFormatException e) {
13239 }
13240
13241 if (proc == null) {
13242 HashMap<String, SparseArray<ProcessRecord>> all
13243 = mProcessNames.getMap();
13244 SparseArray<ProcessRecord> procs = all.get(process);
13245 if (procs != null && procs.size() > 0) {
13246 proc = procs.valueAt(0);
13247 }
13248 }
13249
13250 if (proc == null || proc.thread == null) {
13251 throw new IllegalArgumentException("Unknown process: " + process);
13252 }
13253
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013254 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13255 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013256 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13257 throw new SecurityException("Process not debuggable: " + proc);
13258 }
13259 }
13260
13261 proc.thread.dumpHeap(managed, path, fd);
13262 fd = null;
13263 return true;
13264 }
13265 } catch (RemoteException e) {
13266 throw new IllegalStateException("Process disappeared");
13267 } finally {
13268 if (fd != null) {
13269 try {
13270 fd.close();
13271 } catch (IOException e) {
13272 }
13273 }
13274 }
13275 }
13276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013277 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13278 public void monitor() {
13279 synchronized (this) { }
13280 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013281
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013282 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013283 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13284 ProcessRecord processRecord = mLruProcesses.get(i);
13285 try {
13286 if (processRecord.thread != null) {
13287 processRecord.thread.setCoreSettings(settings);
13288 }
13289 } catch (RemoteException re) {
13290 /* ignore */
13291 }
13292 }
13293 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013294
13295 // Multi-user methods
13296
Amith Yamasani742a6712011-05-04 14:49:28 -070013297 private int mCurrentUserId;
13298 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
13299
13300 public boolean switchUser(int userId) {
13301 final int callingUid = Binder.getCallingUid();
13302 if (callingUid != 0 && callingUid != Process.myUid()) {
13303 Slog.e(TAG, "Trying to switch user from unauthorized app");
13304 return false;
13305 }
13306 if (mCurrentUserId == userId)
13307 return true;
13308
13309 synchronized (this) {
13310 // Check if user is already logged in, otherwise check if user exists first before
13311 // adding to the list of logged in users.
13312 if (mLoggedInUsers.indexOfKey(userId) < 0) {
13313 if (!userExists(userId)) {
13314 return false;
13315 }
13316 mLoggedInUsers.append(userId, userId);
13317 }
13318
13319 mCurrentUserId = userId;
13320 boolean haveActivities = mMainStack.switchUser(userId);
13321 if (!haveActivities) {
13322 startHomeActivityLocked(userId);
13323 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013324
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013325 }
Amith Yamasani13593602012-03-22 16:16:17 -070013326
13327 // Inform of user switch
13328 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13329 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
13330 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
13331
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013332 return true;
13333 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013334
Amith Yamasani52f1d752012-03-28 18:19:29 -070013335 @Override
13336 public UserInfo getCurrentUser() throws RemoteException {
13337 final int callingUid = Binder.getCallingUid();
13338 if (callingUid != 0 && callingUid != Process.myUid()) {
13339 Slog.e(TAG, "Trying to get user from unauthorized app");
13340 return null;
13341 }
13342 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
13343 }
13344
Amith Yamasani13593602012-03-22 16:16:17 -070013345 private void onUserRemoved(Intent intent) {
13346 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
13347 if (extraUserId < 1) return;
13348
13349 // Kill all the processes for the user
13350 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
13351 synchronized (this) {
13352 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
13353 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
13354 SparseArray<ProcessRecord> uids = uidMap.getValue();
13355 for (int i = 0; i < uids.size(); i++) {
13356 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
13357 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
13358 }
13359 }
13360 }
13361
13362 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
13363 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
13364 false, false, true, true, extraUserId);
13365 }
13366 }
13367 }
13368
Amith Yamasani742a6712011-05-04 14:49:28 -070013369 private boolean userExists(int userId) {
13370 try {
Amith Yamasani13593602012-03-22 16:16:17 -070013371 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
13372 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013373 } catch (RemoteException re) {
13374 // Won't happen, in same process
13375 }
13376
13377 return false;
13378 }
13379
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013380 private void checkValidCaller(int uid, int userId) {
13381 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
13382
13383 throw new SecurityException("Caller uid=" + uid
13384 + " is not privileged to communicate with user=" + userId);
13385 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013386
13387 private int applyUserId(int uid, int userId) {
13388 return UserId.getUid(userId, uid);
13389 }
13390
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013391 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013392 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013393 ApplicationInfo newInfo = new ApplicationInfo(info);
13394 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013395 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13396 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013397 return newInfo;
13398 }
13399
13400 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013401 if (aInfo == null
13402 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013403 return aInfo;
13404 }
13405
13406 ActivityInfo info = new ActivityInfo(aInfo);
13407 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13408 return info;
13409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410}