blob: 375f7f1ba94bcfeb2f3b5f920b82ecfe00353a6d [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) {
Amith Yamasani82644082012-08-03 13:09:11 -07002308 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
2309 startFlags, profileFile, profileFd, options, UserId.getCallingUserId());
2310 }
2311
2312 public final int startActivityAsUser(IApplicationThread caller,
2313 Intent intent, String resolvedType, IBinder resultTo,
2314 String resultWho, int requestCode, int startFlags,
2315 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002316 enforceNotIsolatedCaller("startActivity");
Amith Yamasani82644082012-08-03 13:09:11 -07002317 if (userId != UserId.getCallingUserId()) {
2318 // Requesting a different user, make sure that they have the permission
2319 if (checkComponentPermission(
2320 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2321 Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
2322 == PackageManager.PERMISSION_GRANTED) {
2323 // Translate to the current user id, if caller wasn't aware
2324 if (userId == UserId.USER_CURRENT) {
2325 userId = mCurrentUserId;
2326 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002327 } else {
Amith Yamasani82644082012-08-03 13:09:11 -07002328 String msg = "Permission Denial: "
2329 + "Request to startActivity as user " + userId
2330 + " but is calling from user " + UserId.getCallingUserId()
2331 + "; this requires "
2332 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
2333 Slog.w(TAG, msg);
2334 throw new SecurityException(msg);
2335 }
2336 } else {
2337 if (intent.getCategories() != null
2338 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2339 // Requesting home, set the identity to the current user
2340 // HACK!
2341 userId = mCurrentUserId;
2342 } else {
2343 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2344 // the current user's userId
2345 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2346 userId = 0;
2347 } else {
2348 userId = Binder.getOrigCallingUser();
2349 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002350 }
2351 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002352 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002353 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2354 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002355 }
2356
2357 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002358 Intent intent, String resolvedType, IBinder resultTo,
2359 String resultWho, int requestCode, int startFlags, String profileFile,
2360 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002361 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002362 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002363 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002364 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002365 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2366 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002367 return res;
2368 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002369
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002370 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002371 Intent intent, String resolvedType, IBinder resultTo,
2372 String resultWho, int requestCode, int startFlags, Configuration config,
2373 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002374 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002375 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002376 resultTo, resultWho, requestCode, startFlags,
2377 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002378 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002379 }
2380
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002381 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002382 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002383 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002384 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002385 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002386 // Refuse possible leaked file descriptors
2387 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2388 throw new IllegalArgumentException("File descriptors passed in Intent");
2389 }
2390
2391 IIntentSender sender = intent.getTarget();
2392 if (!(sender instanceof PendingIntentRecord)) {
2393 throw new IllegalArgumentException("Bad PendingIntent object");
2394 }
2395
2396 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002397
2398 synchronized (this) {
2399 // If this is coming from the currently resumed activity, it is
2400 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002401 if (mMainStack.mResumedActivity != null
2402 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002403 Binder.getCallingUid()) {
2404 mAppSwitchesAllowedTime = 0;
2405 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002406 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002407 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2408 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002409 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002410 }
2411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002413 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 // Refuse possible leaked file descriptors
2415 if (intent != null && intent.hasFileDescriptors() == true) {
2416 throw new IllegalArgumentException("File descriptors passed in Intent");
2417 }
2418
2419 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002420 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2421 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002422 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 return false;
2424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 if (r.app == null || r.app.thread == null) {
2426 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002427 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 return false;
2429 }
2430 intent = new Intent(intent);
2431 // The caller is not allowed to change the data.
2432 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2433 // And we are resetting to find the next component...
2434 intent.setComponent(null);
2435
2436 ActivityInfo aInfo = null;
2437 try {
2438 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002439 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002441 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2442 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443
2444 // Look for the original activity in the list...
2445 final int N = resolves != null ? resolves.size() : 0;
2446 for (int i=0; i<N; i++) {
2447 ResolveInfo rInfo = resolves.get(i);
2448 if (rInfo.activityInfo.packageName.equals(r.packageName)
2449 && rInfo.activityInfo.name.equals(r.info.name)) {
2450 // We found the current one... the next matching is
2451 // after it.
2452 i++;
2453 if (i<N) {
2454 aInfo = resolves.get(i).activityInfo;
2455 }
2456 break;
2457 }
2458 }
2459 } catch (RemoteException e) {
2460 }
2461
2462 if (aInfo == null) {
2463 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002464 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 return false;
2466 }
2467
2468 intent.setComponent(new ComponentName(
2469 aInfo.applicationInfo.packageName, aInfo.name));
2470 intent.setFlags(intent.getFlags()&~(
2471 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2472 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2473 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2474 Intent.FLAG_ACTIVITY_NEW_TASK));
2475
2476 // Okay now we need to start the new activity, replacing the
2477 // currently running activity. This is a little tricky because
2478 // we want to start the new one as if the current one is finished,
2479 // but not finish the current one first so that there is no flicker.
2480 // And thus...
2481 final boolean wasFinishing = r.finishing;
2482 r.finishing = true;
2483
2484 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002485 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 final String resultWho = r.resultWho;
2487 final int requestCode = r.requestCode;
2488 r.resultTo = null;
2489 if (resultTo != null) {
2490 resultTo.removeResultsLocked(r, resultWho, requestCode);
2491 }
2492
2493 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002494 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002495 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2496 resultWho, requestCode, -1, r.launchedFromUid, 0,
2497 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 Binder.restoreCallingIdentity(origId);
2499
2500 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002501 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 return false;
2503 }
2504 return true;
2505 }
2506 }
2507
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002508 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002510 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002511
2512 // This is so super not safe, that only the system (or okay root)
2513 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002514 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002515 final int callingUid = Binder.getCallingUid();
2516 if (callingUid != 0 && callingUid != Process.myUid()) {
2517 throw new SecurityException(
2518 "startActivityInPackage only available to the system");
2519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520
Amith Yamasani742a6712011-05-04 14:49:28 -07002521 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002522 resultTo, resultWho, requestCode, startFlags,
2523 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002524 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002525 }
2526
2527 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002529 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002530 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002531 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002532 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002533 }
2534
2535 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002536 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2537 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002538
2539 // This is so super not safe, that only the system (or okay root)
2540 // can do it.
2541 final int callingUid = Binder.getCallingUid();
2542 if (callingUid != 0 && callingUid != Process.myUid()) {
2543 throw new SecurityException(
2544 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002546 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002547 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002548 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002553 // Quick case: check if the top-most recent task is the same.
2554 if (N > 0 && mRecentTasks.get(0) == task) {
2555 return;
2556 }
2557 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 for (int i=0; i<N; i++) {
2559 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002560 if (task.userId == tr.userId
2561 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2562 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 mRecentTasks.remove(i);
2564 i--;
2565 N--;
2566 if (task.intent == null) {
2567 // If the new recent task we are adding is not fully
2568 // specified, then replace it with the existing recent task.
2569 task = tr;
2570 }
2571 }
2572 }
2573 if (N >= MAX_RECENT_TASKS) {
2574 mRecentTasks.remove(N-1);
2575 }
2576 mRecentTasks.add(0, task);
2577 }
2578
2579 public void setRequestedOrientation(IBinder token,
2580 int requestedOrientation) {
2581 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002582 ActivityRecord r = mMainStack.isInStackLocked(token);
2583 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 return;
2585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002587 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002589 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002590 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (config != null) {
2592 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002593 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596 }
2597 Binder.restoreCallingIdentity(origId);
2598 }
2599 }
2600
2601 public int getRequestedOrientation(IBinder token) {
2602 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002603 ActivityRecord r = mMainStack.isInStackLocked(token);
2604 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2606 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002607 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 }
2609 }
2610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 /**
2612 * This is the internal entry point for handling Activity.finish().
2613 *
2614 * @param token The Binder token referencing the Activity we want to finish.
2615 * @param resultCode Result code, if any, from this Activity.
2616 * @param resultData Result data (Intent), if any, from this Activity.
2617 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002618 * @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 -08002619 */
2620 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2621 // Refuse possible leaked file descriptors
2622 if (resultData != null && resultData.hasFileDescriptors() == true) {
2623 throw new IllegalArgumentException("File descriptors passed in Intent");
2624 }
2625
2626 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002627 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002629 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 if (next != null) {
2631 // ask watcher if this is allowed
2632 boolean resumeOK = true;
2633 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002634 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002636 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 }
2638
2639 if (!resumeOK) {
2640 return false;
2641 }
2642 }
2643 }
2644 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 resultData, "app-request");
2647 Binder.restoreCallingIdentity(origId);
2648 return res;
2649 }
2650 }
2651
Dianne Hackborn860755f2010-06-03 18:47:52 -07002652 public final void finishHeavyWeightApp() {
2653 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2654 != PackageManager.PERMISSION_GRANTED) {
2655 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2656 + Binder.getCallingPid()
2657 + ", uid=" + Binder.getCallingUid()
2658 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2659 Slog.w(TAG, msg);
2660 throw new SecurityException(msg);
2661 }
2662
2663 synchronized(this) {
2664 if (mHeavyWeightProcess == null) {
2665 return;
2666 }
2667
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002668 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002669 mHeavyWeightProcess.activities);
2670 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002671 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002672 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002673 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002674 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002675 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002676 null, "finish-heavy");
2677 }
2678 }
2679 }
2680
2681 mHeavyWeightProcess = null;
2682 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2683 }
2684 }
2685
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002686 public void crashApplication(int uid, int initialPid, String packageName,
2687 String message) {
2688 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2689 != PackageManager.PERMISSION_GRANTED) {
2690 String msg = "Permission Denial: crashApplication() from pid="
2691 + Binder.getCallingPid()
2692 + ", uid=" + Binder.getCallingUid()
2693 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2694 Slog.w(TAG, msg);
2695 throw new SecurityException(msg);
2696 }
2697
2698 synchronized(this) {
2699 ProcessRecord proc = null;
2700
2701 // Figure out which process to kill. We don't trust that initialPid
2702 // still has any relation to current pids, so must scan through the
2703 // list.
2704 synchronized (mPidsSelfLocked) {
2705 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2706 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002707 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002708 continue;
2709 }
2710 if (p.pid == initialPid) {
2711 proc = p;
2712 break;
2713 }
2714 for (String str : p.pkgList) {
2715 if (str.equals(packageName)) {
2716 proc = p;
2717 }
2718 }
2719 }
2720 }
2721
2722 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002723 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002724 + " initialPid=" + initialPid
2725 + " packageName=" + packageName);
2726 return;
2727 }
2728
2729 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002730 if (proc.pid == Process.myPid()) {
2731 Log.w(TAG, "crashApplication: trying to crash self!");
2732 return;
2733 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002734 long ident = Binder.clearCallingIdentity();
2735 try {
2736 proc.thread.scheduleCrash(message);
2737 } catch (RemoteException e) {
2738 }
2739 Binder.restoreCallingIdentity(ident);
2740 }
2741 }
2742 }
2743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 public final void finishSubActivity(IBinder token, String resultWho,
2745 int requestCode) {
2746 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002748 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 Binder.restoreCallingIdentity(origId);
2750 }
2751 }
2752
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002753 public boolean finishActivityAffinity(IBinder token) {
2754 synchronized(this) {
2755 final long origId = Binder.clearCallingIdentity();
2756 boolean res = mMainStack.finishActivityAffinityLocked(token);
2757 Binder.restoreCallingIdentity(origId);
2758 return res;
2759 }
2760 }
2761
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002762 public boolean willActivityBeVisible(IBinder token) {
2763 synchronized(this) {
2764 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2766 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002767 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002768 return true;
2769 }
2770 if (r.fullscreen && !r.finishing) {
2771 return false;
2772 }
2773 }
2774 return true;
2775 }
2776 }
2777
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002778 public void overridePendingTransition(IBinder token, String packageName,
2779 int enterAnim, int exitAnim) {
2780 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002781 ActivityRecord self = mMainStack.isInStackLocked(token);
2782 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002783 return;
2784 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002785
2786 final long origId = Binder.clearCallingIdentity();
2787
2788 if (self.state == ActivityState.RESUMED
2789 || self.state == ActivityState.PAUSING) {
2790 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002791 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002792 }
2793
2794 Binder.restoreCallingIdentity(origId);
2795 }
2796 }
2797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 * Main function for removing an existing process from the activity manager
2800 * as a result of that process going away. Clears out all connections
2801 * to the process.
2802 */
2803 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002804 boolean restarting, boolean allowRestart) {
2805 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002807 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 }
2809
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002810 if (mProfileProc == app) {
2811 clearProfilerLocked();
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002815 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2816 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2817 mMainStack.mPausingActivity = null;
2818 }
2819 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2820 mMainStack.mLastPausedActivity = null;
2821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822
2823 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002824 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825
2826 boolean atTop = true;
2827 boolean hasVisibleActivities = false;
2828
2829 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002831 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 TAG, "Removing app " + app + " from history with " + i + " entries");
2833 while (i > 0) {
2834 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002835 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002836 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2838 if (r.app == app) {
2839 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002840 if (ActivityStack.DEBUG_ADD_REMOVE) {
2841 RuntimeException here = new RuntimeException("here");
2842 here.fillInStackTrace();
2843 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2844 + ": haveState=" + r.haveState
2845 + " stateNotNeeded=" + r.stateNotNeeded
2846 + " finishing=" + r.finishing
2847 + " state=" + r.state, here);
2848 }
2849 if (!r.finishing) {
2850 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002851 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2852 System.identityHashCode(r),
2853 r.task.taskId, r.shortComponentName,
2854 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002855 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002856 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857
2858 } else {
2859 // We have the current state for this activity, so
2860 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 TAG, "Keeping entry, setting app to null");
2863 if (r.visible) {
2864 hasVisibleActivities = true;
2865 }
2866 r.app = null;
2867 r.nowVisible = false;
2868 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002869 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2870 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 r.icicle = null;
2872 }
2873 }
2874
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002875 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 }
2877 atTop = false;
2878 }
2879
2880 app.activities.clear();
2881
2882 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002883 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 + " running instrumentation " + app.instrumentationClass);
2885 Bundle info = new Bundle();
2886 info.putString("shortMsg", "Process crashed.");
2887 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2888 }
2889
2890 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002891 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 // If there was nothing to resume, and we are not already
2893 // restarting this process, but there is a visible activity that
2894 // is hosted by the process... then make sure all visible
2895 // activities are running, taking care of restarting this
2896 // process.
2897 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002898 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 }
2900 }
2901 }
2902 }
2903
2904 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2905 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002907 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2908 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2910 return i;
2911 }
2912 }
2913 return -1;
2914 }
2915
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002916 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 IApplicationThread thread) {
2918 if (thread == null) {
2919 return null;
2920 }
2921
2922 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002923 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 IApplicationThread thread) {
2928
2929 mProcDeaths[0]++;
2930
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002931 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2932 synchronized (stats) {
2933 stats.noteProcessDiedLocked(app.info.uid, pid);
2934 }
2935
Magnus Edlund7bb25812010-02-24 15:45:06 +01002936 // Clean up already done if the process has been re-started.
2937 if (app.pid == pid && app.thread != null &&
2938 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002939 if (!app.killedBackground) {
2940 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2941 + ") has died.");
2942 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002943 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002944 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 TAG, "Dying app: " + app + ", pid: " + pid
2946 + ", thread: " + thread.asBinder());
2947 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002948 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949
2950 if (doLowMem) {
2951 // If there are no longer any background processes running,
2952 // and the app that died was not running instrumentation,
2953 // then tell everyone we are now low on memory.
2954 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002955 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2956 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002957 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 haveBg = true;
2959 break;
2960 }
2961 }
2962
2963 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002964 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002965 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002966 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2967 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002968 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002969 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2970 // The low memory report is overriding any current
2971 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002972 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002973 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002974 rec.lastRequestedGc = 0;
2975 } else {
2976 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002978 rec.reportLowMemory = true;
2979 rec.lastLowMemory = now;
2980 mProcessesToGc.remove(rec);
2981 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 }
2983 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002984 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002985 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002988 } else if (app.pid != pid) {
2989 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002990 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002991 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002992 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002993 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002994 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 + thread.asBinder());
2996 }
2997 }
2998
Dan Egnor42471dd2010-01-07 17:25:22 -08002999 /**
3000 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003001 * @param clearTraces causes the dump file to be erased prior to the new
3002 * traces being written, if true; when false, the new traces will be
3003 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003004 * @param firstPids of dalvik VM processes to dump stack traces for first
3005 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003006 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003007 * @return file containing stack traces, or null if no dump file is configured
3008 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003009 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003010 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003011 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3012 if (tracesPath == null || tracesPath.length() == 0) {
3013 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003015
3016 File tracesFile = new File(tracesPath);
3017 try {
3018 File tracesDir = tracesFile.getParentFile();
3019 if (!tracesDir.exists()) tracesFile.mkdirs();
3020 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3021
Christopher Tate6ee412d2010-05-28 12:01:56 -07003022 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003023 tracesFile.createNewFile();
3024 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3025 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003026 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003027 return null;
3028 }
3029
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003030 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003031 return tracesFile;
3032 }
3033
3034 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003035 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003036 // Use a FileObserver to detect when traces finish writing.
3037 // The order of traces is considered important to maintain for legibility.
3038 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3039 public synchronized void onEvent(int event, String path) { notify(); }
3040 };
3041
3042 try {
3043 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003044
3045 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003046 if (firstPids != null) {
3047 try {
3048 int num = firstPids.size();
3049 for (int i = 0; i < num; i++) {
3050 synchronized (observer) {
3051 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3052 observer.wait(200); // Wait for write-close, give up after 200msec
3053 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003054 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003055 } catch (InterruptedException e) {
3056 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003057 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003058 }
3059
3060 // Next measure CPU usage.
3061 if (processStats != null) {
3062 processStats.init();
3063 System.gc();
3064 processStats.update();
3065 try {
3066 synchronized (processStats) {
3067 processStats.wait(500); // measure over 1/2 second.
3068 }
3069 } catch (InterruptedException e) {
3070 }
3071 processStats.update();
3072
3073 // We'll take the stack crawls of just the top apps using CPU.
3074 final int N = processStats.countWorkingStats();
3075 int numProcs = 0;
3076 for (int i=0; i<N && numProcs<5; i++) {
3077 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3078 if (lastPids.indexOfKey(stats.pid) >= 0) {
3079 numProcs++;
3080 try {
3081 synchronized (observer) {
3082 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3083 observer.wait(200); // Wait for write-close, give up after 200msec
3084 }
3085 } catch (InterruptedException e) {
3086 Log.wtf(TAG, e);
3087 }
3088
3089 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003090 }
3091 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003092
Dan Egnor42471dd2010-01-07 17:25:22 -08003093 } finally {
3094 observer.stopWatching();
3095 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003096
3097 if (nativeProcs != null) {
3098 int[] pids = Process.getPidsForCommands(nativeProcs);
3099 if (pids != null) {
3100 for (int pid : pids) {
3101 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3102 }
3103 }
3104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
3106
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003107 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003108 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003109 return;
3110 }
3111 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3112 if (tracesPath == null || tracesPath.length() == 0) {
3113 return;
3114 }
3115
3116 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3117 StrictMode.allowThreadDiskWrites();
3118 try {
3119 final File tracesFile = new File(tracesPath);
3120 final File tracesDir = tracesFile.getParentFile();
3121 final File tracesTmp = new File(tracesDir, "__tmp__");
3122 try {
3123 if (!tracesDir.exists()) tracesFile.mkdirs();
3124 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3125
3126 if (tracesFile.exists()) {
3127 tracesTmp.delete();
3128 tracesFile.renameTo(tracesTmp);
3129 }
3130 StringBuilder sb = new StringBuilder();
3131 Time tobj = new Time();
3132 tobj.set(System.currentTimeMillis());
3133 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3134 sb.append(": ");
3135 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3136 sb.append(" since ");
3137 sb.append(msg);
3138 FileOutputStream fos = new FileOutputStream(tracesFile);
3139 fos.write(sb.toString().getBytes());
3140 if (app == null) {
3141 fos.write("\n*** No application process!".getBytes());
3142 }
3143 fos.close();
3144 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3145 } catch (IOException e) {
3146 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3147 return;
3148 }
3149
3150 if (app != null) {
3151 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3152 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003153 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003154 }
3155
3156 File lastTracesFile = null;
3157 File curTracesFile = null;
3158 for (int i=9; i>=0; i--) {
3159 String name = String.format("slow%02d.txt", i);
3160 curTracesFile = new File(tracesDir, name);
3161 if (curTracesFile.exists()) {
3162 if (lastTracesFile != null) {
3163 curTracesFile.renameTo(lastTracesFile);
3164 } else {
3165 curTracesFile.delete();
3166 }
3167 }
3168 lastTracesFile = curTracesFile;
3169 }
3170 tracesFile.renameTo(curTracesFile);
3171 if (tracesTmp.exists()) {
3172 tracesTmp.renameTo(tracesFile);
3173 }
3174 } finally {
3175 StrictMode.setThreadPolicy(oldPolicy);
3176 }
3177 }
3178
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003179 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3180 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003181 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3182 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3183
Dianne Hackborn287952c2010-09-22 22:34:31 -07003184 if (mController != null) {
3185 try {
3186 // 0 == continue, -1 = kill process immediately
3187 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3188 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3189 } catch (RemoteException e) {
3190 mController = null;
3191 }
3192 }
3193
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003194 long anrTime = SystemClock.uptimeMillis();
3195 if (MONITOR_CPU_USAGE) {
3196 updateCpuStatsNow();
3197 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003198
3199 synchronized (this) {
3200 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3201 if (mShuttingDown) {
3202 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3203 return;
3204 } else if (app.notResponding) {
3205 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3206 return;
3207 } else if (app.crashing) {
3208 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3209 return;
3210 }
3211
3212 // In case we come through here for the same app before completing
3213 // this one, mark as anring now so we will bail out.
3214 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003215
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003216 // Log the ANR to the event log.
3217 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3218 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003219
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003220 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003221 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003222
3223 int parentPid = app.pid;
3224 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003225 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003226
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003227 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003228
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003229 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3230 ProcessRecord r = mLruProcesses.get(i);
3231 if (r != null && r.thread != null) {
3232 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003233 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3234 if (r.persistent) {
3235 firstPids.add(pid);
3236 } else {
3237 lastPids.put(pid, Boolean.TRUE);
3238 }
3239 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 }
3242 }
3243
Dan Egnor42471dd2010-01-07 17:25:22 -08003244 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003245 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003246 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003247 info.append("ANR in ").append(app.processName);
3248 if (activity != null && activity.shortComponentName != null) {
3249 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003250 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003251 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003253 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003255 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003256 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258
Dianne Hackborn287952c2010-09-22 22:34:31 -07003259 final ProcessStats processStats = new ProcessStats(true);
3260
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003261 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003262
Dan Egnor42471dd2010-01-07 17:25:22 -08003263 String cpuInfo = null;
3264 if (MONITOR_CPU_USAGE) {
3265 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003266 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003267 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003268 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003269 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003270 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 }
3272
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003273 info.append(processStats.printCurrentState(anrTime));
3274
Joe Onorato8a9b2202010-02-26 18:56:32 -08003275 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003276 if (tracesFile == null) {
3277 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3278 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3279 }
3280
Jeff Sharkeya353d262011-10-28 11:12:06 -07003281 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3282 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003283
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003284 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003286 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3287 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003289 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3290 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 }
3292 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003293 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 }
3295 }
3296
Dan Egnor42471dd2010-01-07 17:25:22 -08003297 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3298 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3299 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003300
3301 synchronized (this) {
3302 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003303 Slog.w(TAG, "Killing " + app + ": background ANR");
3304 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3305 app.processName, app.setAdj, "background ANR");
3306 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003307 return;
3308 }
3309
3310 // Set the app's notResponding state, and look up the errorReportReceiver
3311 makeAppNotRespondingLocked(app,
3312 activity != null ? activity.shortComponentName : null,
3313 annotation != null ? "ANR " + annotation : "ANR",
3314 info.toString());
3315
3316 // Bring up the infamous App Not Responding dialog
3317 Message msg = Message.obtain();
3318 HashMap map = new HashMap();
3319 msg.what = SHOW_NOT_RESPONDING_MSG;
3320 msg.obj = map;
3321 map.put("app", app);
3322 if (activity != null) {
3323 map.put("activity", activity);
3324 }
3325
3326 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 }
3329
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003330 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3331 if (!mLaunchWarningShown) {
3332 mLaunchWarningShown = true;
3333 mHandler.post(new Runnable() {
3334 @Override
3335 public void run() {
3336 synchronized (ActivityManagerService.this) {
3337 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3338 d.show();
3339 mHandler.postDelayed(new Runnable() {
3340 @Override
3341 public void run() {
3342 synchronized (ActivityManagerService.this) {
3343 d.dismiss();
3344 mLaunchWarningShown = false;
3345 }
3346 }
3347 }, 4000);
3348 }
3349 }
3350 });
3351 }
3352 }
3353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003355 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003356 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 int uid = Binder.getCallingUid();
3358 int pid = Binder.getCallingPid();
3359 long callingId = Binder.clearCallingIdentity();
3360 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003361 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 int pkgUid = -1;
3363 synchronized(this) {
3364 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003365 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 } catch (RemoteException e) {
3367 }
3368 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003369 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 return false;
3371 }
3372 if (uid == pkgUid || checkComponentPermission(
3373 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003374 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003376 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 } else {
3378 throw new SecurityException(pid+" does not have permission:"+
3379 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3380 "for process:"+packageName);
3381 }
3382 }
3383
3384 try {
3385 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003386 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3388 Uri.fromParts("package", packageName, null));
3389 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003390 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003391 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 } catch (RemoteException e) {
3393 }
3394 } finally {
3395 Binder.restoreCallingIdentity(callingId);
3396 }
3397 return true;
3398 }
3399
Dianne Hackborn03abb812010-01-04 18:43:19 -08003400 public void killBackgroundProcesses(final String packageName) {
3401 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3402 != PackageManager.PERMISSION_GRANTED &&
3403 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3404 != PackageManager.PERMISSION_GRANTED) {
3405 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 + Binder.getCallingPid()
3407 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003408 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003409 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 throw new SecurityException(msg);
3411 }
3412
Amith Yamasani483f3b02012-03-13 16:08:00 -07003413 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 long callingId = Binder.clearCallingIdentity();
3415 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003416 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 int pkgUid = -1;
3418 synchronized(this) {
3419 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003420 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 } catch (RemoteException e) {
3422 }
3423 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003424 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 return;
3426 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003427 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003428 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3429 }
3430 } finally {
3431 Binder.restoreCallingIdentity(callingId);
3432 }
3433 }
3434
3435 public void killAllBackgroundProcesses() {
3436 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3437 != PackageManager.PERMISSION_GRANTED) {
3438 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3439 + Binder.getCallingPid()
3440 + ", uid=" + Binder.getCallingUid()
3441 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3442 Slog.w(TAG, msg);
3443 throw new SecurityException(msg);
3444 }
3445
3446 long callingId = Binder.clearCallingIdentity();
3447 try {
3448 synchronized(this) {
3449 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3450 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3451 final int NA = apps.size();
3452 for (int ia=0; ia<NA; ia++) {
3453 ProcessRecord app = apps.valueAt(ia);
3454 if (app.persistent) {
3455 // we don't kill persistent processes
3456 continue;
3457 }
3458 if (app.removed) {
3459 procs.add(app);
3460 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3461 app.removed = true;
3462 procs.add(app);
3463 }
3464 }
3465 }
3466
3467 int N = procs.size();
3468 for (int i=0; i<N; i++) {
3469 removeProcessLocked(procs.get(i), false, true, "kill all background");
3470 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003471 }
3472 } finally {
3473 Binder.restoreCallingIdentity(callingId);
3474 }
3475 }
3476
3477 public void forceStopPackage(final String packageName) {
3478 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3479 != PackageManager.PERMISSION_GRANTED) {
3480 String msg = "Permission Denial: forceStopPackage() from pid="
3481 + Binder.getCallingPid()
3482 + ", uid=" + Binder.getCallingUid()
3483 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003484 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003485 throw new SecurityException(msg);
3486 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003487 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003488 long callingId = Binder.clearCallingIdentity();
3489 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003490 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003491 int pkgUid = -1;
3492 synchronized(this) {
3493 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003494 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003495 } catch (RemoteException e) {
3496 }
3497 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003498 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003499 return;
3500 }
3501 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003502 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003503 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003504 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003505 } catch (IllegalArgumentException e) {
3506 Slog.w(TAG, "Failed trying to unstop package "
3507 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 }
3510 } finally {
3511 Binder.restoreCallingIdentity(callingId);
3512 }
3513 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003514
3515 /*
3516 * The pkg name and uid have to be specified.
3517 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3518 */
3519 public void killApplicationWithUid(String pkg, int uid) {
3520 if (pkg == null) {
3521 return;
3522 }
3523 // Make sure the uid is valid.
3524 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003525 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003526 return;
3527 }
3528 int callerUid = Binder.getCallingUid();
3529 // Only the system server can kill an application
3530 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003531 // Post an aysnc message to kill the application
3532 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3533 msg.arg1 = uid;
3534 msg.arg2 = 0;
3535 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003536 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003537 } else {
3538 throw new SecurityException(callerUid + " cannot kill pkg: " +
3539 pkg);
3540 }
3541 }
3542
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003543 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003544 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003545
3546 final int uid = Binder.getCallingUid();
3547 final long origId = Binder.clearCallingIdentity();
3548 synchronized (this) {
3549 closeSystemDialogsLocked(uid, reason);
3550 }
3551 Binder.restoreCallingIdentity(origId);
3552 }
3553
3554 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003555 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003556 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003557 if (reason != null) {
3558 intent.putExtra("reason", reason);
3559 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003560 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003561
Dianne Hackborne302a162012-05-15 14:58:32 -07003562 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3563 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003564 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003565 r.stack.finishActivityLocked(r, i,
3566 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003567 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003568 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003569
3570 broadcastIntentLocked(null, null, intent, null,
3571 null, 0, null, null, null, false, false, -1,
3572 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003573 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003574
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003575 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003576 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003577 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003578 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3579 for (int i=pids.length-1; i>=0; i--) {
3580 infos[i] = new Debug.MemoryInfo();
3581 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003582 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003583 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003584 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003585
Dianne Hackbornb437e092011-08-05 17:50:29 -07003586 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003587 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003588 long[] pss = new long[pids.length];
3589 for (int i=pids.length-1; i>=0; i--) {
3590 pss[i] = Debug.getPss(pids[i]);
3591 }
3592 return pss;
3593 }
3594
Christopher Tate5e1ab332009-09-01 20:32:49 -07003595 public void killApplicationProcess(String processName, int uid) {
3596 if (processName == null) {
3597 return;
3598 }
3599
3600 int callerUid = Binder.getCallingUid();
3601 // Only the system server can kill an application
3602 if (callerUid == Process.SYSTEM_UID) {
3603 synchronized (this) {
3604 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003605 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003606 try {
3607 app.thread.scheduleSuicide();
3608 } catch (RemoteException e) {
3609 // If the other end already died, then our work here is done.
3610 }
3611 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003612 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003613 + processName + " / " + uid);
3614 }
3615 }
3616 } else {
3617 throw new SecurityException(callerUid + " cannot kill app process: " +
3618 processName);
3619 }
3620 }
3621
Dianne Hackborn03abb812010-01-04 18:43:19 -08003622 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003623 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3625 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003626 if (!mProcessesReady) {
3627 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 intent.putExtra(Intent.EXTRA_UID, uid);
3630 broadcastIntentLocked(null, null, intent,
3631 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003632 false, false,
3633 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003636 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003637 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003638 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003639 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640
Dianne Hackborn03abb812010-01-04 18:43:19 -08003641 // Remove all processes this package may have touched: all with the
3642 // same UID (except for the system or root user), and all whose name
3643 // matches the package name.
3644 final String procNamePrefix = packageName + ":";
3645 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3646 final int NA = apps.size();
3647 for (int ia=0; ia<NA; ia++) {
3648 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003649 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003650 // we don't kill persistent processes
3651 continue;
3652 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003653 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003654 if (doit) {
3655 procs.add(app);
3656 }
Amith Yamasani13593602012-03-22 16:16:17 -07003657 // If uid is specified and the uid and process name match
3658 // Or, the uid is not specified and the process name matches
3659 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003660 || ((app.processName.equals(packageName)
3661 || app.processName.startsWith(procNamePrefix))
3662 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003663 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003664 if (!doit) {
3665 return true;
3666 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003667 app.removed = true;
3668 procs.add(app);
3669 }
3670 }
3671 }
3672 }
3673
3674 int N = procs.size();
3675 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003676 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003677 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003678 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003679 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003680
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003681 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003682 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003683 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003684 int i;
3685 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 if (uid < 0) {
3688 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003689 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 } catch (RemoteException e) {
3691 }
3692 }
3693
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003694 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003695 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003696
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003697 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3698 while (badApps.hasNext()) {
3699 SparseArray<Long> ba = badApps.next();
3700 if (ba.get(uid) != null) {
3701 badApps.remove();
3702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
3704 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003705
3706 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003707 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003709 TaskRecord lastTask = null;
3710 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003712 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003713 if (r.userId == userId
3714 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003715 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003716 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003717 if (r.finishing) {
3718 // If this activity is just finishing, then it is not
3719 // interesting as far as something to stop.
3720 continue;
3721 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003722 return true;
3723 }
3724 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003725 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003726 if (samePackage) {
3727 if (r.app != null) {
3728 r.app.removed = true;
3729 }
3730 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003732 lastTask = r.task;
3733 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003734 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003735 i--;
3736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 }
3738 }
3739
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003740 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3741 if (!doit) {
3742 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003744 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003746
3747 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003748 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003749 if (provider.info.packageName.equals(name)
3750 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3751 if (!doit) {
3752 return true;
3753 }
3754 didSomething = true;
3755 providers.add(provider);
3756 }
3757 }
3758
3759 N = providers.size();
3760 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003761 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003762 }
3763
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003764 if (doit) {
3765 if (purgeCache) {
3766 AttributeCache ac = AttributeCache.instance();
3767 if (ac != null) {
3768 ac.removePackage(name);
3769 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003770 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003771 if (mBooted) {
3772 mMainStack.resumeTopActivityLocked(null);
3773 mMainStack.scheduleIdleLocked();
3774 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003775 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003776
3777 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 }
3779
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003780 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003781 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003783 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003784 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003785 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 + "/" + uid + ")");
3787
3788 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003789 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003790 if (mHeavyWeightProcess == app) {
3791 mHeavyWeightProcess = null;
3792 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 boolean needRestart = false;
3795 if (app.pid > 0 && app.pid != MY_PID) {
3796 int pid = app.pid;
3797 synchronized (mPidsSelfLocked) {
3798 mPidsSelfLocked.remove(pid);
3799 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3800 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003801 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003802 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003803 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003804 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003806 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003808 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 } else {
3810 needRestart = true;
3811 }
3812 }
3813 } else {
3814 mRemovedProcesses.add(app);
3815 }
3816
3817 return needRestart;
3818 }
3819
3820 private final void processStartTimedOutLocked(ProcessRecord app) {
3821 final int pid = app.pid;
3822 boolean gone = false;
3823 synchronized (mPidsSelfLocked) {
3824 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3825 if (knownApp != null && knownApp.thread == null) {
3826 mPidsSelfLocked.remove(pid);
3827 gone = true;
3828 }
3829 }
3830
3831 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003832 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003833 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003834 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003835 mProcessNames.remove(app.processName, app.uid);
3836 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003837 if (mHeavyWeightProcess == app) {
3838 mHeavyWeightProcess = null;
3839 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3840 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003841 // Take care of any launching providers waiting for this process.
3842 checkAppInLaunchingProvidersLocked(app, true);
3843 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003844 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003845 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3846 app.processName, app.setAdj, "start timeout");
3847 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003848 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003849 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003850 try {
3851 IBackupManager bm = IBackupManager.Stub.asInterface(
3852 ServiceManager.getService(Context.BACKUP_SERVICE));
3853 bm.agentDisconnected(app.info.packageName);
3854 } catch (RemoteException e) {
3855 // Can't happen; the backup manager is local
3856 }
3857 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003858 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003859 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003860 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003863 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 }
3865 }
3866
3867 private final boolean attachApplicationLocked(IApplicationThread thread,
3868 int pid) {
3869
3870 // Find the application record that is being attached... either via
3871 // the pid if we are running in multiple processes, or just pull the
3872 // next app record if we are emulating process with anonymous threads.
3873 ProcessRecord app;
3874 if (pid != MY_PID && pid >= 0) {
3875 synchronized (mPidsSelfLocked) {
3876 app = mPidsSelfLocked.get(pid);
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 } else {
3879 app = null;
3880 }
3881
3882 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003883 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003885 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003887 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } else {
3889 try {
3890 thread.scheduleExit();
3891 } catch (Exception e) {
3892 // Ignore exceptions.
3893 }
3894 }
3895 return false;
3896 }
3897
3898 // If this application record is still attached to a previous
3899 // process, clean it up now.
3900 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003901 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
3903
3904 // Tell the process all about itself.
3905
Joe Onorato8a9b2202010-02-26 18:56:32 -08003906 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 TAG, "Binding process pid " + pid + " to record " + app);
3908
3909 String processName = app.processName;
3910 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003911 AppDeathRecipient adr = new AppDeathRecipient(
3912 app, pid, thread);
3913 thread.asBinder().linkToDeath(adr, 0);
3914 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 } catch (RemoteException e) {
3916 app.resetPackageList();
3917 startProcessLocked(app, "link fail", processName);
3918 return false;
3919 }
3920
Doug Zongker2bec3d42009-12-04 12:52:44 -08003921 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922
3923 app.thread = thread;
3924 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003925 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3926 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 app.forcingToForeground = null;
3928 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003929 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 app.debugging = false;
3931
3932 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3933
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003934 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003935 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003937 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003938 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003939 }
3940
Joe Onorato8a9b2202010-02-26 18:56:32 -08003941 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 TAG, "New app record " + app
3943 + " thread=" + thread.asBinder() + " pid=" + pid);
3944 try {
3945 int testMode = IApplicationThread.DEBUG_OFF;
3946 if (mDebugApp != null && mDebugApp.equals(processName)) {
3947 testMode = mWaitForDebugger
3948 ? IApplicationThread.DEBUG_WAIT
3949 : IApplicationThread.DEBUG_ON;
3950 app.debugging = true;
3951 if (mDebugTransient) {
3952 mDebugApp = mOrigDebugApp;
3953 mWaitForDebugger = mOrigWaitForDebugger;
3954 }
3955 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003956 String profileFile = app.instrumentationProfileFile;
3957 ParcelFileDescriptor profileFd = null;
3958 boolean profileAutoStop = false;
3959 if (mProfileApp != null && mProfileApp.equals(processName)) {
3960 mProfileProc = app;
3961 profileFile = mProfileFile;
3962 profileFd = mProfileFd;
3963 profileAutoStop = mAutoStopProfiler;
3964 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003965 boolean enableOpenGlTrace = false;
3966 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3967 enableOpenGlTrace = true;
3968 mOpenGlTraceApp = null;
3969 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003970
Christopher Tate181fafa2009-05-14 11:12:14 -07003971 // If the app is being launched for restore or full backup, set it up specially
3972 boolean isRestrictedBackupMode = false;
3973 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3974 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003975 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003976 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3977 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003978
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003979 ensurePackageDexOpt(app.instrumentationInfo != null
3980 ? app.instrumentationInfo.packageName
3981 : app.info.packageName);
3982 if (app.instrumentationClass != null) {
3983 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003984 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003985 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003986 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003987 ApplicationInfo appInfo = app.instrumentationInfo != null
3988 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003989 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003990 if (profileFd != null) {
3991 profileFd = profileFd.dup();
3992 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003993 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003994 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003995 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3996 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003997 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003998 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003999 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004000 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 } catch (Exception e) {
4002 // todo: Yikes! What should we do? For now we will try to
4003 // start another process, but that could easily get us in
4004 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004005 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006
4007 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004008 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 startProcessLocked(app, "bind fail", processName);
4010 return false;
4011 }
4012
4013 // Remove this record from the list of starting applications.
4014 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004015 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4016 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 mProcessesOnHold.remove(app);
4018
4019 boolean badApp = false;
4020 boolean didSomething = false;
4021
4022 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004023 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004024 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004025 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 && processName.equals(hr.processName)) {
4027 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004028 if (mHeadless) {
4029 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4030 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 didSomething = true;
4032 }
4033 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 + hr.intent.getComponent().flattenToShortString(), e);
4036 badApp = true;
4037 }
4038 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004039 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
4041 }
4042
4043 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004044 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004046 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 badApp = true;
4049 }
4050 }
4051
Christopher Tatef46723b2012-01-26 14:19:24 -08004052 // Check if a next-broadcast receiver is in this process...
4053 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004055 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004057 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 }
4060 }
4061
Christopher Tate181fafa2009-05-14 11:12:14 -07004062 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004063 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004064 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004065 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004066 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004067 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4068 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4069 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004070 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004071 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004072 e.printStackTrace();
4073 }
4074 }
4075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 if (badApp) {
4077 // todo: Also need to kill application to deal with all
4078 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004079 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 return false;
4081 }
4082
4083 if (!didSomething) {
4084 updateOomAdjLocked();
4085 }
4086
4087 return true;
4088 }
4089
4090 public final void attachApplication(IApplicationThread thread) {
4091 synchronized (this) {
4092 int callingPid = Binder.getCallingPid();
4093 final long origId = Binder.clearCallingIdentity();
4094 attachApplicationLocked(thread, callingPid);
4095 Binder.restoreCallingIdentity(origId);
4096 }
4097 }
4098
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004099 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004101 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4102 if (stopProfiling) {
4103 synchronized (this) {
4104 if (mProfileProc == r.app) {
4105 if (mProfileFd != null) {
4106 try {
4107 mProfileFd.close();
4108 } catch (IOException e) {
4109 }
4110 clearProfilerLocked();
4111 }
4112 }
4113 }
4114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 Binder.restoreCallingIdentity(origId);
4116 }
4117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004119 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004120 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004122
4123 synchronized (this) {
4124 updateEventDispatchingLocked();
4125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
4127
Dianne Hackborn661cd522011-08-22 00:26:20 -07004128 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004129 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004130 mWindowManager.showBootMessage(msg, always);
4131 }
4132
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004133 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004134 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004135 final long token = Binder.clearCallingIdentity();
4136 try {
4137 synchronized (this) {
4138 if (mLockScreenShown) {
4139 mLockScreenShown = false;
4140 comeOutOfSleepIfNeededLocked();
4141 }
4142 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004143 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004144 } finally {
4145 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004146 }
4147 }
4148
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004149 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004150 IntentFilter pkgFilter = new IntentFilter();
4151 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4152 pkgFilter.addDataScheme("package");
4153 mContext.registerReceiver(new BroadcastReceiver() {
4154 @Override
4155 public void onReceive(Context context, Intent intent) {
4156 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4157 if (pkgs != null) {
4158 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004159 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004160 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4161 setResultCode(Activity.RESULT_OK);
4162 return;
4163 }
4164 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004165 }
4166 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004167 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004168 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004169
4170 IntentFilter userFilter = new IntentFilter();
4171 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4172 mContext.registerReceiver(new BroadcastReceiver() {
4173 @Override
4174 public void onReceive(Context context, Intent intent) {
4175 onUserRemoved(intent);
4176 }
4177 }, userFilter);
4178
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004179 synchronized (this) {
4180 // Ensure that any processes we had put on hold are now started
4181 // up.
4182 final int NP = mProcessesOnHold.size();
4183 if (NP > 0) {
4184 ArrayList<ProcessRecord> procs =
4185 new ArrayList<ProcessRecord>(mProcessesOnHold);
4186 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004187 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4188 + procs.get(ip));
4189 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004190 }
4191 }
4192
4193 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004194 // Start looking for apps that are abusing wake locks.
4195 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004196 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004197 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004198 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004199 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004200 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004201 broadcastIntentLocked(null, null,
4202 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4203 null, null, 0, null, null,
4204 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004205 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004206 }
4207 }
4208 }
4209
4210 final void ensureBootCompleted() {
4211 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004212 boolean enableScreen;
4213 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004214 booting = mBooting;
4215 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004216 enableScreen = !mBooted;
4217 mBooted = true;
4218 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004219
4220 if (booting) {
4221 finishBooting();
4222 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004223
4224 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004225 enableScreenAfterBoot();
4226 }
4227 }
4228
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004229 public final void activityPaused(IBinder token) {
4230 final long origId = Binder.clearCallingIdentity();
4231 mMainStack.activityPaused(token, false);
4232 Binder.restoreCallingIdentity(origId);
4233 }
4234
4235 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4236 CharSequence description) {
4237 if (localLOGV) Slog.v(
4238 TAG, "Activity stopped: token=" + token);
4239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 // Refuse possible leaked file descriptors
4241 if (icicle != null && icicle.hasFileDescriptors()) {
4242 throw new IllegalArgumentException("File descriptors passed in Bundle");
4243 }
4244
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004245 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246
4247 final long origId = Binder.clearCallingIdentity();
4248
4249 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004250 r = mMainStack.isInStackLocked(token);
4251 if (r != null) {
4252 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 }
4254 }
4255
4256 if (r != null) {
4257 sendPendingThumbnail(r, null, null, null, false);
4258 }
4259
4260 trimApplications();
4261
4262 Binder.restoreCallingIdentity(origId);
4263 }
4264
4265 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004266 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004267 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 }
4269
4270 public String getCallingPackage(IBinder token) {
4271 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004272 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004273 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 }
4275 }
4276
4277 public ComponentName getCallingActivity(IBinder token) {
4278 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004279 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 return r != null ? r.intent.getComponent() : null;
4281 }
4282 }
4283
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004284 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004285 ActivityRecord r = mMainStack.isInStackLocked(token);
4286 if (r == null) {
4287 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004289 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 }
4291
4292 public ComponentName getActivityClassForToken(IBinder token) {
4293 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004294 ActivityRecord r = mMainStack.isInStackLocked(token);
4295 if (r == null) {
4296 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300 }
4301
4302 public String getPackageForToken(IBinder token) {
4303 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004304 ActivityRecord r = mMainStack.isInStackLocked(token);
4305 if (r == null) {
4306 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004308 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 }
4310 }
4311
4312 public IIntentSender getIntentSender(int type,
4313 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004314 int requestCode, Intent[] intents, String[] resolvedTypes,
4315 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004316 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004318 if (intents != null) {
4319 if (intents.length < 1) {
4320 throw new IllegalArgumentException("Intents array length must be >= 1");
4321 }
4322 for (int i=0; i<intents.length; i++) {
4323 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004324 if (intent != null) {
4325 if (intent.hasFileDescriptors()) {
4326 throw new IllegalArgumentException("File descriptors passed in Intent");
4327 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004328 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004329 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4330 throw new IllegalArgumentException(
4331 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4332 }
4333 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004334 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004335 }
4336 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004337 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004338 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004339 }
4340 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004341 if (options != null) {
4342 if (options.hasFileDescriptors()) {
4343 throw new IllegalArgumentException("File descriptors passed in options");
4344 }
4345 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 synchronized(this) {
4348 int callingUid = Binder.getCallingUid();
4349 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004350 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004351 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004352 .getPackageUid(packageName, UserId.getUserId(callingUid));
4353 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 String msg = "Permission Denial: getIntentSender() from pid="
4355 + Binder.getCallingPid()
4356 + ", uid=" + Binder.getCallingUid()
4357 + ", (need uid=" + uid + ")"
4358 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004359 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 throw new SecurityException(msg);
4361 }
4362 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004363
Amith Yamasani742a6712011-05-04 14:49:28 -07004364 if (DEBUG_MU)
4365 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4366 + Binder.getOrigCallingUid());
4367 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004368 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 } catch (RemoteException e) {
4371 throw new SecurityException(e);
4372 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004373 }
4374 }
4375
4376 IIntentSender getIntentSenderLocked(int type,
4377 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004378 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4379 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004380 if (DEBUG_MU)
4381 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004382 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004383 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004384 activity = mMainStack.isInStackLocked(token);
4385 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004386 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004388 if (activity.finishing) {
4389 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004391 }
4392
4393 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4394 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4395 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4396 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4397 |PendingIntent.FLAG_UPDATE_CURRENT);
4398
4399 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4400 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004401 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004402 WeakReference<PendingIntentRecord> ref;
4403 ref = mIntentSenderRecords.get(key);
4404 PendingIntentRecord rec = ref != null ? ref.get() : null;
4405 if (rec != null) {
4406 if (!cancelCurrent) {
4407 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004408 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004409 rec.key.requestIntent.replaceExtras(intents != null ?
4410 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004411 }
4412 if (intents != null) {
4413 intents[intents.length-1] = rec.key.requestIntent;
4414 rec.key.allIntents = intents;
4415 rec.key.allResolvedTypes = resolvedTypes;
4416 } else {
4417 rec.key.allIntents = null;
4418 rec.key.allResolvedTypes = null;
4419 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 return rec;
4422 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004423 rec.canceled = true;
4424 mIntentSenderRecords.remove(key);
4425 }
4426 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427 return rec;
4428 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004429 rec = new PendingIntentRecord(this, key, callingUid);
4430 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004431 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004432 if (activity.pendingResults == null) {
4433 activity.pendingResults
4434 = new HashSet<WeakReference<PendingIntentRecord>>();
4435 }
4436 activity.pendingResults.add(rec.ref);
4437 }
4438 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
4440
4441 public void cancelIntentSender(IIntentSender sender) {
4442 if (!(sender instanceof PendingIntentRecord)) {
4443 return;
4444 }
4445 synchronized(this) {
4446 PendingIntentRecord rec = (PendingIntentRecord)sender;
4447 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004448 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004449 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004450 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 String msg = "Permission Denial: cancelIntentSender() from pid="
4452 + Binder.getCallingPid()
4453 + ", uid=" + Binder.getCallingUid()
4454 + " is not allowed to cancel packges "
4455 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004456 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 throw new SecurityException(msg);
4458 }
4459 } catch (RemoteException e) {
4460 throw new SecurityException(e);
4461 }
4462 cancelIntentSenderLocked(rec, true);
4463 }
4464 }
4465
4466 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4467 rec.canceled = true;
4468 mIntentSenderRecords.remove(rec.key);
4469 if (cleanActivity && rec.key.activity != null) {
4470 rec.key.activity.pendingResults.remove(rec.ref);
4471 }
4472 }
4473
4474 public String getPackageForIntentSender(IIntentSender pendingResult) {
4475 if (!(pendingResult instanceof PendingIntentRecord)) {
4476 return null;
4477 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004478 try {
4479 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4480 return res.key.packageName;
4481 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483 return null;
4484 }
4485
Christopher Tatec4a07d12012-04-06 14:19:13 -07004486 public int getUidForIntentSender(IIntentSender sender) {
4487 if (sender instanceof PendingIntentRecord) {
4488 try {
4489 PendingIntentRecord res = (PendingIntentRecord)sender;
4490 return res.uid;
4491 } catch (ClassCastException e) {
4492 }
4493 }
4494 return -1;
4495 }
4496
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004497 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4498 if (!(pendingResult instanceof PendingIntentRecord)) {
4499 return false;
4500 }
4501 try {
4502 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4503 if (res.key.allIntents == null) {
4504 return false;
4505 }
4506 for (int i=0; i<res.key.allIntents.length; i++) {
4507 Intent intent = res.key.allIntents[i];
4508 if (intent.getPackage() != null && intent.getComponent() != null) {
4509 return false;
4510 }
4511 }
4512 return true;
4513 } catch (ClassCastException e) {
4514 }
4515 return false;
4516 }
4517
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004518 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4519 if (!(pendingResult instanceof PendingIntentRecord)) {
4520 return false;
4521 }
4522 try {
4523 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4524 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4525 return true;
4526 }
4527 return false;
4528 } catch (ClassCastException e) {
4529 }
4530 return false;
4531 }
4532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 public void setProcessLimit(int max) {
4534 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4535 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004536 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004537 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004538 mProcessLimitOverride = max;
4539 }
4540 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 }
4542
4543 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004544 synchronized (this) {
4545 return mProcessLimitOverride;
4546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 }
4548
4549 void foregroundTokenDied(ForegroundToken token) {
4550 synchronized (ActivityManagerService.this) {
4551 synchronized (mPidsSelfLocked) {
4552 ForegroundToken cur
4553 = mForegroundProcesses.get(token.pid);
4554 if (cur != token) {
4555 return;
4556 }
4557 mForegroundProcesses.remove(token.pid);
4558 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4559 if (pr == null) {
4560 return;
4561 }
4562 pr.forcingToForeground = null;
4563 pr.foregroundServices = false;
4564 }
4565 updateOomAdjLocked();
4566 }
4567 }
4568
4569 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4570 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4571 "setProcessForeground()");
4572 synchronized(this) {
4573 boolean changed = false;
4574
4575 synchronized (mPidsSelfLocked) {
4576 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004577 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004578 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 return;
4580 }
4581 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4582 if (oldToken != null) {
4583 oldToken.token.unlinkToDeath(oldToken, 0);
4584 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004585 if (pr != null) {
4586 pr.forcingToForeground = null;
4587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 changed = true;
4589 }
4590 if (isForeground && token != null) {
4591 ForegroundToken newToken = new ForegroundToken() {
4592 public void binderDied() {
4593 foregroundTokenDied(this);
4594 }
4595 };
4596 newToken.pid = pid;
4597 newToken.token = token;
4598 try {
4599 token.linkToDeath(newToken, 0);
4600 mForegroundProcesses.put(pid, newToken);
4601 pr.forcingToForeground = token;
4602 changed = true;
4603 } catch (RemoteException e) {
4604 // If the process died while doing this, we will later
4605 // do the cleanup with the process death link.
4606 }
4607 }
4608 }
4609
4610 if (changed) {
4611 updateOomAdjLocked();
4612 }
4613 }
4614 }
4615
4616 // =========================================================
4617 // PERMISSIONS
4618 // =========================================================
4619
4620 static class PermissionController extends IPermissionController.Stub {
4621 ActivityManagerService mActivityManagerService;
4622 PermissionController(ActivityManagerService activityManagerService) {
4623 mActivityManagerService = activityManagerService;
4624 }
4625
4626 public boolean checkPermission(String permission, int pid, int uid) {
4627 return mActivityManagerService.checkPermission(permission, pid,
4628 uid) == PackageManager.PERMISSION_GRANTED;
4629 }
4630 }
4631
4632 /**
4633 * This can be called with or without the global lock held.
4634 */
4635 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004636 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 // We might be performing an operation on behalf of an indirect binder
4638 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4639 // client identity accordingly before proceeding.
4640 Identity tlsIdentity = sCallerIdentity.get();
4641 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004642 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4644 uid = tlsIdentity.uid;
4645 pid = tlsIdentity.pid;
4646 }
4647
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004648 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 return PackageManager.PERMISSION_GRANTED;
4650 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004651
4652 return ActivityManager.checkComponentPermission(permission, uid,
4653 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 }
4655
4656 /**
4657 * As the only public entry point for permissions checking, this method
4658 * can enforce the semantic that requesting a check on a null global
4659 * permission is automatically denied. (Internally a null permission
4660 * string is used when calling {@link #checkComponentPermission} in cases
4661 * when only uid-based security is needed.)
4662 *
4663 * This can be called with or without the global lock held.
4664 */
4665 public int checkPermission(String permission, int pid, int uid) {
4666 if (permission == null) {
4667 return PackageManager.PERMISSION_DENIED;
4668 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004669 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 }
4671
4672 /**
4673 * Binder IPC calls go through the public entry point.
4674 * This can be called with or without the global lock held.
4675 */
4676 int checkCallingPermission(String permission) {
4677 return checkPermission(permission,
4678 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004679 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 }
4681
4682 /**
4683 * This can be called with or without the global lock held.
4684 */
4685 void enforceCallingPermission(String permission, String func) {
4686 if (checkCallingPermission(permission)
4687 == PackageManager.PERMISSION_GRANTED) {
4688 return;
4689 }
4690
4691 String msg = "Permission Denial: " + func + " from pid="
4692 + Binder.getCallingPid()
4693 + ", uid=" + Binder.getCallingUid()
4694 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004695 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 throw new SecurityException(msg);
4697 }
4698
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 /**
4700 * Determine if UID is holding permissions required to access {@link Uri} in
4701 * the given {@link ProviderInfo}. Final permission checking is always done
4702 * in {@link ContentProvider}.
4703 */
4704 private final boolean checkHoldingPermissionsLocked(
4705 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004706 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4707 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004708
4709 if (pi.applicationInfo.uid == uid) {
4710 return true;
4711 } else if (!pi.exported) {
4712 return false;
4713 }
4714
4715 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4716 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004718 // check if target holds top-level <provider> permissions
4719 if (!readMet && pi.readPermission != null
4720 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4721 readMet = true;
4722 }
4723 if (!writeMet && pi.writePermission != null
4724 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4725 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004727
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004728 // track if unprotected read/write is allowed; any denied
4729 // <path-permission> below removes this ability
4730 boolean allowDefaultRead = pi.readPermission == null;
4731 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004732
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004733 // check if target holds any <path-permission> that match uri
4734 final PathPermission[] pps = pi.pathPermissions;
4735 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004736 final String path = uri.getPath();
4737 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004738 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004739 i--;
4740 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741 if (pp.match(path)) {
4742 if (!readMet) {
4743 final String pprperm = pp.getReadPermission();
4744 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4745 + pprperm + " for " + pp.getPath()
4746 + ": match=" + pp.match(path)
4747 + " check=" + pm.checkUidPermission(pprperm, uid));
4748 if (pprperm != null) {
4749 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4750 readMet = true;
4751 } else {
4752 allowDefaultRead = false;
4753 }
4754 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004755 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004756 if (!writeMet) {
4757 final String ppwperm = pp.getWritePermission();
4758 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4759 + ppwperm + " for " + pp.getPath()
4760 + ": match=" + pp.match(path)
4761 + " check=" + pm.checkUidPermission(ppwperm, uid));
4762 if (ppwperm != null) {
4763 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4764 writeMet = true;
4765 } else {
4766 allowDefaultWrite = false;
4767 }
4768 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004769 }
4770 }
4771 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004772 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004773
4774 // grant unprotected <provider> read/write, if not blocked by
4775 // <path-permission> above
4776 if (allowDefaultRead) readMet = true;
4777 if (allowDefaultWrite) writeMet = true;
4778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 } catch (RemoteException e) {
4780 return false;
4781 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004782
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004783 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784 }
4785
4786 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4787 int modeFlags) {
4788 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004789 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 return true;
4791 }
4792 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4793 if (perms == null) return false;
4794 UriPermission perm = perms.get(uri);
4795 if (perm == null) return false;
4796 return (modeFlags&perm.modeFlags) == modeFlags;
4797 }
4798
4799 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004800 enforceNotIsolatedCaller("checkUriPermission");
4801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 // Another redirected-binder-call permissions check as in
4803 // {@link checkComponentPermission}.
4804 Identity tlsIdentity = sCallerIdentity.get();
4805 if (tlsIdentity != null) {
4806 uid = tlsIdentity.uid;
4807 pid = tlsIdentity.pid;
4808 }
4809
Amith Yamasani742a6712011-05-04 14:49:28 -07004810 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 // Our own process gets to do everything.
4812 if (pid == MY_PID) {
4813 return PackageManager.PERMISSION_GRANTED;
4814 }
4815 synchronized(this) {
4816 return checkUriPermissionLocked(uri, uid, modeFlags)
4817 ? PackageManager.PERMISSION_GRANTED
4818 : PackageManager.PERMISSION_DENIED;
4819 }
4820 }
4821
Dianne Hackborn39792d22010-08-19 18:01:52 -07004822 /**
4823 * Check if the targetPkg can be granted permission to access uri by
4824 * the callingUid using the given modeFlags. Throws a security exception
4825 * if callingUid is not allowed to do this. Returns the uid of the target
4826 * if the URI permission grant should be performed; returns -1 if it is not
4827 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004828 * If you already know the uid of the target, you can supply it in
4829 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004830 */
4831 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004832 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004833 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4834 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4835 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004836 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 }
4838
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004839 if (targetPkg != null) {
4840 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4841 "Checking grant " + targetPkg + " permission to " + uri);
4842 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004843
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004844 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845
4846 // If this is not a content: uri, we can't do anything with it.
4847 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004848 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004849 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004850 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 }
4852
4853 String name = uri.getAuthority();
4854 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004855 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4856 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 if (cpr != null) {
4858 pi = cpr.info;
4859 } else {
4860 try {
4861 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004862 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004863 } catch (RemoteException ex) {
4864 }
4865 }
4866 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004867 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004868 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 }
4870
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004871 int targetUid = lastTargetUid;
4872 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004873 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004874 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004875 if (targetUid < 0) {
4876 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4877 "Can't grant URI permission no uid for: " + targetPkg);
4878 return -1;
4879 }
4880 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004881 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 }
4884
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004885 if (targetUid >= 0) {
4886 // First... does the target actually need this permission?
4887 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4888 // No need to grant the target this permission.
4889 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4890 "Target " + targetPkg + " already has full permission to " + uri);
4891 return -1;
4892 }
4893 } else {
4894 // First... there is no target package, so can anyone access it?
4895 boolean allowed = pi.exported;
4896 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4897 if (pi.readPermission != null) {
4898 allowed = false;
4899 }
4900 }
4901 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4902 if (pi.writePermission != null) {
4903 allowed = false;
4904 }
4905 }
4906 if (allowed) {
4907 return -1;
4908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 }
4910
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004911 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 if (!pi.grantUriPermissions) {
4913 throw new SecurityException("Provider " + pi.packageName
4914 + "/" + pi.name
4915 + " does not allow granting of Uri permissions (uri "
4916 + uri + ")");
4917 }
4918 if (pi.uriPermissionPatterns != null) {
4919 final int N = pi.uriPermissionPatterns.length;
4920 boolean allowed = false;
4921 for (int i=0; i<N; i++) {
4922 if (pi.uriPermissionPatterns[i] != null
4923 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4924 allowed = true;
4925 break;
4926 }
4927 }
4928 if (!allowed) {
4929 throw new SecurityException("Provider " + pi.packageName
4930 + "/" + pi.name
4931 + " does not allow granting of permission to path of Uri "
4932 + uri);
4933 }
4934 }
4935
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004936 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004937 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004938 if (callingUid != Process.myUid()) {
4939 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4940 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4941 throw new SecurityException("Uid " + callingUid
4942 + " does not have permission to uri " + uri);
4943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 }
4945 }
4946
Dianne Hackborn39792d22010-08-19 18:01:52 -07004947 return targetUid;
4948 }
4949
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004950 public int checkGrantUriPermission(int callingUid, String targetPkg,
4951 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004952 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004953 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004954 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004955 }
4956 }
4957
Dianne Hackborn39792d22010-08-19 18:01:52 -07004958 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4959 Uri uri, int modeFlags, UriPermissionOwner owner) {
4960 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4961 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4962 if (modeFlags == 0) {
4963 return;
4964 }
4965
4966 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 // to the uri, and the target doesn't. Let's now give this to
4968 // the target.
4969
Joe Onorato8a9b2202010-02-26 18:56:32 -08004970 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004971 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 HashMap<Uri, UriPermission> targetUris
4974 = mGrantedUriPermissions.get(targetUid);
4975 if (targetUris == null) {
4976 targetUris = new HashMap<Uri, UriPermission>();
4977 mGrantedUriPermissions.put(targetUid, targetUris);
4978 }
4979
4980 UriPermission perm = targetUris.get(uri);
4981 if (perm == null) {
4982 perm = new UriPermission(targetUid, uri);
4983 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004987 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004989 } else {
4990 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4991 perm.readOwners.add(owner);
4992 owner.addReadPermission(perm);
4993 }
4994 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4995 perm.writeOwners.add(owner);
4996 owner.addWritePermission(perm);
4997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 }
4999 }
5000
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5002 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005003 if (targetPkg == null) {
5004 throw new NullPointerException("targetPkg");
5005 }
5006
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005007 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005008 if (targetUid < 0) {
5009 return;
5010 }
5011
5012 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5013 }
5014
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005015 static class NeededUriGrants extends ArrayList<Uri> {
5016 final String targetPkg;
5017 final int targetUid;
5018 final int flags;
5019
5020 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5021 targetPkg = _targetPkg;
5022 targetUid = _targetUid;
5023 flags = _flags;
5024 }
5025 }
5026
Dianne Hackborn39792d22010-08-19 18:01:52 -07005027 /**
5028 * Like checkGrantUriPermissionLocked, but takes an Intent.
5029 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005030 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5031 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005032 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005033 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5034 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005035 + " from " + intent + "; flags=0x"
5036 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5037
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005038 if (targetPkg == null) {
5039 throw new NullPointerException("targetPkg");
5040 }
5041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005043 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 }
5045 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005046 ClipData clip = intent.getClipData();
5047 if (data == null && clip == null) {
5048 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005049 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005050 if (data != null) {
5051 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5052 mode, needed != null ? needed.targetUid : -1);
5053 if (target > 0) {
5054 if (needed == null) {
5055 needed = new NeededUriGrants(targetPkg, target, mode);
5056 }
5057 needed.add(data);
5058 }
5059 }
5060 if (clip != null) {
5061 for (int i=0; i<clip.getItemCount(); i++) {
5062 Uri uri = clip.getItemAt(i).getUri();
5063 if (uri != null) {
5064 int target = -1;
5065 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5066 mode, needed != null ? needed.targetUid : -1);
5067 if (target > 0) {
5068 if (needed == null) {
5069 needed = new NeededUriGrants(targetPkg, target, mode);
5070 }
5071 needed.add(uri);
5072 }
5073 } else {
5074 Intent clipIntent = clip.getItemAt(i).getIntent();
5075 if (clipIntent != null) {
5076 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5077 callingUid, targetPkg, clipIntent, mode, needed);
5078 if (newNeeded != null) {
5079 needed = newNeeded;
5080 }
5081 }
5082 }
5083 }
5084 }
5085
5086 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005087 }
5088
5089 /**
5090 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5091 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005092 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5093 UriPermissionOwner owner) {
5094 if (needed != null) {
5095 for (int i=0; i<needed.size(); i++) {
5096 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5097 needed.get(i), needed.flags, owner);
5098 }
5099 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005100 }
5101
5102 void grantUriPermissionFromIntentLocked(int callingUid,
5103 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005104 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005105 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005106 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 return;
5108 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005109
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005110 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
5112
5113 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5114 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005115 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 synchronized(this) {
5117 final ProcessRecord r = getRecordForAppLocked(caller);
5118 if (r == null) {
5119 throw new SecurityException("Unable to find app for caller "
5120 + caller
5121 + " when granting permission to uri " + uri);
5122 }
5123 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005124 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 }
5126 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005127 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
5129
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005130 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 null);
5132 }
5133 }
5134
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005135 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5137 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5138 HashMap<Uri, UriPermission> perms
5139 = mGrantedUriPermissions.get(perm.uid);
5140 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005141 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005142 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 perms.remove(perm.uri);
5144 if (perms.size() == 0) {
5145 mGrantedUriPermissions.remove(perm.uid);
5146 }
5147 }
5148 }
5149 }
5150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5152 int modeFlags) {
5153 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5154 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5155 if (modeFlags == 0) {
5156 return;
5157 }
5158
Joe Onorato8a9b2202010-02-26 18:56:32 -08005159 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005160 "Revoking all granted permissions to " + uri);
5161
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005162 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163
5164 final String authority = uri.getAuthority();
5165 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005166 int userId = UserId.getUserId(callingUid);
5167 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 if (cpr != null) {
5169 pi = cpr.info;
5170 } else {
5171 try {
5172 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005173 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 } catch (RemoteException ex) {
5175 }
5176 }
5177 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005178 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 return;
5180 }
5181
5182 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005183 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 // Right now, if you are not the original owner of the permission,
5185 // you are not allowed to revoke it.
5186 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5187 throw new SecurityException("Uid " + callingUid
5188 + " does not have permission to uri " + uri);
5189 //}
5190 }
5191
5192 // Go through all of the permissions and remove any that match.
5193 final List<String> SEGMENTS = uri.getPathSegments();
5194 if (SEGMENTS != null) {
5195 final int NS = SEGMENTS.size();
5196 int N = mGrantedUriPermissions.size();
5197 for (int i=0; i<N; i++) {
5198 HashMap<Uri, UriPermission> perms
5199 = mGrantedUriPermissions.valueAt(i);
5200 Iterator<UriPermission> it = perms.values().iterator();
5201 toploop:
5202 while (it.hasNext()) {
5203 UriPermission perm = it.next();
5204 Uri targetUri = perm.uri;
5205 if (!authority.equals(targetUri.getAuthority())) {
5206 continue;
5207 }
5208 List<String> targetSegments = targetUri.getPathSegments();
5209 if (targetSegments == null) {
5210 continue;
5211 }
5212 if (targetSegments.size() < NS) {
5213 continue;
5214 }
5215 for (int j=0; j<NS; j++) {
5216 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5217 continue toploop;
5218 }
5219 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005220 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005221 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 perm.clearModes(modeFlags);
5223 if (perm.modeFlags == 0) {
5224 it.remove();
5225 }
5226 }
5227 if (perms.size() == 0) {
5228 mGrantedUriPermissions.remove(
5229 mGrantedUriPermissions.keyAt(i));
5230 N--;
5231 i--;
5232 }
5233 }
5234 }
5235 }
5236
5237 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5238 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005239 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 synchronized(this) {
5241 final ProcessRecord r = getRecordForAppLocked(caller);
5242 if (r == null) {
5243 throw new SecurityException("Unable to find app for caller "
5244 + caller
5245 + " when revoking permission to uri " + uri);
5246 }
5247 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005248 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 return;
5250 }
5251
5252 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5253 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5254 if (modeFlags == 0) {
5255 return;
5256 }
5257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005258 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259
5260 final String authority = uri.getAuthority();
5261 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005262 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 if (cpr != null) {
5264 pi = cpr.info;
5265 } else {
5266 try {
5267 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005268 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 } catch (RemoteException ex) {
5270 }
5271 }
5272 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005273 Slog.w(TAG, "No content provider found for permission revoke: "
5274 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275 return;
5276 }
5277
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005278 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 }
5280 }
5281
Dianne Hackborn7e269642010-08-25 19:50:20 -07005282 @Override
5283 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005284 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005285 synchronized(this) {
5286 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5287 return owner.getExternalTokenLocked();
5288 }
5289 }
5290
5291 @Override
5292 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5293 Uri uri, int modeFlags) {
5294 synchronized(this) {
5295 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5296 if (owner == null) {
5297 throw new IllegalArgumentException("Unknown owner: " + token);
5298 }
5299 if (fromUid != Binder.getCallingUid()) {
5300 if (Binder.getCallingUid() != Process.myUid()) {
5301 // Only system code can grant URI permissions on behalf
5302 // of other users.
5303 throw new SecurityException("nice try");
5304 }
5305 }
5306 if (targetPkg == null) {
5307 throw new IllegalArgumentException("null target");
5308 }
5309 if (uri == null) {
5310 throw new IllegalArgumentException("null uri");
5311 }
5312
5313 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5314 }
5315 }
5316
5317 @Override
5318 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5319 synchronized(this) {
5320 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5321 if (owner == null) {
5322 throw new IllegalArgumentException("Unknown owner: " + token);
5323 }
5324
5325 if (uri == null) {
5326 owner.removeUriPermissionsLocked(mode);
5327 } else {
5328 owner.removeUriPermissionLocked(uri, mode);
5329 }
5330 }
5331 }
5332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5334 synchronized (this) {
5335 ProcessRecord app =
5336 who != null ? getRecordForAppLocked(who) : null;
5337 if (app == null) return;
5338
5339 Message msg = Message.obtain();
5340 msg.what = WAIT_FOR_DEBUGGER_MSG;
5341 msg.obj = app;
5342 msg.arg1 = waiting ? 1 : 0;
5343 mHandler.sendMessage(msg);
5344 }
5345 }
5346
5347 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005348 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5349 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005351 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005352 outInfo.threshold = homeAppMem;
5353 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5354 outInfo.hiddenAppThreshold = hiddenAppMem;
5355 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005356 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005357 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5358 ProcessList.VISIBLE_APP_ADJ);
5359 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5360 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
5362
5363 // =========================================================
5364 // TASK MANAGEMENT
5365 // =========================================================
5366
5367 public List getTasks(int maxNum, int flags,
5368 IThumbnailReceiver receiver) {
5369 ArrayList list = new ArrayList();
5370
5371 PendingThumbnailsRecord pending = null;
5372 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005373 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374
5375 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005376 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5378 + ", receiver=" + receiver);
5379
5380 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5381 != PackageManager.PERMISSION_GRANTED) {
5382 if (receiver != null) {
5383 // If the caller wants to wait for pending thumbnails,
5384 // it ain't gonna get them.
5385 try {
5386 receiver.finished();
5387 } catch (RemoteException ex) {
5388 }
5389 }
5390 String msg = "Permission Denial: getTasks() from pid="
5391 + Binder.getCallingPid()
5392 + ", uid=" + Binder.getCallingUid()
5393 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005394 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 throw new SecurityException(msg);
5396 }
5397
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005398 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005399 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005400 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005401 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 TaskRecord curTask = null;
5403 int numActivities = 0;
5404 int numRunning = 0;
5405 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005406 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005408 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409
5410 // Initialize state for next task if needed.
5411 if (top == null ||
5412 (top.state == ActivityState.INITIALIZING
5413 && top.task == r.task)) {
5414 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 curTask = r.task;
5416 numActivities = numRunning = 0;
5417 }
5418
5419 // Add 'r' into the current task.
5420 numActivities++;
5421 if (r.app != null && r.app.thread != null) {
5422 numRunning++;
5423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424
Joe Onorato8a9b2202010-02-26 18:56:32 -08005425 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 TAG, r.intent.getComponent().flattenToShortString()
5427 + ": task=" + r.task);
5428
5429 // If the next one is a different task, generate a new
5430 // TaskInfo entry for what we have.
5431 if (next == null || next.task != curTask) {
5432 ActivityManager.RunningTaskInfo ci
5433 = new ActivityManager.RunningTaskInfo();
5434 ci.id = curTask.taskId;
5435 ci.baseActivity = r.intent.getComponent();
5436 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005437 if (top.thumbHolder != null) {
5438 ci.description = top.thumbHolder.lastDescription;
5439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 ci.numActivities = numActivities;
5441 ci.numRunning = numRunning;
5442 //System.out.println(
5443 // "#" + maxNum + ": " + " descr=" + ci.description);
5444 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005445 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 TAG, "State=" + top.state + "Idle=" + top.idle
5447 + " app=" + top.app
5448 + " thr=" + (top.app != null ? top.app.thread : null));
5449 if (top.state == ActivityState.RESUMED
5450 || top.state == ActivityState.PAUSING) {
5451 if (top.idle && top.app != null
5452 && top.app.thread != null) {
5453 topRecord = top;
5454 topThumbnail = top.app.thread;
5455 } else {
5456 top.thumbnailNeeded = true;
5457 }
5458 }
5459 if (pending == null) {
5460 pending = new PendingThumbnailsRecord(receiver);
5461 }
5462 pending.pendingRecords.add(top);
5463 }
5464 list.add(ci);
5465 maxNum--;
5466 top = null;
5467 }
5468 }
5469
5470 if (pending != null) {
5471 mPendingThumbnails.add(pending);
5472 }
5473 }
5474
Joe Onorato8a9b2202010-02-26 18:56:32 -08005475 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476
5477 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005478 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005480 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005482 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005483 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 }
5485 }
5486
5487 if (pending == null && receiver != null) {
5488 // In this case all thumbnails were available and the client
5489 // is being asked to be told when the remaining ones come in...
5490 // which is unusually, since the top-most currently running
5491 // activity should never have a canned thumbnail! Oh well.
5492 try {
5493 receiver.finished();
5494 } catch (RemoteException ex) {
5495 }
5496 }
5497
5498 return list;
5499 }
5500
5501 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005502 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005503 final int callingUid = Binder.getCallingUid();
Amith Yamasani82644082012-08-03 13:09:11 -07005504 if (userId != UserId.getCallingUserId()) {
5505 // Check if the caller is holding permissions for cross-user requests.
5506 if (checkComponentPermission(
5507 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5508 Binder.getCallingPid(), callingUid, -1, true)
5509 != PackageManager.PERMISSION_GRANTED) {
5510 String msg = "Permission Denial: "
5511 + "Request to get recent tasks for user " + userId
5512 + " but is calling from user " + UserId.getUserId(callingUid)
5513 + "; this requires "
5514 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5515 Slog.w(TAG, msg);
5516 throw new SecurityException(msg);
5517 } else {
5518 if (userId == UserId.USER_CURRENT) {
5519 userId = mCurrentUserId;
5520 }
5521 }
5522 }
5523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 synchronized (this) {
5525 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5526 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005527 final boolean detailed = checkCallingPermission(
5528 android.Manifest.permission.GET_DETAILED_TASKS)
5529 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005531 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 final int N = mRecentTasks.size();
5534 ArrayList<ActivityManager.RecentTaskInfo> res
5535 = new ArrayList<ActivityManager.RecentTaskInfo>(
5536 maxNum < N ? maxNum : N);
5537 for (int i=0; i<N && maxNum > 0; i++) {
5538 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005539 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005540 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005541 // Return the entry if desired by the caller. We always return
5542 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005543 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005544 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5545 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005546
Dianne Hackborn905577f2011-09-07 18:31:28 -07005547 if (i == 0
5548 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 || (tr.intent == null)
5550 || ((tr.intent.getFlags()
5551 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5552 ActivityManager.RecentTaskInfo rti
5553 = new ActivityManager.RecentTaskInfo();
5554 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005555 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 rti.baseIntent = new Intent(
5557 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005558 if (!detailed) {
5559 rti.baseIntent.replaceExtras((Bundle)null);
5560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005562 rti.description = tr.lastDescription;
5563
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005564 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5565 // Check whether this activity is currently available.
5566 try {
5567 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005568 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005569 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005570 continue;
5571 }
5572 } else if (rti.baseIntent != null) {
5573 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005574 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005575 continue;
5576 }
5577 }
5578 } catch (RemoteException e) {
5579 // Will never happen.
5580 }
5581 }
5582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 res.add(rti);
5584 maxNum--;
5585 }
5586 }
5587 return res;
5588 }
5589 }
5590
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005591 private TaskRecord taskForIdLocked(int id) {
5592 final int N = mRecentTasks.size();
5593 for (int i=0; i<N; i++) {
5594 TaskRecord tr = mRecentTasks.get(i);
5595 if (tr.taskId == id) {
5596 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005597 }
5598 }
5599 return null;
5600 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005601
5602 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5603 synchronized (this) {
5604 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5605 "getTaskThumbnails()");
5606 TaskRecord tr = taskForIdLocked(id);
5607 if (tr != null) {
5608 return mMainStack.getTaskThumbnailsLocked(tr);
5609 }
5610 }
5611 return null;
5612 }
5613
5614 public boolean removeSubTask(int taskId, int subTaskIndex) {
5615 synchronized (this) {
5616 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5617 "removeSubTask()");
5618 long ident = Binder.clearCallingIdentity();
5619 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005620 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5621 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005622 } finally {
5623 Binder.restoreCallingIdentity(ident);
5624 }
5625 }
5626 }
5627
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005628 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5629 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005630 Intent baseIntent = new Intent(
5631 tr.intent != null ? tr.intent : tr.affinityIntent);
5632 ComponentName component = baseIntent.getComponent();
5633 if (component == null) {
5634 Slog.w(TAG, "Now component for base intent of task: " + tr);
5635 return;
5636 }
5637
5638 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005639 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005640
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005641 if (killProcesses) {
5642 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005643 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005644 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005645 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5646 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5647 for (int i=0; i<uids.size(); i++) {
5648 ProcessRecord proc = uids.valueAt(i);
5649 if (proc.userId != tr.userId) {
5650 continue;
5651 }
5652 if (!proc.pkgList.contains(pkg)) {
5653 continue;
5654 }
5655 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005656 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005657 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005658
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005659 // Kill the running processes.
5660 for (int i=0; i<procs.size(); i++) {
5661 ProcessRecord pr = procs.get(i);
5662 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5663 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5664 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5665 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005666 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005667 Process.killProcessQuiet(pr.pid);
5668 } else {
5669 pr.waitingToKill = "remove task";
5670 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005671 }
5672 }
5673 }
5674
5675 public boolean removeTask(int taskId, int flags) {
5676 synchronized (this) {
5677 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5678 "removeTask()");
5679 long ident = Binder.clearCallingIdentity();
5680 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005681 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5682 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005683 if (r != null) {
5684 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005685 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005686 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005687 } else {
5688 TaskRecord tr = null;
5689 int i=0;
5690 while (i < mRecentTasks.size()) {
5691 TaskRecord t = mRecentTasks.get(i);
5692 if (t.taskId == taskId) {
5693 tr = t;
5694 break;
5695 }
5696 i++;
5697 }
5698 if (tr != null) {
5699 if (tr.numActivities <= 0) {
5700 // Caller is just removing a recent task that is
5701 // not actively running. That is easy!
5702 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005703 cleanUpRemovedTaskLocked(tr, flags);
5704 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005705 } else {
5706 Slog.w(TAG, "removeTask: task " + taskId
5707 + " does not have activities to remove, "
5708 + " but numActivities=" + tr.numActivities
5709 + ": " + tr);
5710 }
5711 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005712 }
5713 } finally {
5714 Binder.restoreCallingIdentity(ident);
5715 }
5716 }
5717 return false;
5718 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5721 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005722 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 TaskRecord jt = startTask;
5724
5725 // First look backwards
5726 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005727 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 if (r.task != jt) {
5729 jt = r.task;
5730 if (affinity.equals(jt.affinity)) {
5731 return j;
5732 }
5733 }
5734 }
5735
5736 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005737 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 jt = startTask;
5739 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005740 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 if (r.task != jt) {
5742 if (affinity.equals(jt.affinity)) {
5743 return j;
5744 }
5745 jt = r.task;
5746 }
5747 }
5748
5749 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005750 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 return N-1;
5752 }
5753
5754 return -1;
5755 }
5756
5757 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005758 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005760 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5762 "moveTaskToFront()");
5763
5764 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005765 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5766 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005767 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005768 return;
5769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 final long origId = Binder.clearCallingIdentity();
5771 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005772 TaskRecord tr = taskForIdLocked(task);
5773 if (tr != null) {
5774 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5775 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005777 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5778 // Caller wants the home activity moved with it. To accomplish this,
5779 // we'll just move the home task to the top first.
5780 mMainStack.moveHomeToFrontLocked();
5781 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005782 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005783 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005785 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5786 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005788 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5789 mMainStack.mUserLeaving = true;
5790 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005791 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5792 // Caller wants the home activity moved with it. To accomplish this,
5793 // we'll just move the home task to the top first.
5794 mMainStack.moveHomeToFrontLocked();
5795 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005796 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 return;
5798 }
5799 }
5800 } finally {
5801 Binder.restoreCallingIdentity(origId);
5802 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005803 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 }
5805 }
5806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 public void moveTaskToBack(int task) {
5808 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5809 "moveTaskToBack()");
5810
5811 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005812 if (mMainStack.mResumedActivity != null
5813 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005814 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5815 Binder.getCallingUid(), "Task to back")) {
5816 return;
5817 }
5818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005820 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 Binder.restoreCallingIdentity(origId);
5822 }
5823 }
5824
5825 /**
5826 * Moves an activity, and all of the other activities within the same task, to the bottom
5827 * of the history stack. The activity's order within the task is unchanged.
5828 *
5829 * @param token A reference to the activity we wish to move
5830 * @param nonRoot If false then this only works if the activity is the root
5831 * of a task; if true it will work for any activity in a task.
5832 * @return Returns true if the move completed, false if not.
5833 */
5834 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005835 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 synchronized(this) {
5837 final long origId = Binder.clearCallingIdentity();
5838 int taskId = getTaskForActivityLocked(token, !nonRoot);
5839 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005840 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
5842 Binder.restoreCallingIdentity(origId);
5843 }
5844 return false;
5845 }
5846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 public void moveTaskBackwards(int task) {
5848 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5849 "moveTaskBackwards()");
5850
5851 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005852 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5853 Binder.getCallingUid(), "Task backwards")) {
5854 return;
5855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 final long origId = Binder.clearCallingIdentity();
5857 moveTaskBackwardsLocked(task);
5858 Binder.restoreCallingIdentity(origId);
5859 }
5860 }
5861
5862 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005863 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
5865
5866 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5867 synchronized(this) {
5868 return getTaskForActivityLocked(token, onlyRoot);
5869 }
5870 }
5871
5872 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005873 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 TaskRecord lastTask = null;
5875 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005876 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005877 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 if (!onlyRoot || lastTask != r.task) {
5879 return r.task.taskId;
5880 }
5881 return -1;
5882 }
5883 lastTask = r.task;
5884 }
5885
5886 return -1;
5887 }
5888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 // =========================================================
5890 // THUMBNAILS
5891 // =========================================================
5892
5893 public void reportThumbnail(IBinder token,
5894 Bitmap thumbnail, CharSequence description) {
5895 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5896 final long origId = Binder.clearCallingIdentity();
5897 sendPendingThumbnail(null, token, thumbnail, description, true);
5898 Binder.restoreCallingIdentity(origId);
5899 }
5900
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005901 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 Bitmap thumbnail, CharSequence description, boolean always) {
5903 TaskRecord task = null;
5904 ArrayList receivers = null;
5905
5906 //System.out.println("Send pending thumbnail: " + r);
5907
5908 synchronized(this) {
5909 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005910 r = mMainStack.isInStackLocked(token);
5911 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 return;
5913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005915 if (thumbnail == null && r.thumbHolder != null) {
5916 thumbnail = r.thumbHolder.lastThumbnail;
5917 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 }
5919 if (thumbnail == null && !always) {
5920 // If there is no thumbnail, and this entry is not actually
5921 // going away, then abort for now and pick up the next
5922 // thumbnail we get.
5923 return;
5924 }
5925 task = r.task;
5926
5927 int N = mPendingThumbnails.size();
5928 int i=0;
5929 while (i<N) {
5930 PendingThumbnailsRecord pr =
5931 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5932 //System.out.println("Looking in " + pr.pendingRecords);
5933 if (pr.pendingRecords.remove(r)) {
5934 if (receivers == null) {
5935 receivers = new ArrayList();
5936 }
5937 receivers.add(pr);
5938 if (pr.pendingRecords.size() == 0) {
5939 pr.finished = true;
5940 mPendingThumbnails.remove(i);
5941 N--;
5942 continue;
5943 }
5944 }
5945 i++;
5946 }
5947 }
5948
5949 if (receivers != null) {
5950 final int N = receivers.size();
5951 for (int i=0; i<N; i++) {
5952 try {
5953 PendingThumbnailsRecord pr =
5954 (PendingThumbnailsRecord)receivers.get(i);
5955 pr.receiver.newThumbnail(
5956 task != null ? task.taskId : -1, thumbnail, description);
5957 if (pr.finished) {
5958 pr.receiver.finished();
5959 }
5960 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005961 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 }
5963 }
5964 }
5965 }
5966
5967 // =========================================================
5968 // CONTENT PROVIDERS
5969 // =========================================================
5970
Jeff Brown10e89712011-07-08 18:52:57 -07005971 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5972 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005974 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005975 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005976 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 } catch (RemoteException ex) {
5978 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005979 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005980 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5981 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07005983 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 for (int i=0; i<N; i++) {
5985 ProviderInfo cpi =
5986 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07005987 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
5988 cpi.name, cpi.flags);
5989 if (singleton && UserId.getUserId(app.uid) != 0) {
5990 // This is a singleton provider, but a user besides the
5991 // default user is asking to initialize a process it runs
5992 // in... well, no, it doesn't actually run in this process,
5993 // it runs in the process of the default user. Get rid of it.
5994 providers.remove(i);
5995 N--;
5996 continue;
5997 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005998
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005999 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006000 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006002 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006003 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006005 if (DEBUG_MU)
6006 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 app.pubProviders.put(cpi.name, cpr);
6008 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006009 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 }
6011 }
6012 return providers;
6013 }
6014
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006015 /**
6016 * Check if {@link ProcessRecord} has a possible chance at accessing the
6017 * given {@link ProviderInfo}. Final permission checking is always done
6018 * in {@link ContentProvider}.
6019 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006021 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006023 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006025 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006026 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 return null;
6028 }
6029 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006030 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 == PackageManager.PERMISSION_GRANTED) {
6032 return null;
6033 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006034
6035 PathPermission[] pps = cpi.pathPermissions;
6036 if (pps != null) {
6037 int i = pps.length;
6038 while (i > 0) {
6039 i--;
6040 PathPermission pp = pps[i];
6041 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006042 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006043 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006044 return null;
6045 }
6046 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006047 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006048 == PackageManager.PERMISSION_GRANTED) {
6049 return null;
6050 }
6051 }
6052 }
6053
Dianne Hackbornb424b632010-08-18 15:59:05 -07006054 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6055 if (perms != null) {
6056 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6057 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6058 return null;
6059 }
6060 }
6061 }
6062
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006063 String msg;
6064 if (!cpi.exported) {
6065 msg = "Permission Denial: opening provider " + cpi.name
6066 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6067 + ", uid=" + callingUid + ") that is not exported from uid "
6068 + cpi.applicationInfo.uid;
6069 } else {
6070 msg = "Permission Denial: opening provider " + cpi.name
6071 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6072 + ", uid=" + callingUid + ") requires "
6073 + cpi.readPermission + " or " + cpi.writePermission;
6074 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006075 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return msg;
6077 }
6078
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006079 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6080 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006081 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006082 for (int i=0; i<r.conProviders.size(); i++) {
6083 ContentProviderConnection conn = r.conProviders.get(i);
6084 if (conn.provider == cpr) {
6085 if (DEBUG_PROVIDER) Slog.v(TAG,
6086 "Adding provider requested by "
6087 + r.processName + " from process "
6088 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6089 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6090 if (stable) {
6091 conn.stableCount++;
6092 conn.numStableIncs++;
6093 } else {
6094 conn.unstableCount++;
6095 conn.numUnstableIncs++;
6096 }
6097 return conn;
6098 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006099 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006100 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6101 if (stable) {
6102 conn.stableCount = 1;
6103 conn.numStableIncs = 1;
6104 } else {
6105 conn.unstableCount = 1;
6106 conn.numUnstableIncs = 1;
6107 }
6108 cpr.connections.add(conn);
6109 r.conProviders.add(conn);
6110 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006111 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006112 cpr.addExternalProcessHandleLocked(externalProcessToken);
6113 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006114 }
6115
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006116 boolean decProviderCountLocked(ContentProviderConnection conn,
6117 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6118 if (conn != null) {
6119 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006120 if (DEBUG_PROVIDER) Slog.v(TAG,
6121 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006122 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006123 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006124 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6125 if (stable) {
6126 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006127 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006128 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006129 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006130 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6131 cpr.connections.remove(conn);
6132 conn.client.conProviders.remove(conn);
6133 return true;
6134 }
6135 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006136 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006137 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006138 return false;
6139 }
6140
Amith Yamasani742a6712011-05-04 14:49:28 -07006141 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006142 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006144 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 ProviderInfo cpi = null;
6146
6147 synchronized(this) {
6148 ProcessRecord r = null;
6149 if (caller != null) {
6150 r = getRecordForAppLocked(caller);
6151 if (r == null) {
6152 throw new SecurityException(
6153 "Unable to find app for caller " + caller
6154 + " (pid=" + Binder.getCallingPid()
6155 + ") when getting content provider " + name);
6156 }
6157 }
6158
6159 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006160 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006161 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006162 boolean providerRunning = cpr != null;
6163 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006165 String msg;
6166 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6167 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 }
6169
6170 if (r != null && cpr.canRunHere(r)) {
6171 // This provider has been published or is in the process
6172 // of being published... but it is also allowed to run
6173 // in the caller's process, so don't make a connection
6174 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006175 ContentProviderHolder holder = cpr.newHolder(null);
6176 // don't give caller the provider object, it needs
6177 // to make its own.
6178 holder.provider = null;
6179 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 }
6181
6182 final long origId = Binder.clearCallingIdentity();
6183
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006184 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006186 conn = incProviderCountLocked(r, cpr, token, stable);
6187 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006188 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006189 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006190 // make sure to count it as being accessed and thus
6191 // back up on the LRU list. This is good because
6192 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006193 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006194 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006195 }
6196
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006197 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006198 if (false) {
6199 if (cpr.name.flattenToShortString().equals(
6200 "com.android.providers.calendar/.CalendarProvider2")) {
6201 Slog.v(TAG, "****************** KILLING "
6202 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006203 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006204 }
6205 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006206 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006207 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6208 // NOTE: there is still a race here where a signal could be
6209 // pending on the process even though we managed to update its
6210 // adj level. Not sure what to do about this, but at least
6211 // the race is now smaller.
6212 if (!success) {
6213 // Uh oh... it looks like the provider's process
6214 // has been killed on us. We need to wait for a new
6215 // process to be started, and make sure its death
6216 // doesn't kill our process.
6217 Slog.i(TAG,
6218 "Existing provider " + cpr.name.flattenToShortString()
6219 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006220 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006221 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006222 if (!lastRef) {
6223 // This wasn't the last ref our process had on
6224 // the provider... we have now been killed, bail.
6225 return null;
6226 }
6227 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006228 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 }
6231
6232 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006235 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006236 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006238 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006239 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006240 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 } catch (RemoteException ex) {
6242 }
6243 if (cpi == null) {
6244 return null;
6245 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006246 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6247 cpi.name, cpi.flags);
6248 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006249 userId = 0;
6250 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006251 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006252
Dianne Hackbornb424b632010-08-18 15:59:05 -07006253 String msg;
6254 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6255 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 }
6257
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006258 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006259 && !cpi.processName.equals("system")) {
6260 // If this content provider does not run in the system
6261 // process, and the system is not yet ready to run other
6262 // processes, then fail fast instead of hanging.
6263 throw new IllegalArgumentException(
6264 "Attempt to launch content provider before system ready");
6265 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006266
6267 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006268 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 final boolean firstClass = cpr == null;
6270 if (firstClass) {
6271 try {
6272 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006273 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 getApplicationInfo(
6275 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006276 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006278 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 + cpi.name);
6280 return null;
6281 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006282 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006283 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 } catch (RemoteException ex) {
6285 // pm is in same process, this will never happen.
6286 }
6287 }
6288
6289 if (r != null && cpr.canRunHere(r)) {
6290 // If this is a multiprocess provider, then just return its
6291 // info and allow the caller to instantiate it. Only do
6292 // this if the provider is the same user as the caller's
6293 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006294 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
6296
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006297 if (DEBUG_PROVIDER) {
6298 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006299 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006300 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 }
6302
6303 // This is single process, and our app is now connecting to it.
6304 // See if we are already in the process of launching this
6305 // provider.
6306 final int N = mLaunchingProviders.size();
6307 int i;
6308 for (i=0; i<N; i++) {
6309 if (mLaunchingProviders.get(i) == cpr) {
6310 break;
6311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
6313
6314 // If the provider is not already being launched, then get it
6315 // started.
6316 if (i >= N) {
6317 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006318
6319 try {
6320 // Content provider is now in use, its package can't be stopped.
6321 try {
6322 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006323 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006324 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006325 } catch (IllegalArgumentException e) {
6326 Slog.w(TAG, "Failed trying to unstop package "
6327 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006328 }
6329
6330 ProcessRecord proc = startProcessLocked(cpi.processName,
6331 cpr.appInfo, false, 0, "content provider",
6332 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006333 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006334 if (proc == null) {
6335 Slog.w(TAG, "Unable to launch app "
6336 + cpi.applicationInfo.packageName + "/"
6337 + cpi.applicationInfo.uid + " for provider "
6338 + name + ": process is bad");
6339 return null;
6340 }
6341 cpr.launchingApp = proc;
6342 mLaunchingProviders.add(cpr);
6343 } finally {
6344 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347
6348 // Make sure the provider is published (the same provider class
6349 // may be published under multiple names).
6350 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006351 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006353
Amith Yamasani742a6712011-05-04 14:49:28 -07006354 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006355 conn = incProviderCountLocked(r, cpr, token, stable);
6356 if (conn != null) {
6357 conn.waiting = true;
6358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 }
6360 }
6361
6362 // Wait for the provider to be published...
6363 synchronized (cpr) {
6364 while (cpr.provider == null) {
6365 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006366 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 + cpi.applicationInfo.packageName + "/"
6368 + cpi.applicationInfo.uid + " for provider "
6369 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006370 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 cpi.applicationInfo.packageName,
6372 cpi.applicationInfo.uid, name);
6373 return null;
6374 }
6375 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006376 if (DEBUG_MU) {
6377 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6378 + cpr.launchingApp);
6379 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006380 if (conn != null) {
6381 conn.waiting = true;
6382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 cpr.wait();
6384 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006385 } finally {
6386 if (conn != null) {
6387 conn.waiting = false;
6388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 }
6390 }
6391 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006392 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 }
6394
6395 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006396 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006397 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 if (caller == null) {
6399 String msg = "null IApplicationThread when getting content provider "
6400 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006401 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 throw new SecurityException(msg);
6403 }
6404
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006405 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 }
6407
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006408 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6409 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6410 "Do not have permission in call getContentProviderExternal()");
6411 return getContentProviderExternalUnchecked(name, token);
6412 }
6413
6414 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006415 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
6417
6418 /**
6419 * Drop a content provider from a ProcessRecord's bookkeeping
6420 * @param cpr
6421 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006422 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006423 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006425 ContentProviderConnection conn;
6426 try {
6427 conn = (ContentProviderConnection)connection;
6428 } catch (ClassCastException e) {
6429 String msg ="removeContentProvider: " + connection
6430 + " not a ContentProviderConnection";
6431 Slog.w(TAG, msg);
6432 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006434 if (conn == null) {
6435 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006437 if (decProviderCountLocked(conn, null, null, stable)) {
6438 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 }
6441 }
6442
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006443 public void removeContentProviderExternal(String name, IBinder token) {
6444 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6445 "Do not have permission in call removeContentProviderExternal()");
6446 removeContentProviderExternalUnchecked(name, token);
6447 }
6448
6449 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006451 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6452 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 if(cpr == null) {
6454 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006455 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 return;
6457 }
6458
6459 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006460 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006461 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6462 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006463 if (localCpr.hasExternalProcessHandles()) {
6464 if (localCpr.removeExternalProcessHandleLocked(token)) {
6465 updateOomAdjLocked();
6466 } else {
6467 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6468 + " with no external reference for token: "
6469 + token + ".");
6470 }
6471 } else {
6472 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6473 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 }
6476 }
6477
6478 public final void publishContentProviders(IApplicationThread caller,
6479 List<ContentProviderHolder> providers) {
6480 if (providers == null) {
6481 return;
6482 }
6483
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006484 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006485 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006487 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006488 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 if (r == null) {
6490 throw new SecurityException(
6491 "Unable to find app for caller " + caller
6492 + " (pid=" + Binder.getCallingPid()
6493 + ") when publishing content providers");
6494 }
6495
6496 final long origId = Binder.clearCallingIdentity();
6497
6498 final int N = providers.size();
6499 for (int i=0; i<N; i++) {
6500 ContentProviderHolder src = providers.get(i);
6501 if (src == null || src.info == null || src.provider == null) {
6502 continue;
6503 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006504 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006505 if (DEBUG_MU)
6506 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006508 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006509 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 String names[] = dst.info.authority.split(";");
6511 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006512 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 }
6514
6515 int NL = mLaunchingProviders.size();
6516 int j;
6517 for (j=0; j<NL; j++) {
6518 if (mLaunchingProviders.get(j) == dst) {
6519 mLaunchingProviders.remove(j);
6520 j--;
6521 NL--;
6522 }
6523 }
6524 synchronized (dst) {
6525 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006526 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 dst.notifyAll();
6528 }
6529 updateOomAdjLocked(r);
6530 }
6531 }
6532
6533 Binder.restoreCallingIdentity(origId);
6534 }
6535 }
6536
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006537 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6538 ContentProviderConnection conn;
6539 try {
6540 conn = (ContentProviderConnection)connection;
6541 } catch (ClassCastException e) {
6542 String msg ="refContentProvider: " + connection
6543 + " not a ContentProviderConnection";
6544 Slog.w(TAG, msg);
6545 throw new IllegalArgumentException(msg);
6546 }
6547 if (conn == null) {
6548 throw new NullPointerException("connection is null");
6549 }
6550
6551 synchronized (this) {
6552 if (stable > 0) {
6553 conn.numStableIncs += stable;
6554 }
6555 stable = conn.stableCount + stable;
6556 if (stable < 0) {
6557 throw new IllegalStateException("stableCount < 0: " + stable);
6558 }
6559
6560 if (unstable > 0) {
6561 conn.numUnstableIncs += unstable;
6562 }
6563 unstable = conn.unstableCount + unstable;
6564 if (unstable < 0) {
6565 throw new IllegalStateException("unstableCount < 0: " + unstable);
6566 }
6567
6568 if ((stable+unstable) <= 0) {
6569 throw new IllegalStateException("ref counts can't go to zero here: stable="
6570 + stable + " unstable=" + unstable);
6571 }
6572 conn.stableCount = stable;
6573 conn.unstableCount = unstable;
6574 return !conn.dead;
6575 }
6576 }
6577
6578 public void unstableProviderDied(IBinder connection) {
6579 ContentProviderConnection conn;
6580 try {
6581 conn = (ContentProviderConnection)connection;
6582 } catch (ClassCastException e) {
6583 String msg ="refContentProvider: " + connection
6584 + " not a ContentProviderConnection";
6585 Slog.w(TAG, msg);
6586 throw new IllegalArgumentException(msg);
6587 }
6588 if (conn == null) {
6589 throw new NullPointerException("connection is null");
6590 }
6591
6592 // Safely retrieve the content provider associated with the connection.
6593 IContentProvider provider;
6594 synchronized (this) {
6595 provider = conn.provider.provider;
6596 }
6597
6598 if (provider == null) {
6599 // Um, yeah, we're way ahead of you.
6600 return;
6601 }
6602
6603 // Make sure the caller is being honest with us.
6604 if (provider.asBinder().pingBinder()) {
6605 // Er, no, still looks good to us.
6606 synchronized (this) {
6607 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6608 + " says " + conn + " died, but we don't agree");
6609 return;
6610 }
6611 }
6612
6613 // Well look at that! It's dead!
6614 synchronized (this) {
6615 if (conn.provider.provider != provider) {
6616 // But something changed... good enough.
6617 return;
6618 }
6619
6620 ProcessRecord proc = conn.provider.proc;
6621 if (proc == null || proc.thread == null) {
6622 // Seems like the process is already cleaned up.
6623 return;
6624 }
6625
6626 // As far as we're concerned, this is just like receiving a
6627 // death notification... just a bit prematurely.
6628 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6629 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006630 final long ident = Binder.clearCallingIdentity();
6631 try {
6632 appDiedLocked(proc, proc.pid, proc.thread);
6633 } finally {
6634 Binder.restoreCallingIdentity(ident);
6635 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006636 }
6637 }
6638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006640 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006641 synchronized (mSelf) {
6642 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6643 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006644 if (providers != null) {
6645 for (int i=providers.size()-1; i>=0; i--) {
6646 ProviderInfo pi = (ProviderInfo)providers.get(i);
6647 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6648 Slog.w(TAG, "Not installing system proc provider " + pi.name
6649 + ": not system .apk");
6650 providers.remove(i);
6651 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006652 }
6653 }
6654 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006655 if (providers != null) {
6656 mSystemThread.installSystemProviders(providers);
6657 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006658
6659 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006660
6661 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
6663
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006664 /**
6665 * Allows app to retrieve the MIME type of a URI without having permission
6666 * to access its content provider.
6667 *
6668 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6669 *
6670 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6671 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6672 */
6673 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006674 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006675 final String name = uri.getAuthority();
6676 final long ident = Binder.clearCallingIdentity();
6677 ContentProviderHolder holder = null;
6678
6679 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006680 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006681 if (holder != null) {
6682 return holder.provider.getType(uri);
6683 }
6684 } catch (RemoteException e) {
6685 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6686 return null;
6687 } finally {
6688 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006689 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006690 }
6691 Binder.restoreCallingIdentity(ident);
6692 }
6693
6694 return null;
6695 }
6696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 // =========================================================
6698 // GLOBAL MANAGEMENT
6699 // =========================================================
6700
6701 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006702 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 String proc = customProcess != null ? customProcess : info.processName;
6704 BatteryStatsImpl.Uid.Proc ps = null;
6705 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006706 int uid = info.uid;
6707 if (isolated) {
6708 int userId = UserId.getUserId(uid);
6709 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6710 uid = 0;
6711 while (true) {
6712 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6713 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6714 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6715 }
6716 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6717 mNextIsolatedProcessUid++;
6718 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6719 // No process for this uid, use it.
6720 break;
6721 }
6722 stepsLeft--;
6723 if (stepsLeft <= 0) {
6724 return null;
6725 }
6726 }
6727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 synchronized (stats) {
6729 ps = stats.getProcessStatsLocked(info.uid, proc);
6730 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006731 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 }
6733
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006734 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6735 ProcessRecord app;
6736 if (!isolated) {
6737 app = getProcessRecordLocked(info.processName, info.uid);
6738 } else {
6739 app = null;
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741
6742 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006743 app = newProcessRecordLocked(null, info, null, isolated);
6744 mProcessNames.put(info.processName, app.uid, app);
6745 if (isolated) {
6746 mIsolatedProcesses.put(app.uid, app);
6747 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006748 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 }
6750
Dianne Hackborne7f97212011-02-24 14:40:20 -08006751 // This package really, really can not be stopped.
6752 try {
6753 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006754 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006755 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006756 } catch (IllegalArgumentException e) {
6757 Slog.w(TAG, "Failed trying to unstop package "
6758 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006759 }
6760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6762 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6763 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006764 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 }
6766 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6767 mPersistentStartingProcesses.add(app);
6768 startProcessLocked(app, "added application", app.processName);
6769 }
6770
6771 return app;
6772 }
6773
6774 public void unhandledBack() {
6775 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6776 "unhandledBack()");
6777
6778 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006779 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006780 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 TAG, "Performing unhandledBack(): stack size = " + count);
6782 if (count > 1) {
6783 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006784 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6786 Binder.restoreCallingIdentity(origId);
6787 }
6788 }
6789 }
6790
6791 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006792 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006794 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 ParcelFileDescriptor pfd = null;
6796 if (cph != null) {
6797 // We record the binder invoker's uid in thread-local storage before
6798 // going to the content provider to open the file. Later, in the code
6799 // that handles all permissions checks, we look for this uid and use
6800 // that rather than the Activity Manager's own uid. The effect is that
6801 // we do the check against the caller's permissions even though it looks
6802 // to the content provider like the Activity Manager itself is making
6803 // the request.
6804 sCallerIdentity.set(new Identity(
6805 Binder.getCallingPid(), Binder.getCallingUid()));
6806 try {
6807 pfd = cph.provider.openFile(uri, "r");
6808 } catch (FileNotFoundException e) {
6809 // do nothing; pfd will be returned null
6810 } finally {
6811 // Ensure that whatever happens, we clean up the identity state
6812 sCallerIdentity.remove();
6813 }
6814
6815 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006816 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006818 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 }
6820 return pfd;
6821 }
6822
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006823 // Actually is sleeping or shutting down or whatever else in the future
6824 // is an inactive state.
6825 public boolean isSleeping() {
6826 return mSleeping || mShuttingDown;
6827 }
6828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006830 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6831 != PackageManager.PERMISSION_GRANTED) {
6832 throw new SecurityException("Requires permission "
6833 + android.Manifest.permission.DEVICE_POWER);
6834 }
6835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006837 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006838 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006840 if (!mSleeping) {
6841 mSleeping = true;
6842 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006843
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006844 // Initialize the wake times of all processes.
6845 checkExcessivePowerUsageLocked(false);
6846 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6847 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6848 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 }
6851 }
6852
Dianne Hackborn55280a92009-05-07 15:53:46 -07006853 public boolean shutdown(int timeout) {
6854 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6855 != PackageManager.PERMISSION_GRANTED) {
6856 throw new SecurityException("Requires permission "
6857 + android.Manifest.permission.SHUTDOWN);
6858 }
6859
6860 boolean timedout = false;
6861
6862 synchronized(this) {
6863 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006864 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006865
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006866 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006867 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006868 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006869 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006870 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006871 long delay = endTime - System.currentTimeMillis();
6872 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006873 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006874 timedout = true;
6875 break;
6876 }
6877 try {
6878 this.wait();
6879 } catch (InterruptedException e) {
6880 }
6881 }
6882 }
6883 }
6884
6885 mUsageStatsService.shutdown();
6886 mBatteryStatsService.shutdown();
6887
6888 return timedout;
6889 }
6890
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006891 public final void activitySlept(IBinder token) {
6892 if (localLOGV) Slog.v(
6893 TAG, "Activity slept: token=" + token);
6894
6895 ActivityRecord r = null;
6896
6897 final long origId = Binder.clearCallingIdentity();
6898
6899 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006900 r = mMainStack.isInStackLocked(token);
6901 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006902 mMainStack.activitySleptLocked(r);
6903 }
6904 }
6905
6906 Binder.restoreCallingIdentity(origId);
6907 }
6908
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006909 private void comeOutOfSleepIfNeededLocked() {
6910 if (!mWentToSleep && !mLockScreenShown) {
6911 if (mSleeping) {
6912 mSleeping = false;
6913 mMainStack.awakeFromSleepingLocked();
6914 mMainStack.resumeTopActivityLocked(null);
6915 }
6916 }
6917 }
6918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006920 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6921 != PackageManager.PERMISSION_GRANTED) {
6922 throw new SecurityException("Requires permission "
6923 + android.Manifest.permission.DEVICE_POWER);
6924 }
6925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006927 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006928 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006929 comeOutOfSleepIfNeededLocked();
6930 }
6931 }
6932
Jeff Brownc042ee22012-05-08 13:03:42 -07006933 private void updateEventDispatchingLocked() {
6934 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6935 }
6936
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006937 public void setLockScreenShown(boolean shown) {
6938 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6939 != PackageManager.PERMISSION_GRANTED) {
6940 throw new SecurityException("Requires permission "
6941 + android.Manifest.permission.DEVICE_POWER);
6942 }
6943
6944 synchronized(this) {
6945 mLockScreenShown = shown;
6946 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 }
6948 }
6949
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006950 public void stopAppSwitches() {
6951 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6952 != PackageManager.PERMISSION_GRANTED) {
6953 throw new SecurityException("Requires permission "
6954 + android.Manifest.permission.STOP_APP_SWITCHES);
6955 }
6956
6957 synchronized(this) {
6958 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6959 + APP_SWITCH_DELAY_TIME;
6960 mDidAppSwitch = false;
6961 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6962 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6963 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6964 }
6965 }
6966
6967 public void resumeAppSwitches() {
6968 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6969 != PackageManager.PERMISSION_GRANTED) {
6970 throw new SecurityException("Requires permission "
6971 + android.Manifest.permission.STOP_APP_SWITCHES);
6972 }
6973
6974 synchronized(this) {
6975 // Note that we don't execute any pending app switches... we will
6976 // let those wait until either the timeout, or the next start
6977 // activity request.
6978 mAppSwitchesAllowedTime = 0;
6979 }
6980 }
6981
6982 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6983 String name) {
6984 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6985 return true;
6986 }
6987
6988 final int perm = checkComponentPermission(
6989 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006990 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006991 if (perm == PackageManager.PERMISSION_GRANTED) {
6992 return true;
6993 }
6994
Joe Onorato8a9b2202010-02-26 18:56:32 -08006995 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006996 return false;
6997 }
6998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006999 public void setDebugApp(String packageName, boolean waitForDebugger,
7000 boolean persistent) {
7001 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7002 "setDebugApp()");
7003
7004 // Note that this is not really thread safe if there are multiple
7005 // callers into it at the same time, but that's not a situation we
7006 // care about.
7007 if (persistent) {
7008 final ContentResolver resolver = mContext.getContentResolver();
7009 Settings.System.putString(
7010 resolver, Settings.System.DEBUG_APP,
7011 packageName);
7012 Settings.System.putInt(
7013 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7014 waitForDebugger ? 1 : 0);
7015 }
7016
7017 synchronized (this) {
7018 if (!persistent) {
7019 mOrigDebugApp = mDebugApp;
7020 mOrigWaitForDebugger = mWaitForDebugger;
7021 }
7022 mDebugApp = packageName;
7023 mWaitForDebugger = waitForDebugger;
7024 mDebugTransient = !persistent;
7025 if (packageName != null) {
7026 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007027 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 Binder.restoreCallingIdentity(origId);
7029 }
7030 }
7031 }
7032
Siva Velusamy92a8b222012-03-09 16:24:04 -08007033 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7034 synchronized (this) {
7035 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7036 if (!isDebuggable) {
7037 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7038 throw new SecurityException("Process not debuggable: " + app.packageName);
7039 }
7040 }
7041
7042 mOpenGlTraceApp = processName;
7043 }
7044 }
7045
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007046 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7047 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7048 synchronized (this) {
7049 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7050 if (!isDebuggable) {
7051 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7052 throw new SecurityException("Process not debuggable: " + app.packageName);
7053 }
7054 }
7055 mProfileApp = processName;
7056 mProfileFile = profileFile;
7057 if (mProfileFd != null) {
7058 try {
7059 mProfileFd.close();
7060 } catch (IOException e) {
7061 }
7062 mProfileFd = null;
7063 }
7064 mProfileFd = profileFd;
7065 mProfileType = 0;
7066 mAutoStopProfiler = autoStopProfiler;
7067 }
7068 }
7069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 public void setAlwaysFinish(boolean enabled) {
7071 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7072 "setAlwaysFinish()");
7073
7074 Settings.System.putInt(
7075 mContext.getContentResolver(),
7076 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7077
7078 synchronized (this) {
7079 mAlwaysFinishActivities = enabled;
7080 }
7081 }
7082
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007083 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007085 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007087 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 }
7089 }
7090
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007091 public boolean isUserAMonkey() {
7092 // For now the fact that there is a controller implies
7093 // we have a monkey.
7094 synchronized (this) {
7095 return mController != null;
7096 }
7097 }
7098
Jeff Sharkeya4620792011-05-20 15:29:23 -07007099 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007100 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7101 "registerProcessObserver()");
7102 synchronized (this) {
7103 mProcessObservers.register(observer);
7104 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007105 }
7106
7107 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007108 synchronized (this) {
7109 mProcessObservers.unregister(observer);
7110 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007111 }
7112
Daniel Sandler69a48172010-06-23 16:29:36 -04007113 public void setImmersive(IBinder token, boolean immersive) {
7114 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007115 ActivityRecord r = mMainStack.isInStackLocked(token);
7116 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007117 throw new IllegalArgumentException();
7118 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007119 r.immersive = immersive;
7120 }
7121 }
7122
7123 public boolean isImmersive(IBinder token) {
7124 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007125 ActivityRecord r = mMainStack.isInStackLocked(token);
7126 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007127 throw new IllegalArgumentException();
7128 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007129 return r.immersive;
7130 }
7131 }
7132
7133 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007134 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007135 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007136 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007137 return (r != null) ? r.immersive : false;
7138 }
7139 }
7140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 public final void enterSafeMode() {
7142 synchronized(this) {
7143 // It only makes sense to do this before the system is ready
7144 // and started launching other packages.
7145 if (!mSystemReady) {
7146 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007147 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 } catch (RemoteException e) {
7149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 }
7151 }
7152 }
7153
Jeff Brownb09abc12011-01-13 21:08:27 -08007154 public final void showSafeModeOverlay() {
7155 View v = LayoutInflater.from(mContext).inflate(
7156 com.android.internal.R.layout.safe_mode, null);
7157 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7158 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7159 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7160 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007161 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007162 lp.format = v.getBackground().getOpacity();
7163 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7164 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7165 ((WindowManager)mContext.getSystemService(
7166 Context.WINDOW_SERVICE)).addView(v, lp);
7167 }
7168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 public void noteWakeupAlarm(IIntentSender sender) {
7170 if (!(sender instanceof PendingIntentRecord)) {
7171 return;
7172 }
7173 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7174 synchronized (stats) {
7175 if (mBatteryStatsService.isOnBattery()) {
7176 mBatteryStatsService.enforceCallingPermission();
7177 PendingIntentRecord rec = (PendingIntentRecord)sender;
7178 int MY_UID = Binder.getCallingUid();
7179 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7180 BatteryStatsImpl.Uid.Pkg pkg =
7181 stats.getPackageStatsLocked(uid, rec.key.packageName);
7182 pkg.incWakeupsLocked();
7183 }
7184 }
7185 }
7186
Dianne Hackborn64825172011-03-02 21:32:58 -08007187 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007189 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007191 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 // XXX Note: don't acquire main activity lock here, because the window
7193 // manager calls in with its locks held.
7194
7195 boolean killed = false;
7196 synchronized (mPidsSelfLocked) {
7197 int[] types = new int[pids.length];
7198 int worstType = 0;
7199 for (int i=0; i<pids.length; i++) {
7200 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7201 if (proc != null) {
7202 int type = proc.setAdj;
7203 types[i] = type;
7204 if (type > worstType) {
7205 worstType = type;
7206 }
7207 }
7208 }
7209
Dianne Hackborn64825172011-03-02 21:32:58 -08007210 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007212 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7213 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007214 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007216
7217 // If this is not a secure call, don't let it kill processes that
7218 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007219 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7220 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007221 }
7222
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007223 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 for (int i=0; i<pids.length; i++) {
7225 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7226 if (proc == null) {
7227 continue;
7228 }
7229 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007230 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007231 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007232 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7233 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007235 proc.killedBackground = true;
7236 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 }
7238 }
7239 }
7240 return killed;
7241 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007242
7243 @Override
7244 public boolean killProcessesBelowForeground(String reason) {
7245 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7246 throw new SecurityException("killProcessesBelowForeground() only available to system");
7247 }
7248
7249 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7250 }
7251
7252 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7253 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7254 throw new SecurityException("killProcessesBelowAdj() only available to system");
7255 }
7256
7257 boolean killed = false;
7258 synchronized (mPidsSelfLocked) {
7259 final int size = mPidsSelfLocked.size();
7260 for (int i = 0; i < size; i++) {
7261 final int pid = mPidsSelfLocked.keyAt(i);
7262 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7263 if (proc == null) continue;
7264
7265 final int adj = proc.setAdj;
7266 if (adj > belowAdj && !proc.killedBackground) {
7267 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7268 EventLog.writeEvent(
7269 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7270 killed = true;
7271 proc.killedBackground = true;
7272 Process.killProcessQuiet(pid);
7273 }
7274 }
7275 }
7276 return killed;
7277 }
7278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 public final void startRunning(String pkg, String cls, String action,
7280 String data) {
7281 synchronized(this) {
7282 if (mStartRunning) {
7283 return;
7284 }
7285 mStartRunning = true;
7286 mTopComponent = pkg != null && cls != null
7287 ? new ComponentName(pkg, cls) : null;
7288 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7289 mTopData = data;
7290 if (!mSystemReady) {
7291 return;
7292 }
7293 }
7294
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007295 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 }
7297
7298 private void retrieveSettings() {
7299 final ContentResolver resolver = mContext.getContentResolver();
7300 String debugApp = Settings.System.getString(
7301 resolver, Settings.System.DEBUG_APP);
7302 boolean waitForDebugger = Settings.System.getInt(
7303 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7304 boolean alwaysFinishActivities = Settings.System.getInt(
7305 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7306
7307 Configuration configuration = new Configuration();
7308 Settings.System.getConfiguration(resolver, configuration);
7309
7310 synchronized (this) {
7311 mDebugApp = mOrigDebugApp = debugApp;
7312 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7313 mAlwaysFinishActivities = alwaysFinishActivities;
7314 // This happens before any activities are started, so we can
7315 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007316 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007317 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 }
7319 }
7320
7321 public boolean testIsSystemReady() {
7322 // no need to synchronize(this) just to read & return the value
7323 return mSystemReady;
7324 }
7325
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007326 private static File getCalledPreBootReceiversFile() {
7327 File dataDir = Environment.getDataDirectory();
7328 File systemDir = new File(dataDir, "system");
7329 File fname = new File(systemDir, "called_pre_boots.dat");
7330 return fname;
7331 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007332
7333 static final int LAST_DONE_VERSION = 10000;
7334
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007335 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7336 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7337 File file = getCalledPreBootReceiversFile();
7338 FileInputStream fis = null;
7339 try {
7340 fis = new FileInputStream(file);
7341 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007342 int fvers = dis.readInt();
7343 if (fvers == LAST_DONE_VERSION) {
7344 String vers = dis.readUTF();
7345 String codename = dis.readUTF();
7346 String build = dis.readUTF();
7347 if (android.os.Build.VERSION.RELEASE.equals(vers)
7348 && android.os.Build.VERSION.CODENAME.equals(codename)
7349 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7350 int num = dis.readInt();
7351 while (num > 0) {
7352 num--;
7353 String pkg = dis.readUTF();
7354 String cls = dis.readUTF();
7355 lastDoneReceivers.add(new ComponentName(pkg, cls));
7356 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007357 }
7358 }
7359 } catch (FileNotFoundException e) {
7360 } catch (IOException e) {
7361 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7362 } finally {
7363 if (fis != null) {
7364 try {
7365 fis.close();
7366 } catch (IOException e) {
7367 }
7368 }
7369 }
7370 return lastDoneReceivers;
7371 }
7372
7373 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7374 File file = getCalledPreBootReceiversFile();
7375 FileOutputStream fos = null;
7376 DataOutputStream dos = null;
7377 try {
7378 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7379 fos = new FileOutputStream(file);
7380 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007381 dos.writeInt(LAST_DONE_VERSION);
7382 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007383 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007384 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007385 dos.writeInt(list.size());
7386 for (int i=0; i<list.size(); i++) {
7387 dos.writeUTF(list.get(i).getPackageName());
7388 dos.writeUTF(list.get(i).getClassName());
7389 }
7390 } catch (IOException e) {
7391 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7392 file.delete();
7393 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007394 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007395 if (dos != null) {
7396 try {
7397 dos.close();
7398 } catch (IOException e) {
7399 // TODO Auto-generated catch block
7400 e.printStackTrace();
7401 }
7402 }
7403 }
7404 }
7405
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007406 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 synchronized(this) {
7408 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007409 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 return;
7411 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007412
7413 // Check to see if there are any update receivers to run.
7414 if (!mDidUpdate) {
7415 if (mWaitingUpdate) {
7416 return;
7417 }
7418 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7419 List<ResolveInfo> ris = null;
7420 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007421 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007422 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007423 } catch (RemoteException e) {
7424 }
7425 if (ris != null) {
7426 for (int i=ris.size()-1; i>=0; i--) {
7427 if ((ris.get(i).activityInfo.applicationInfo.flags
7428 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7429 ris.remove(i);
7430 }
7431 }
7432 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007433
7434 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7435
7436 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007437 for (int i=0; i<ris.size(); i++) {
7438 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007439 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7440 if (lastDoneReceivers.contains(comp)) {
7441 ris.remove(i);
7442 i--;
7443 }
7444 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007445
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007446 for (int i=0; i<ris.size(); i++) {
7447 ActivityInfo ai = ris.get(i).activityInfo;
7448 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7449 doneReceivers.add(comp);
7450 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007451 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007452 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007453 finisher = new IIntentReceiver.Stub() {
7454 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007455 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007456 boolean sticky) {
7457 // The raw IIntentReceiver interface is called
7458 // with the AM lock held, so redispatch to
7459 // execute our code without the lock.
7460 mHandler.post(new Runnable() {
7461 public void run() {
7462 synchronized (ActivityManagerService.this) {
7463 mDidUpdate = true;
7464 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007465 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007466 showBootMessage(mContext.getText(
7467 R.string.android_upgrading_complete),
7468 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007469 systemReady(goingCallback);
7470 }
7471 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007472 }
7473 };
7474 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007475 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007476 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007477 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007478 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007479 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007480 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007481 mWaitingUpdate = true;
7482 }
7483 }
7484 }
7485 if (mWaitingUpdate) {
7486 return;
7487 }
7488 mDidUpdate = true;
7489 }
7490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 mSystemReady = true;
7492 if (!mStartRunning) {
7493 return;
7494 }
7495 }
7496
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007497 ArrayList<ProcessRecord> procsToKill = null;
7498 synchronized(mPidsSelfLocked) {
7499 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7500 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7501 if (!isAllowedWhileBooting(proc.info)){
7502 if (procsToKill == null) {
7503 procsToKill = new ArrayList<ProcessRecord>();
7504 }
7505 procsToKill.add(proc);
7506 }
7507 }
7508 }
7509
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007510 synchronized(this) {
7511 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007512 for (int i=procsToKill.size()-1; i>=0; i--) {
7513 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007514 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007515 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007516 }
7517 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007518
7519 // Now that we have cleaned up any update processes, we
7520 // are ready to start launching real processes and know that
7521 // we won't trample on them any more.
7522 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007523 }
7524
Joe Onorato8a9b2202010-02-26 18:56:32 -08007525 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007526 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 SystemClock.uptimeMillis());
7528
7529 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007530 // Make sure we have no pre-ready processes sitting around.
7531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7533 ResolveInfo ri = mContext.getPackageManager()
7534 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007535 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 CharSequence errorMsg = null;
7537 if (ri != null) {
7538 ActivityInfo ai = ri.activityInfo;
7539 ApplicationInfo app = ai.applicationInfo;
7540 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7541 mTopAction = Intent.ACTION_FACTORY_TEST;
7542 mTopData = null;
7543 mTopComponent = new ComponentName(app.packageName,
7544 ai.name);
7545 } else {
7546 errorMsg = mContext.getResources().getText(
7547 com.android.internal.R.string.factorytest_not_system);
7548 }
7549 } else {
7550 errorMsg = mContext.getResources().getText(
7551 com.android.internal.R.string.factorytest_no_action);
7552 }
7553 if (errorMsg != null) {
7554 mTopAction = null;
7555 mTopData = null;
7556 mTopComponent = null;
7557 Message msg = Message.obtain();
7558 msg.what = SHOW_FACTORY_ERROR_MSG;
7559 msg.getData().putCharSequence("msg", errorMsg);
7560 mHandler.sendMessage(msg);
7561 }
7562 }
7563 }
7564
7565 retrieveSettings();
7566
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007567 if (goingCallback != null) goingCallback.run();
7568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 synchronized (this) {
7570 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7571 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007572 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007573 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 if (apps != null) {
7575 int N = apps.size();
7576 int i;
7577 for (i=0; i<N; i++) {
7578 ApplicationInfo info
7579 = (ApplicationInfo)apps.get(i);
7580 if (info != null &&
7581 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007582 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
7584 }
7585 }
7586 } catch (RemoteException ex) {
7587 // pm is in same process, this will never happen.
7588 }
7589 }
7590
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007591 // Start up initial activity.
7592 mBooting = true;
7593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007595 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 Message msg = Message.obtain();
7597 msg.what = SHOW_UID_ERROR_MSG;
7598 mHandler.sendMessage(msg);
7599 }
7600 } catch (RemoteException e) {
7601 }
7602
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007603 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 }
7605 }
7606
Dan Egnorb7f03672009-12-09 16:22:32 -08007607 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007608 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007610 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007611 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 startAppProblemLocked(app);
7613 app.stopFreezingAllLocked();
7614 return handleAppCrashLocked(app);
7615 }
7616
Dan Egnorb7f03672009-12-09 16:22:32 -08007617 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007618 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007620 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007621 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7622 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007623 startAppProblemLocked(app);
7624 app.stopFreezingAllLocked();
7625 }
7626
7627 /**
7628 * Generate a process error record, suitable for attachment to a ProcessRecord.
7629 *
7630 * @param app The ProcessRecord in which the error occurred.
7631 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7632 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007633 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 * @param shortMsg Short message describing the crash.
7635 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007636 * @param stackTrace Full crash stack trace, may be null.
7637 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 * @return Returns a fully-formed AppErrorStateInfo record.
7639 */
7640 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007641 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 report.condition = condition;
7645 report.processName = app.processName;
7646 report.pid = app.pid;
7647 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007648 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 report.shortMsg = shortMsg;
7650 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007651 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652
7653 return report;
7654 }
7655
Dan Egnor42471dd2010-01-07 17:25:22 -08007656 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 synchronized (this) {
7658 app.crashing = false;
7659 app.crashingReport = null;
7660 app.notResponding = false;
7661 app.notRespondingReport = null;
7662 if (app.anrDialog == fromDialog) {
7663 app.anrDialog = null;
7664 }
7665 if (app.waitDialog == fromDialog) {
7666 app.waitDialog = null;
7667 }
7668 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007669 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007670 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007671 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7672 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007673 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 }
7676 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007677
Dan Egnorb7f03672009-12-09 16:22:32 -08007678 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007679 if (mHeadless) {
7680 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7681 return false;
7682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 long now = SystemClock.uptimeMillis();
7684
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007685 Long crashTime;
7686 if (!app.isolated) {
7687 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7688 } else {
7689 crashTime = null;
7690 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007691 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007693 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007695 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007696 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007697 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7698 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007700 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007702 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 }
7704 }
7705 if (!app.persistent) {
7706 // We don't want to start this process again until the user
7707 // explicitly does so... but for persistent process, we really
7708 // need to keep it running. If a persistent process is actually
7709 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007710 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007712 if (!app.isolated) {
7713 // XXX We don't have a way to mark isolated processes
7714 // as bad, since they don't have a peristent identity.
7715 mBadProcesses.put(app.info.processName, app.uid, now);
7716 mProcessCrashTimes.remove(app.info.processName, app.uid);
7717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007720 // Don't let services in this process be restarted and potentially
7721 // annoy the user repeatedly. Unless it is persistent, since those
7722 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007723 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007724 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 return false;
7726 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007727 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007728 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007729 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007730 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007731 // If the top running activity is from this crashing
7732 // process, then terminate it to avoid getting in a loop.
7733 Slog.w(TAG, " Force finishing activity "
7734 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007735 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007736 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007737 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007738 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007739 // stopped, to avoid a situation where one will get
7740 // re-start our crashing activity once it gets resumed again.
7741 index--;
7742 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007743 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007744 if (r.state == ActivityState.RESUMED
7745 || r.state == ActivityState.PAUSING
7746 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007747 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007748 Slog.w(TAG, " Force finishing activity "
7749 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007750 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007751 Activity.RESULT_CANCELED, null, "crashed");
7752 }
7753 }
7754 }
7755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 }
7757
7758 // Bump up the crash count of any services currently running in the proc.
7759 if (app.services.size() != 0) {
7760 // Any services running in the application need to be placed
7761 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007762 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007764 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 sr.crashCount++;
7766 }
7767 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007768
7769 // If the crashing process is what we consider to be the "home process" and it has been
7770 // replaced by a third-party app, clear the package preferred activities from packages
7771 // with a home activity running in the process to prevent a repeatedly crashing app
7772 // from blocking the user to manually clear the list.
7773 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7774 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7775 Iterator it = mHomeProcess.activities.iterator();
7776 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007777 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007778 if (r.isHomeActivity) {
7779 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7780 try {
7781 ActivityThread.getPackageManager()
7782 .clearPackagePreferredActivities(r.packageName);
7783 } catch (RemoteException c) {
7784 // pm is in same process, this will never happen.
7785 }
7786 }
7787 }
7788 }
7789
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007790 if (!app.isolated) {
7791 // XXX Can't keep track of crash times for isolated processes,
7792 // because they don't have a perisistent identity.
7793 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7794 }
7795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 return true;
7797 }
7798
7799 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007800 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7801 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 skipCurrentReceiverLocked(app);
7803 }
7804
7805 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007806 for (BroadcastQueue queue : mBroadcastQueues) {
7807 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 }
7809 }
7810
Dan Egnor60d87622009-12-16 16:32:58 -08007811 /**
7812 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7813 * The application process will exit immediately after this call returns.
7814 * @param app object of the crashing app, null for the system server
7815 * @param crashInfo describing the exception
7816 */
7817 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007818 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007819 final String processName = app == null ? "system_server"
7820 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007821
7822 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007823 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007824 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007825 crashInfo.exceptionClassName,
7826 crashInfo.exceptionMessage,
7827 crashInfo.throwFileName,
7828 crashInfo.throwLineNumber);
7829
Jeff Sharkeya353d262011-10-28 11:12:06 -07007830 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007831
7832 crashApplication(r, crashInfo);
7833 }
7834
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007835 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007836 IBinder app,
7837 int violationMask,
7838 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007839 ProcessRecord r = findAppProcess(app, "StrictMode");
7840 if (r == null) {
7841 return;
7842 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007843
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007844 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007845 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007846 boolean logIt = true;
7847 synchronized (mAlreadyLoggedViolatedStacks) {
7848 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7849 logIt = false;
7850 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007851 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007852 // the relative pain numbers, without logging all
7853 // the stack traces repeatedly. We'd want to do
7854 // likewise in the client code, which also does
7855 // dup suppression, before the Binder call.
7856 } else {
7857 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7858 mAlreadyLoggedViolatedStacks.clear();
7859 }
7860 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7861 }
7862 }
7863 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007864 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007865 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007866 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007867
7868 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7869 AppErrorResult result = new AppErrorResult();
7870 synchronized (this) {
7871 final long origId = Binder.clearCallingIdentity();
7872
7873 Message msg = Message.obtain();
7874 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7875 HashMap<String, Object> data = new HashMap<String, Object>();
7876 data.put("result", result);
7877 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007878 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007879 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007880 msg.obj = data;
7881 mHandler.sendMessage(msg);
7882
7883 Binder.restoreCallingIdentity(origId);
7884 }
7885 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007886 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007887 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007888 }
7889
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007890 // Depending on the policy in effect, there could be a bunch of
7891 // these in quick succession so we try to batch these together to
7892 // minimize disk writes, number of dropbox entries, and maximize
7893 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007894 private void logStrictModeViolationToDropBox(
7895 ProcessRecord process,
7896 StrictMode.ViolationInfo info) {
7897 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007898 return;
7899 }
7900 final boolean isSystemApp = process == null ||
7901 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7902 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007903 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007904 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7905 final DropBoxManager dbox = (DropBoxManager)
7906 mContext.getSystemService(Context.DROPBOX_SERVICE);
7907
7908 // Exit early if the dropbox isn't configured to accept this report type.
7909 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7910
7911 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007912 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007913 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7914 synchronized (sb) {
7915 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007916 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007917 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7918 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007919 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7920 if (info.violationNumThisLoop != 0) {
7921 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7922 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007923 if (info.numAnimationsRunning != 0) {
7924 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7925 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007926 if (info.broadcastIntentAction != null) {
7927 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7928 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007929 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007930 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007931 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007932 if (info.numInstances != -1) {
7933 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7934 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007935 if (info.tags != null) {
7936 for (String tag : info.tags) {
7937 sb.append("Span-Tag: ").append(tag).append("\n");
7938 }
7939 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007940 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007941 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7942 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007943 }
7944 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007945
7946 // Only buffer up to ~64k. Various logging bits truncate
7947 // things at 128k.
7948 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007949 }
7950
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007951 // Flush immediately if the buffer's grown too large, or this
7952 // is a non-system app. Non-system apps are isolated with a
7953 // different tag & policy and not batched.
7954 //
7955 // Batching is useful during internal testing with
7956 // StrictMode settings turned up high. Without batching,
7957 // thousands of separate files could be created on boot.
7958 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007959 new Thread("Error dump: " + dropboxTag) {
7960 @Override
7961 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007962 String report;
7963 synchronized (sb) {
7964 report = sb.toString();
7965 sb.delete(0, sb.length());
7966 sb.trimToSize();
7967 }
7968 if (report.length() != 0) {
7969 dbox.addText(dropboxTag, report);
7970 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007971 }
7972 }.start();
7973 return;
7974 }
7975
7976 // System app batching:
7977 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007978 // An existing dropbox-writing thread is outstanding, so
7979 // we don't need to start it up. The existing thread will
7980 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007981 return;
7982 }
7983
7984 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7985 // (After this point, we shouldn't access AMS internal data structures.)
7986 new Thread("Error dump: " + dropboxTag) {
7987 @Override
7988 public void run() {
7989 // 5 second sleep to let stacks arrive and be batched together
7990 try {
7991 Thread.sleep(5000); // 5 seconds
7992 } catch (InterruptedException e) {}
7993
7994 String errorReport;
7995 synchronized (mStrictModeBuffer) {
7996 errorReport = mStrictModeBuffer.toString();
7997 if (errorReport.length() == 0) {
7998 return;
7999 }
8000 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8001 mStrictModeBuffer.trimToSize();
8002 }
8003 dbox.addText(dropboxTag, errorReport);
8004 }
8005 }.start();
8006 }
8007
Dan Egnor60d87622009-12-16 16:32:58 -08008008 /**
8009 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8010 * @param app object of the crashing app, null for the system server
8011 * @param tag reported by the caller
8012 * @param crashInfo describing the context of the error
8013 * @return true if the process should exit immediately (WTF is fatal)
8014 */
8015 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008016 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008017 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008018 final String processName = app == null ? "system_server"
8019 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008020
8021 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008022 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008023 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008024 tag, crashInfo.exceptionMessage);
8025
Jeff Sharkeya353d262011-10-28 11:12:06 -07008026 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008027
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008028 if (r != null && r.pid != Process.myPid() &&
8029 Settings.Secure.getInt(mContext.getContentResolver(),
8030 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008031 crashApplication(r, crashInfo);
8032 return true;
8033 } else {
8034 return false;
8035 }
8036 }
8037
8038 /**
8039 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8040 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8041 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008042 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008043 if (app == null) {
8044 return null;
8045 }
8046
8047 synchronized (this) {
8048 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8049 final int NA = apps.size();
8050 for (int ia=0; ia<NA; ia++) {
8051 ProcessRecord p = apps.valueAt(ia);
8052 if (p.thread != null && p.thread.asBinder() == app) {
8053 return p;
8054 }
8055 }
8056 }
8057
Dianne Hackborncb44d962011-03-10 17:02:27 -08008058 Slog.w(TAG, "Can't find mystery application for " + reason
8059 + " from pid=" + Binder.getCallingPid()
8060 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008061 return null;
8062 }
8063 }
8064
8065 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008066 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8067 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008068 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008069 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8070 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008071 // Watchdog thread ends up invoking this function (with
8072 // a null ProcessRecord) to add the stack file to dropbox.
8073 // Do not acquire a lock on this (am) in such cases, as it
8074 // could cause a potential deadlock, if and when watchdog
8075 // is invoked due to unavailability of lock on am and it
8076 // would prevent watchdog from killing system_server.
8077 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008078 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008079 return;
8080 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008081 // Note: ProcessRecord 'process' is guarded by the service
8082 // instance. (notably process.pkgList, which could otherwise change
8083 // concurrently during execution of this method)
8084 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008085 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008086 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008087 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008088 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8089 for (String pkg : process.pkgList) {
8090 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008091 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008092 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008093 if (pi != null) {
8094 sb.append(" v").append(pi.versionCode);
8095 if (pi.versionName != null) {
8096 sb.append(" (").append(pi.versionName).append(")");
8097 }
8098 }
8099 } catch (RemoteException e) {
8100 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008101 }
Dan Egnora455d192010-03-12 08:52:28 -08008102 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008103 }
Dan Egnora455d192010-03-12 08:52:28 -08008104 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008105 }
8106
8107 private static String processClass(ProcessRecord process) {
8108 if (process == null || process.pid == MY_PID) {
8109 return "system_server";
8110 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8111 return "system_app";
8112 } else {
8113 return "data_app";
8114 }
8115 }
8116
8117 /**
8118 * Write a description of an error (crash, WTF, ANR) to the drop box.
8119 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8120 * @param process which caused the error, null means the system server
8121 * @param activity which triggered the error, null if unknown
8122 * @param parent activity related to the error, null if unknown
8123 * @param subject line related to the error, null if absent
8124 * @param report in long form describing the error, null if absent
8125 * @param logFile to include in the report, null if none
8126 * @param crashInfo giving an application stack trace, null if absent
8127 */
8128 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008129 ProcessRecord process, String processName, ActivityRecord activity,
8130 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008131 final String report, final File logFile,
8132 final ApplicationErrorReport.CrashInfo crashInfo) {
8133 // NOTE -- this must never acquire the ActivityManagerService lock,
8134 // otherwise the watchdog may be prevented from resetting the system.
8135
8136 final String dropboxTag = processClass(process) + "_" + eventType;
8137 final DropBoxManager dbox = (DropBoxManager)
8138 mContext.getSystemService(Context.DROPBOX_SERVICE);
8139
8140 // Exit early if the dropbox isn't configured to accept this report type.
8141 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8142
8143 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008144 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008145 if (activity != null) {
8146 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8147 }
8148 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8149 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8150 }
8151 if (parent != null && parent != activity) {
8152 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8153 }
8154 if (subject != null) {
8155 sb.append("Subject: ").append(subject).append("\n");
8156 }
8157 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008158 if (Debug.isDebuggerConnected()) {
8159 sb.append("Debugger: Connected\n");
8160 }
Dan Egnora455d192010-03-12 08:52:28 -08008161 sb.append("\n");
8162
8163 // Do the rest in a worker thread to avoid blocking the caller on I/O
8164 // (After this point, we shouldn't access AMS internal data structures.)
8165 Thread worker = new Thread("Error dump: " + dropboxTag) {
8166 @Override
8167 public void run() {
8168 if (report != null) {
8169 sb.append(report);
8170 }
8171 if (logFile != null) {
8172 try {
8173 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8174 } catch (IOException e) {
8175 Slog.e(TAG, "Error reading " + logFile, e);
8176 }
8177 }
8178 if (crashInfo != null && crashInfo.stackTrace != null) {
8179 sb.append(crashInfo.stackTrace);
8180 }
8181
8182 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8183 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8184 if (lines > 0) {
8185 sb.append("\n");
8186
8187 // Merge several logcat streams, and take the last N lines
8188 InputStreamReader input = null;
8189 try {
8190 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8191 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8192 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8193
8194 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8195 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8196 input = new InputStreamReader(logcat.getInputStream());
8197
8198 int num;
8199 char[] buf = new char[8192];
8200 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8201 } catch (IOException e) {
8202 Slog.e(TAG, "Error running logcat", e);
8203 } finally {
8204 if (input != null) try { input.close(); } catch (IOException e) {}
8205 }
8206 }
8207
8208 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008209 }
Dan Egnora455d192010-03-12 08:52:28 -08008210 };
8211
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008212 if (process == null) {
8213 // If process is null, we are being called from some internal code
8214 // and may be about to die -- run this synchronously.
8215 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008216 } else {
8217 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008218 }
8219 }
8220
8221 /**
8222 * Bring up the "unexpected error" dialog box for a crashing app.
8223 * Deal with edge cases (intercepts from instrumented applications,
8224 * ActivityController, error intent receivers, that sort of thing).
8225 * @param r the application crashing
8226 * @param crashInfo describing the failure
8227 */
8228 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008229 long timeMillis = System.currentTimeMillis();
8230 String shortMsg = crashInfo.exceptionClassName;
8231 String longMsg = crashInfo.exceptionMessage;
8232 String stackTrace = crashInfo.stackTrace;
8233 if (shortMsg != null && longMsg != null) {
8234 longMsg = shortMsg + ": " + longMsg;
8235 } else if (shortMsg != null) {
8236 longMsg = shortMsg;
8237 }
8238
Dan Egnor60d87622009-12-16 16:32:58 -08008239 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008241 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 try {
8243 String name = r != null ? r.processName : null;
8244 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008245 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008246 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008247 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 + " at watcher's request");
8249 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008250 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 }
8252 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008253 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254 }
8255 }
8256
8257 final long origId = Binder.clearCallingIdentity();
8258
8259 // If this process is running instrumentation, finish it.
8260 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008261 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008263 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8264 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 Bundle info = new Bundle();
8266 info.putString("shortMsg", shortMsg);
8267 info.putString("longMsg", longMsg);
8268 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8269 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008270 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 }
8272
Dan Egnor60d87622009-12-16 16:32:58 -08008273 // If we can't identify the process or it's already exceeded its crash quota,
8274 // quit right away without showing a crash dialog.
8275 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008277 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 }
8279
8280 Message msg = Message.obtain();
8281 msg.what = SHOW_ERROR_MSG;
8282 HashMap data = new HashMap();
8283 data.put("result", result);
8284 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008285 msg.obj = data;
8286 mHandler.sendMessage(msg);
8287
8288 Binder.restoreCallingIdentity(origId);
8289 }
8290
8291 int res = result.get();
8292
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008293 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008295 if (r != null && !r.isolated) {
8296 // XXX Can't keep track of crash time for isolated processes,
8297 // since they don't have a persistent identity.
8298 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 SystemClock.uptimeMillis());
8300 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008301 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008302 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008303 }
8304 }
8305
8306 if (appErrorIntent != null) {
8307 try {
8308 mContext.startActivity(appErrorIntent);
8309 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008310 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008314
8315 Intent createAppErrorIntentLocked(ProcessRecord r,
8316 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8317 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008318 if (report == null) {
8319 return null;
8320 }
8321 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8322 result.setComponent(r.errorReportReceiver);
8323 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8324 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8325 return result;
8326 }
8327
Dan Egnorb7f03672009-12-09 16:22:32 -08008328 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8329 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008330 if (r.errorReportReceiver == null) {
8331 return null;
8332 }
8333
8334 if (!r.crashing && !r.notResponding) {
8335 return null;
8336 }
8337
Dan Egnorb7f03672009-12-09 16:22:32 -08008338 ApplicationErrorReport report = new ApplicationErrorReport();
8339 report.packageName = r.info.packageName;
8340 report.installerPackageName = r.errorReportReceiver.getPackageName();
8341 report.processName = r.processName;
8342 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008343 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008344
Dan Egnorb7f03672009-12-09 16:22:32 -08008345 if (r.crashing) {
8346 report.type = ApplicationErrorReport.TYPE_CRASH;
8347 report.crashInfo = crashInfo;
8348 } else if (r.notResponding) {
8349 report.type = ApplicationErrorReport.TYPE_ANR;
8350 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008351
Dan Egnorb7f03672009-12-09 16:22:32 -08008352 report.anrInfo.activity = r.notRespondingReport.tag;
8353 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8354 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008355 }
8356
Dan Egnorb7f03672009-12-09 16:22:32 -08008357 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008358 }
8359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008361 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 // assume our apps are happy - lazy create the list
8363 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8364
8365 synchronized (this) {
8366
8367 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008368 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8369 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8371 // This one's in trouble, so we'll generate a report for it
8372 // crashes are higher priority (in case there's a crash *and* an anr)
8373 ActivityManager.ProcessErrorStateInfo report = null;
8374 if (app.crashing) {
8375 report = app.crashingReport;
8376 } else if (app.notResponding) {
8377 report = app.notRespondingReport;
8378 }
8379
8380 if (report != null) {
8381 if (errList == null) {
8382 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8383 }
8384 errList.add(report);
8385 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008386 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 " crashing = " + app.crashing +
8388 " notResponding = " + app.notResponding);
8389 }
8390 }
8391 }
8392 }
8393
8394 return errList;
8395 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008396
8397 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008398 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008399 if (currApp != null) {
8400 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8401 }
8402 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008403 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8404 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008405 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8406 if (currApp != null) {
8407 currApp.lru = 0;
8408 }
8409 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008410 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008411 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8412 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8413 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8414 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8415 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8416 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8417 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8418 } else {
8419 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8420 }
8421 }
8422
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008423 private void fillInProcMemInfo(ProcessRecord app,
8424 ActivityManager.RunningAppProcessInfo outInfo) {
8425 outInfo.pid = app.pid;
8426 outInfo.uid = app.info.uid;
8427 if (mHeavyWeightProcess == app) {
8428 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8429 }
8430 if (app.persistent) {
8431 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8432 }
8433 outInfo.lastTrimLevel = app.trimMemoryLevel;
8434 int adj = app.curAdj;
8435 outInfo.importance = oomAdjToImportance(adj, outInfo);
8436 outInfo.importanceReasonCode = app.adjTypeCode;
8437 }
8438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008440 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441 // Lazy instantiation of list
8442 List<ActivityManager.RunningAppProcessInfo> runList = null;
8443 synchronized (this) {
8444 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008445 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8446 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8448 // Generate process state info for running application
8449 ActivityManager.RunningAppProcessInfo currApp =
8450 new ActivityManager.RunningAppProcessInfo(app.processName,
8451 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008452 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008453 if (app.adjSource instanceof ProcessRecord) {
8454 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008455 currApp.importanceReasonImportance = oomAdjToImportance(
8456 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008457 } else if (app.adjSource instanceof ActivityRecord) {
8458 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008459 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8460 }
8461 if (app.adjTarget instanceof ComponentName) {
8462 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8463 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008464 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 // + " lru=" + currApp.lru);
8466 if (runList == null) {
8467 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8468 }
8469 runList.add(currApp);
8470 }
8471 }
8472 }
8473 return runList;
8474 }
8475
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008476 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008477 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008478 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8479 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8480 if (runningApps != null && runningApps.size() > 0) {
8481 Set<String> extList = new HashSet<String>();
8482 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8483 if (app.pkgList != null) {
8484 for (String pkg : app.pkgList) {
8485 extList.add(pkg);
8486 }
8487 }
8488 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008489 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008490 for (String pkg : extList) {
8491 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008492 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008493 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8494 retList.add(info);
8495 }
8496 } catch (RemoteException e) {
8497 }
8498 }
8499 }
8500 return retList;
8501 }
8502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008504 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8505 enforceNotIsolatedCaller("getMyMemoryState");
8506 synchronized (this) {
8507 ProcessRecord proc;
8508 synchronized (mPidsSelfLocked) {
8509 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8510 }
8511 fillInProcMemInfo(proc, outInfo);
8512 }
8513 }
8514
8515 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 if (checkCallingPermission(android.Manifest.permission.DUMP)
8518 != PackageManager.PERMISSION_GRANTED) {
8519 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8520 + Binder.getCallingPid()
8521 + ", uid=" + Binder.getCallingUid()
8522 + " without permission "
8523 + android.Manifest.permission.DUMP);
8524 return;
8525 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008526
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008527 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008528 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008529 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530
8531 int opti = 0;
8532 while (opti < args.length) {
8533 String opt = args[opti];
8534 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8535 break;
8536 }
8537 opti++;
8538 if ("-a".equals(opt)) {
8539 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008540 } else if ("-c".equals(opt)) {
8541 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 } else if ("-h".equals(opt)) {
8543 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008544 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008545 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008546 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8548 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8549 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008550 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008551 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008552 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008553 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008554 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008556 pw.println(" all: dump all activities");
8557 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008558 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008559 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8560 pw.println(" a partial substring in a component name, a");
8561 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008562 pw.println(" -a: include all available server state.");
8563 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 } else {
8566 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008568 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008569
8570 long origId = Binder.clearCallingIdentity();
8571 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008572 // Is the caller requesting to dump a particular piece of data?
8573 if (opti < args.length) {
8574 String cmd = args[opti];
8575 opti++;
8576 if ("activities".equals(cmd) || "a".equals(cmd)) {
8577 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008578 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008580 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008581 String[] newArgs;
8582 String name;
8583 if (opti >= args.length) {
8584 name = null;
8585 newArgs = EMPTY_STRING_ARRAY;
8586 } else {
8587 name = args[opti];
8588 opti++;
8589 newArgs = new String[args.length - opti];
8590 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8591 args.length - opti);
8592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008594 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008595 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008596 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008597 String[] newArgs;
8598 String name;
8599 if (opti >= args.length) {
8600 name = null;
8601 newArgs = EMPTY_STRING_ARRAY;
8602 } else {
8603 name = args[opti];
8604 opti++;
8605 newArgs = new String[args.length - opti];
8606 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8607 args.length - opti);
8608 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008609 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008613 String[] newArgs;
8614 String name;
8615 if (opti >= args.length) {
8616 name = null;
8617 newArgs = EMPTY_STRING_ARRAY;
8618 } else {
8619 name = args[opti];
8620 opti++;
8621 newArgs = new String[args.length - opti];
8622 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8623 args.length - opti);
8624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008625 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008626 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008628 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8629 synchronized (this) {
8630 dumpOomLocked(fd, pw, args, opti, true);
8631 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008632 } else if ("provider".equals(cmd)) {
8633 String[] newArgs;
8634 String name;
8635 if (opti >= args.length) {
8636 name = null;
8637 newArgs = EMPTY_STRING_ARRAY;
8638 } else {
8639 name = args[opti];
8640 opti++;
8641 newArgs = new String[args.length - opti];
8642 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8643 }
8644 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8645 pw.println("No providers match: " + name);
8646 pw.println("Use -h for help.");
8647 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008648 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8649 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008650 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008651 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008652 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008653 String[] newArgs;
8654 String name;
8655 if (opti >= args.length) {
8656 name = null;
8657 newArgs = EMPTY_STRING_ARRAY;
8658 } else {
8659 name = args[opti];
8660 opti++;
8661 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008662 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8663 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008664 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008665 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008666 pw.println("No services match: " + name);
8667 pw.println("Use -h for help.");
8668 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 } else if ("package".equals(cmd)) {
8670 String[] newArgs;
8671 if (opti >= args.length) {
8672 pw.println("package: no package name specified");
8673 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008674 } else {
8675 dumpPackage = args[opti];
8676 opti++;
8677 newArgs = new String[args.length - opti];
8678 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8679 args.length - opti);
8680 args = newArgs;
8681 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008682 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008683 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008684 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8685 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008686 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008687 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008688 } else {
8689 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008690 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8691 pw.println("Bad activity command, or no activities match: " + cmd);
8692 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008693 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008694 }
8695 if (!more) {
8696 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008697 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008699 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008700
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008701 // No piece of data specified, dump everything.
8702 synchronized (this) {
8703 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008704 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008705 if (needSep) {
8706 pw.println(" ");
8707 }
8708 if (dumpAll) {
8709 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008710 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008711 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 if (needSep) {
8713 pw.println(" ");
8714 }
8715 if (dumpAll) {
8716 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008717 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 if (needSep) {
8720 pw.println(" ");
8721 }
8722 if (dumpAll) {
8723 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008724 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008725 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 if (needSep) {
8727 pw.println(" ");
8728 }
8729 if (dumpAll) {
8730 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008731 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008732 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008733 if (needSep) {
8734 pw.println(" ");
8735 }
8736 if (dumpAll) {
8737 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008738 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008739 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008740 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008741 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008742 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008743
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008744 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008745 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008746 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8747 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008748 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8749 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008750 pw.println(" ");
8751 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8753 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008754 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008756 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008757 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008759 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008760 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008763 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008766 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8767 pw.println(" ");
8768 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008769 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008770 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008771 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008772 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008773 pw.println(" ");
8774 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008780 if (mMainStack.mPausingActivity != null) {
8781 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008782 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008783 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008784 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008785 if (dumpAll) {
8786 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8787 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008788 pw.println(" mDismissKeyguardOnNextActivity: "
8789 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008792 if (mRecentTasks.size() > 0) {
8793 pw.println();
8794 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795
8796 final int N = mRecentTasks.size();
8797 for (int i=0; i<N; i++) {
8798 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008799 if (dumpPackage != null) {
8800 if (tr.realActivity == null ||
8801 !dumpPackage.equals(tr.realActivity)) {
8802 continue;
8803 }
8804 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8806 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008807 if (dumpAll) {
8808 mRecentTasks.get(i).dump(pw, " ");
8809 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 }
8811 }
8812
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008813 if (dumpAll) {
8814 pw.println(" ");
8815 pw.println(" mCurTask: " + mCurTask);
8816 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817
8818 return true;
8819 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008820
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008822 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 boolean needSep = false;
8824 int numPers = 0;
8825
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008826 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8827
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8830 final int NA = procs.size();
8831 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008832 ProcessRecord r = procs.valueAt(ia);
8833 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8834 continue;
8835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 if (!needSep) {
8837 pw.println(" All known processes:");
8838 needSep = true;
8839 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008840 pw.print(r.persistent ? " *PERS*" : " *APP*");
8841 pw.print(" UID "); pw.print(procs.keyAt(ia));
8842 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 r.dump(pw, " ");
8844 if (r.persistent) {
8845 numPers++;
8846 }
8847 }
8848 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008849 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008850
8851 if (mIsolatedProcesses.size() > 0) {
8852 if (needSep) pw.println(" ");
8853 needSep = true;
8854 pw.println(" Isolated process list (sorted by uid):");
8855 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8856 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8857 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8858 continue;
8859 }
8860 pw.println(String.format("%sIsolated #%2d: %s",
8861 " ", i, r.toString()));
8862 }
8863 }
8864
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008865 if (mLruProcesses.size() > 0) {
8866 if (needSep) pw.println(" ");
8867 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008868 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008869 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008870 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008871 needSep = true;
8872 }
8873
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008874 if (dumpAll) {
8875 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008876 boolean printed = false;
8877 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8878 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8879 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8880 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008881 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008882 if (!printed) {
8883 if (needSep) pw.println(" ");
8884 needSep = true;
8885 pw.println(" PID mappings:");
8886 printed = true;
8887 }
8888 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8889 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 }
8891 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008892 }
8893
8894 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008895 synchronized (mPidsSelfLocked) {
8896 boolean printed = false;
8897 for (int i=0; i<mForegroundProcesses.size(); i++) {
8898 ProcessRecord r = mPidsSelfLocked.get(
8899 mForegroundProcesses.valueAt(i).pid);
8900 if (dumpPackage != null && (r == null
8901 || !dumpPackage.equals(r.info.packageName))) {
8902 continue;
8903 }
8904 if (!printed) {
8905 if (needSep) pw.println(" ");
8906 needSep = true;
8907 pw.println(" Foreground Processes:");
8908 printed = true;
8909 }
8910 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8911 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 }
8915
8916 if (mPersistentStartingProcesses.size() > 0) {
8917 if (needSep) pw.println(" ");
8918 needSep = true;
8919 pw.println(" Persisent processes that are starting:");
8920 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008921 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 if (mRemovedProcesses.size() > 0) {
8925 if (needSep) pw.println(" ");
8926 needSep = true;
8927 pw.println(" Processes that are being removed:");
8928 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008929 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008930 }
8931
8932 if (mProcessesOnHold.size() > 0) {
8933 if (needSep) pw.println(" ");
8934 needSep = true;
8935 pw.println(" Processes that are on old until the system is ready:");
8936 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008937 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008940 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941
8942 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008943 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008944 long now = SystemClock.uptimeMillis();
8945 for (Map.Entry<String, SparseArray<Long>> procs
8946 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008947 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 SparseArray<Long> uids = procs.getValue();
8949 final int N = uids.size();
8950 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008951 int puid = uids.keyAt(i);
8952 ProcessRecord r = mProcessNames.get(pname, puid);
8953 if (dumpPackage != null && (r == null
8954 || !dumpPackage.equals(r.info.packageName))) {
8955 continue;
8956 }
8957 if (!printed) {
8958 if (needSep) pw.println(" ");
8959 needSep = true;
8960 pw.println(" Time since processes crashed:");
8961 printed = true;
8962 }
8963 pw.print(" Process "); pw.print(pname);
8964 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008965 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008966 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8967 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008968 }
8969 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008972 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008973 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008974 for (Map.Entry<String, SparseArray<Long>> procs
8975 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 SparseArray<Long> uids = procs.getValue();
8978 final int N = uids.size();
8979 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008980 int puid = uids.keyAt(i);
8981 ProcessRecord r = mProcessNames.get(pname, puid);
8982 if (dumpPackage != null && (r == null
8983 || !dumpPackage.equals(r.info.packageName))) {
8984 continue;
8985 }
8986 if (!printed) {
8987 if (needSep) pw.println(" ");
8988 needSep = true;
8989 pw.println(" Bad processes:");
8990 }
8991 pw.print(" Bad process "); pw.print(pname);
8992 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 pw.print(": crashed at time ");
8994 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 }
8996 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008999 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009000 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009001 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009002 if (dumpAll) {
9003 StringBuilder sb = new StringBuilder(128);
9004 sb.append(" mPreviousProcessVisibleTime: ");
9005 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9006 pw.println(sb);
9007 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009008 if (mHeavyWeightProcess != null) {
9009 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9010 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009012 if (dumpAll) {
9013 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009014 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009015 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009016 for (Map.Entry<String, Integer> entry
9017 : mCompatModePackages.getPackages().entrySet()) {
9018 String pkg = entry.getKey();
9019 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009020 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9021 continue;
9022 }
9023 if (!printed) {
9024 pw.println(" mScreenCompatPackages:");
9025 printed = true;
9026 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009027 pw.print(" "); pw.print(pkg); pw.print(": ");
9028 pw.print(mode); pw.println();
9029 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009030 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009031 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009032 if (mSleeping || mWentToSleep || mLockScreenShown) {
9033 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9034 + " mLockScreenShown " + mLockScreenShown);
9035 }
9036 if (mShuttingDown) {
9037 pw.println(" mShuttingDown=" + mShuttingDown);
9038 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9040 || mOrigWaitForDebugger) {
9041 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9042 + " mDebugTransient=" + mDebugTransient
9043 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9044 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009045 if (mOpenGlTraceApp != null) {
9046 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9047 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009048 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9049 || mProfileFd != null) {
9050 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9051 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9052 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9053 + mAutoStopProfiler);
9054 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 if (mAlwaysFinishActivities || mController != null) {
9056 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9057 + " mController=" + mController);
9058 }
9059 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009062 + " mProcessesReady=" + mProcessesReady
9063 + " mSystemReady=" + mSystemReady);
9064 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 + " mBooted=" + mBooted
9066 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009067 pw.print(" mLastPowerCheckRealtime=");
9068 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9069 pw.println("");
9070 pw.print(" mLastPowerCheckUptime=");
9071 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9072 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009073 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9074 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009075 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009076 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9077 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079
9080 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 }
9082
Dianne Hackborn287952c2010-09-22 22:34:31 -07009083 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009084 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009085 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009086 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009087 long now = SystemClock.uptimeMillis();
9088 for (int i=0; i<mProcessesToGc.size(); i++) {
9089 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009090 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9091 continue;
9092 }
9093 if (!printed) {
9094 if (needSep) pw.println(" ");
9095 needSep = true;
9096 pw.println(" Processes that are waiting to GC:");
9097 printed = true;
9098 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009099 pw.print(" Process "); pw.println(proc);
9100 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9101 pw.print(", last gced=");
9102 pw.print(now-proc.lastRequestedGc);
9103 pw.print(" ms ago, last lowMem=");
9104 pw.print(now-proc.lastLowMemory);
9105 pw.println(" ms ago");
9106
9107 }
9108 }
9109 return needSep;
9110 }
9111
9112 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9113 int opti, boolean dumpAll) {
9114 boolean needSep = false;
9115
9116 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009117 if (needSep) pw.println(" ");
9118 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009119 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009120 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009121 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009122 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9123 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9124 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9125 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9126 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009127 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009128 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009129 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009130 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009131 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009132 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009133
9134 if (needSep) pw.println(" ");
9135 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009136 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009137 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009139 needSep = true;
9140 }
9141
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009142 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009143
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009144 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009145 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009146 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009147 if (mHeavyWeightProcess != null) {
9148 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9149 }
9150
9151 return true;
9152 }
9153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009154 /**
9155 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009156 * - no provider specified: dump all the providers
9157 * - a flattened component name that matched an existing provider was specified as the
9158 * first arg: dump that one provider
9159 * - the first arg isn't the flattened component name of an existing provider:
9160 * dump all providers whose component contains the first arg as a substring
9161 */
9162 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9163 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009164 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009165 }
9166
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009167 static class ItemMatcher {
9168 ArrayList<ComponentName> components;
9169 ArrayList<String> strings;
9170 ArrayList<Integer> objects;
9171 boolean all;
9172
9173 ItemMatcher() {
9174 all = true;
9175 }
9176
9177 void build(String name) {
9178 ComponentName componentName = ComponentName.unflattenFromString(name);
9179 if (componentName != null) {
9180 if (components == null) {
9181 components = new ArrayList<ComponentName>();
9182 }
9183 components.add(componentName);
9184 all = false;
9185 } else {
9186 int objectId = 0;
9187 // Not a '/' separated full component name; maybe an object ID?
9188 try {
9189 objectId = Integer.parseInt(name, 16);
9190 if (objects == null) {
9191 objects = new ArrayList<Integer>();
9192 }
9193 objects.add(objectId);
9194 all = false;
9195 } catch (RuntimeException e) {
9196 // Not an integer; just do string match.
9197 if (strings == null) {
9198 strings = new ArrayList<String>();
9199 }
9200 strings.add(name);
9201 all = false;
9202 }
9203 }
9204 }
9205
9206 int build(String[] args, int opti) {
9207 for (; opti<args.length; opti++) {
9208 String name = args[opti];
9209 if ("--".equals(name)) {
9210 return opti+1;
9211 }
9212 build(name);
9213 }
9214 return opti;
9215 }
9216
9217 boolean match(Object object, ComponentName comp) {
9218 if (all) {
9219 return true;
9220 }
9221 if (components != null) {
9222 for (int i=0; i<components.size(); i++) {
9223 if (components.get(i).equals(comp)) {
9224 return true;
9225 }
9226 }
9227 }
9228 if (objects != null) {
9229 for (int i=0; i<objects.size(); i++) {
9230 if (System.identityHashCode(object) == objects.get(i)) {
9231 return true;
9232 }
9233 }
9234 }
9235 if (strings != null) {
9236 String flat = comp.flattenToString();
9237 for (int i=0; i<strings.size(); i++) {
9238 if (flat.contains(strings.get(i))) {
9239 return true;
9240 }
9241 }
9242 }
9243 return false;
9244 }
9245 }
9246
Dianne Hackborn625ac272010-09-17 18:29:22 -07009247 /**
9248 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009249 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009250 * - the cmd arg isn't the flattened component name of an existing activity:
9251 * dump all activity whose component contains the cmd as a substring
9252 * - A hex number of the ActivityRecord object instance.
9253 */
9254 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9255 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009256 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009257
9258 if ("all".equals(name)) {
9259 synchronized (this) {
9260 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009261 activities.add(r1);
9262 }
9263 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009264 } else if ("top".equals(name)) {
9265 synchronized (this) {
9266 final int N = mMainStack.mHistory.size();
9267 if (N > 0) {
9268 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9269 }
9270 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009271 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009272 ItemMatcher matcher = new ItemMatcher();
9273 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274
9275 synchronized (this) {
9276 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009277 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009278 activities.add(r1);
9279 }
9280 }
9281 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009282 }
9283
9284 if (activities.size() <= 0) {
9285 return false;
9286 }
9287
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009288 String[] newArgs = new String[args.length - opti];
9289 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9290
Dianne Hackborn30d71892010-12-11 10:37:55 -08009291 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009292 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009293 for (int i=activities.size()-1; i>=0; i--) {
9294 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009295 if (needSep) {
9296 pw.println();
9297 }
9298 needSep = true;
9299 synchronized (this) {
9300 if (lastTask != r.task) {
9301 lastTask = r.task;
9302 pw.print("TASK "); pw.print(lastTask.affinity);
9303 pw.print(" id="); pw.println(lastTask.taskId);
9304 if (dumpAll) {
9305 lastTask.dump(pw, " ");
9306 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009307 }
9308 }
9309 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009310 }
9311 return true;
9312 }
9313
9314 /**
9315 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9316 * there is a thread associated with the activity.
9317 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009318 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009319 final ActivityRecord r, String[] args, boolean dumpAll) {
9320 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009321 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009322 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9323 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9324 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009325 if (r.app != null) pw.println(r.app.pid);
9326 else pw.println("(not running)");
9327 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009328 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009329 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009330 }
9331 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009332 // flush anything that is already in the PrintWriter since the thread is going
9333 // to write to the file descriptor directly
9334 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009335 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009336 TransferPipe tp = new TransferPipe();
9337 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009338 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9339 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009340 tp.go(fd);
9341 } finally {
9342 tp.kill();
9343 }
9344 } catch (IOException e) {
9345 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009346 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009347 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009348 }
9349 }
9350 }
9351
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009352 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009354 boolean needSep = false;
9355
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009356 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009359 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 Iterator it = mRegisteredReceivers.values().iterator();
9361 while (it.hasNext()) {
9362 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009363 if (dumpPackage != null && (r.app == null ||
9364 !dumpPackage.equals(r.app.info.packageName))) {
9365 continue;
9366 }
9367 if (!printed) {
9368 pw.println(" Registered Receivers:");
9369 needSep = true;
9370 printed = true;
9371 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009372 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 r.dump(pw, " ");
9374 }
9375 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376
9377 if (mReceiverResolver.dump(pw, needSep ?
9378 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9379 " ", dumpPackage, false)) {
9380 needSep = true;
9381 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009382 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009383
9384 for (BroadcastQueue q : mBroadcastQueues) {
9385 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009388 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009389
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 if (mStickyBroadcasts != null && dumpPackage == null) {
9391 if (needSep) {
9392 pw.println();
9393 }
9394 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009395 pw.println(" Sticky broadcasts:");
9396 StringBuilder sb = new StringBuilder(128);
9397 for (Map.Entry<String, ArrayList<Intent>> ent
9398 : mStickyBroadcasts.entrySet()) {
9399 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009400 if (dumpAll) {
9401 pw.println(":");
9402 ArrayList<Intent> intents = ent.getValue();
9403 final int N = intents.size();
9404 for (int i=0; i<N; i++) {
9405 sb.setLength(0);
9406 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009407 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 pw.println(sb.toString());
9409 Bundle bundle = intents.get(i).getExtras();
9410 if (bundle != null) {
9411 pw.print(" ");
9412 pw.println(bundle.toString());
9413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 } else {
9416 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 }
9418 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009419 needSep = true;
9420 }
9421
9422 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009424 for (BroadcastQueue queue : mBroadcastQueues) {
9425 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9426 + queue.mBroadcastsScheduled);
9427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 pw.println(" mHandler:");
9429 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432
9433 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
9435
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009436 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009437 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009438 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009440 ItemMatcher matcher = new ItemMatcher();
9441 matcher.build(args, opti);
9442
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009443 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009444
9445 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009446
9447 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009448 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009449 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009450 ContentProviderRecord r = mLaunchingProviders.get(i);
9451 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9452 continue;
9453 }
9454 if (!printed) {
9455 if (needSep) pw.println(" ");
9456 needSep = true;
9457 pw.println(" Launching content providers:");
9458 printed = true;
9459 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009463 }
9464
9465 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 if (needSep) pw.println();
9467 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009468 pw.println("Granted Uri Permissions:");
9469 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9470 int uid = mGrantedUriPermissions.keyAt(i);
9471 HashMap<Uri, UriPermission> perms
9472 = mGrantedUriPermissions.valueAt(i);
9473 pw.print(" * UID "); pw.print(uid);
9474 pw.println(" holds:");
9475 for (UriPermission perm : perms.values()) {
9476 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009477 if (dumpAll) {
9478 perm.dump(pw, " ");
9479 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009480 }
9481 }
9482 needSep = true;
9483 }
9484
9485 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
9487
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009488 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009489 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009490 boolean needSep = false;
9491
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 if (mIntentSenderRecords.size() > 0) {
9493 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009494 Iterator<WeakReference<PendingIntentRecord>> it
9495 = mIntentSenderRecords.values().iterator();
9496 while (it.hasNext()) {
9497 WeakReference<PendingIntentRecord> ref = it.next();
9498 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009499 if (dumpPackage != null && (rec == null
9500 || !dumpPackage.equals(rec.key.packageName))) {
9501 continue;
9502 }
9503 if (!printed) {
9504 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9505 printed = true;
9506 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009507 needSep = true;
9508 if (rec != null) {
9509 pw.print(" * "); pw.println(rec);
9510 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009512 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009513 } else {
9514 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009515 }
9516 }
9517 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518
9519 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520 }
9521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009522 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009523 String prefix, String label, boolean complete, boolean brief, boolean client,
9524 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009525 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009526 boolean needNL = false;
9527 final String innerPrefix = prefix + " ";
9528 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009530 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009531 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9532 continue;
9533 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009534 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009535 if (needNL) {
9536 pw.println(" ");
9537 needNL = false;
9538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009539 if (lastTask != r.task) {
9540 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009541 pw.print(prefix);
9542 pw.print(full ? "* " : " ");
9543 pw.println(lastTask);
9544 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009545 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 } else if (complete) {
9547 // Complete + brief == give a summary. Isn't that obvious?!?
9548 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009549 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009550 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009551 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009554 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9555 pw.print(" #"); pw.print(i); pw.print(": ");
9556 pw.println(r);
9557 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009558 r.dump(pw, innerPrefix);
9559 } else if (complete) {
9560 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009561 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009562 if (r.app != null) {
9563 pw.print(innerPrefix); pw.println(r.app);
9564 }
9565 }
9566 if (client && r.app != null && r.app.thread != null) {
9567 // flush anything that is already in the PrintWriter since the thread is going
9568 // to write to the file descriptor directly
9569 pw.flush();
9570 try {
9571 TransferPipe tp = new TransferPipe();
9572 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009573 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9574 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009575 // Short timeout, since blocking here can
9576 // deadlock with the application.
9577 tp.go(fd, 2000);
9578 } finally {
9579 tp.kill();
9580 }
9581 } catch (IOException e) {
9582 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9583 } catch (RemoteException e) {
9584 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9585 }
9586 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 }
9589 }
9590
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009591 private static String buildOomTag(String prefix, String space, int val, int base) {
9592 if (val == base) {
9593 if (space == null) return prefix;
9594 return prefix + " ";
9595 }
9596 return prefix + "+" + Integer.toString(val-base);
9597 }
9598
9599 private static final int dumpProcessList(PrintWriter pw,
9600 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009601 String prefix, String normalLabel, String persistentLabel,
9602 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009604 final int N = list.size()-1;
9605 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009606 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009607 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9608 continue;
9609 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009610 pw.println(String.format("%s%s #%2d: %s",
9611 prefix, (r.persistent ? persistentLabel : normalLabel),
9612 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009613 if (r.persistent) {
9614 numPers++;
9615 }
9616 }
9617 return numPers;
9618 }
9619
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009620 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009621 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009622 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009624
Dianne Hackborn905577f2011-09-07 18:31:28 -07009625 ArrayList<Pair<ProcessRecord, Integer>> list
9626 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9627 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009628 ProcessRecord r = origList.get(i);
9629 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9630 continue;
9631 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009632 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9633 }
9634
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009635 if (list.size() <= 0) {
9636 return false;
9637 }
9638
Dianne Hackborn905577f2011-09-07 18:31:28 -07009639 Comparator<Pair<ProcessRecord, Integer>> comparator
9640 = new Comparator<Pair<ProcessRecord, Integer>>() {
9641 @Override
9642 public int compare(Pair<ProcessRecord, Integer> object1,
9643 Pair<ProcessRecord, Integer> object2) {
9644 if (object1.first.setAdj != object2.first.setAdj) {
9645 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9646 }
9647 if (object1.second.intValue() != object2.second.intValue()) {
9648 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9649 }
9650 return 0;
9651 }
9652 };
9653
9654 Collections.sort(list, comparator);
9655
Dianne Hackborn287952c2010-09-22 22:34:31 -07009656 final long curRealtime = SystemClock.elapsedRealtime();
9657 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9658 final long curUptime = SystemClock.uptimeMillis();
9659 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9660
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009661 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009662 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009663 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009664 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009665 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009666 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9667 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009668 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9669 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009670 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9671 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009672 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9673 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009674 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009675 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009676 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9677 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9678 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9679 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9680 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9681 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9682 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9683 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009684 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9685 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009686 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9687 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009688 } else {
9689 oomAdj = Integer.toString(r.setAdj);
9690 }
9691 String schedGroup;
9692 switch (r.setSchedGroup) {
9693 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9694 schedGroup = "B";
9695 break;
9696 case Process.THREAD_GROUP_DEFAULT:
9697 schedGroup = "F";
9698 break;
9699 default:
9700 schedGroup = Integer.toString(r.setSchedGroup);
9701 break;
9702 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009703 String foreground;
9704 if (r.foregroundActivities) {
9705 foreground = "A";
9706 } else if (r.foregroundServices) {
9707 foreground = "S";
9708 } else {
9709 foreground = " ";
9710 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009711 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009712 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009713 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9714 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009715 if (r.adjSource != null || r.adjTarget != null) {
9716 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009717 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009718 if (r.adjTarget instanceof ComponentName) {
9719 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9720 } else if (r.adjTarget != null) {
9721 pw.print(r.adjTarget.toString());
9722 } else {
9723 pw.print("{null}");
9724 }
9725 pw.print("<=");
9726 if (r.adjSource instanceof ProcessRecord) {
9727 pw.print("Proc{");
9728 pw.print(((ProcessRecord)r.adjSource).toShortString());
9729 pw.println("}");
9730 } else if (r.adjSource != null) {
9731 pw.println(r.adjSource.toString());
9732 } else {
9733 pw.println("{null}");
9734 }
9735 }
9736 if (inclDetails) {
9737 pw.print(prefix);
9738 pw.print(" ");
9739 pw.print("oom: max="); pw.print(r.maxAdj);
9740 pw.print(" hidden="); pw.print(r.hiddenAdj);
9741 pw.print(" curRaw="); pw.print(r.curRawAdj);
9742 pw.print(" setRaw="); pw.print(r.setRawAdj);
9743 pw.print(" cur="); pw.print(r.curAdj);
9744 pw.print(" set="); pw.println(r.setAdj);
9745 pw.print(prefix);
9746 pw.print(" ");
9747 pw.print("keeping="); pw.print(r.keeping);
9748 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009749 pw.print(" empty="); pw.print(r.empty);
9750 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009751
9752 if (!r.keeping) {
9753 if (r.lastWakeTime != 0) {
9754 long wtime;
9755 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9756 synchronized (stats) {
9757 wtime = stats.getProcessWakeTime(r.info.uid,
9758 r.pid, curRealtime);
9759 }
9760 long timeUsed = wtime - r.lastWakeTime;
9761 pw.print(prefix);
9762 pw.print(" ");
9763 pw.print("keep awake over ");
9764 TimeUtils.formatDuration(realtimeSince, pw);
9765 pw.print(" used ");
9766 TimeUtils.formatDuration(timeUsed, pw);
9767 pw.print(" (");
9768 pw.print((timeUsed*100)/realtimeSince);
9769 pw.println("%)");
9770 }
9771 if (r.lastCpuTime != 0) {
9772 long timeUsed = r.curCpuTime - r.lastCpuTime;
9773 pw.print(prefix);
9774 pw.print(" ");
9775 pw.print("run cpu over ");
9776 TimeUtils.formatDuration(uptimeSince, pw);
9777 pw.print(" used ");
9778 TimeUtils.formatDuration(timeUsed, pw);
9779 pw.print(" (");
9780 pw.print((timeUsed*100)/uptimeSince);
9781 pw.println("%)");
9782 }
9783 }
9784 }
9785 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009786 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009787 }
9788
Dianne Hackbornb437e092011-08-05 17:50:29 -07009789 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 ArrayList<ProcessRecord> procs;
9791 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009792 if (args != null && args.length > start
9793 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009794 procs = new ArrayList<ProcessRecord>();
9795 int pid = -1;
9796 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009797 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009798 } catch (NumberFormatException e) {
9799
9800 }
9801 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9802 ProcessRecord proc = mLruProcesses.get(i);
9803 if (proc.pid == pid) {
9804 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009805 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 procs.add(proc);
9807 }
9808 }
9809 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009810 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009811 return null;
9812 }
9813 } else {
9814 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9815 }
9816 }
9817 return procs;
9818 }
9819
9820 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9821 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009822 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009823 if (procs == null) {
9824 return;
9825 }
9826
9827 long uptime = SystemClock.uptimeMillis();
9828 long realtime = SystemClock.elapsedRealtime();
9829 pw.println("Applications Graphics Acceleration Info:");
9830 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9831
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9833 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009834 if (r.thread != null) {
9835 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9836 pw.flush();
9837 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009838 TransferPipe tp = new TransferPipe();
9839 try {
9840 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9841 tp.go(fd);
9842 } finally {
9843 tp.kill();
9844 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009845 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009846 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009848 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009849 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009850 pw.flush();
9851 }
9852 }
9853 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009854 }
9855
Jeff Brown6754ba22011-12-14 20:20:01 -08009856 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9857 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9858 if (procs == null) {
9859 return;
9860 }
9861
9862 pw.println("Applications Database Info:");
9863
9864 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9865 ProcessRecord r = procs.get(i);
9866 if (r.thread != null) {
9867 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9868 pw.flush();
9869 try {
9870 TransferPipe tp = new TransferPipe();
9871 try {
9872 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9873 tp.go(fd);
9874 } finally {
9875 tp.kill();
9876 }
9877 } catch (IOException e) {
9878 pw.println("Failure while dumping the app: " + r);
9879 pw.flush();
9880 } catch (RemoteException e) {
9881 pw.println("Got a RemoteException while dumping the app " + r);
9882 pw.flush();
9883 }
9884 }
9885 }
9886 }
9887
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009888 final static class MemItem {
9889 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009890 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009891 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009892 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009893 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009894
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009895 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009896 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009897 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009898 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009899 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009900 }
9901 }
9902
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009903 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009904 boolean sort) {
9905 if (sort) {
9906 Collections.sort(items, new Comparator<MemItem>() {
9907 @Override
9908 public int compare(MemItem lhs, MemItem rhs) {
9909 if (lhs.pss < rhs.pss) {
9910 return 1;
9911 } else if (lhs.pss > rhs.pss) {
9912 return -1;
9913 }
9914 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009915 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009916 });
9917 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009918
9919 for (int i=0; i<items.size(); i++) {
9920 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009921 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009922 if (mi.subitems != null) {
9923 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9924 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 }
9926 }
9927
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009928 // These are in KB.
9929 static final long[] DUMP_MEM_BUCKETS = new long[] {
9930 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9931 120*1024, 160*1024, 200*1024,
9932 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9933 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9934 };
9935
Dianne Hackborn672342c2011-11-29 11:29:02 -08009936 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9937 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009938 int start = label.lastIndexOf('.');
9939 if (start >= 0) start++;
9940 else start = 0;
9941 int end = label.length();
9942 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9943 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9944 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9945 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009946 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009947 out.append(label, start, end);
9948 return;
9949 }
9950 }
9951 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009952 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009953 out.append(label, start, end);
9954 }
9955
9956 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9957 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9958 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9959 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9960 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9961 };
9962 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9963 "System", "Persistent", "Foreground",
9964 "Visible", "Perceptible", "Heavy Weight",
9965 "Backup", "A Services", "Home", "Previous",
9966 "B Services", "Background"
9967 };
9968
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009969 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009970 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009971 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009972 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009973 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009974
9975 int opti = 0;
9976 while (opti < args.length) {
9977 String opt = args[opti];
9978 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9979 break;
9980 }
9981 opti++;
9982 if ("-a".equals(opt)) {
9983 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009984 } else if ("--oom".equals(opt)) {
9985 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009986 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009987 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009988 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009989 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009990 pw.println("If [process] is specified it can be the name or ");
9991 pw.println("pid of a specific process to dump.");
9992 return;
9993 } else {
9994 pw.println("Unknown argument: " + opt + "; use -h for help");
9995 }
9996 }
9997
9998 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 if (procs == null) {
10000 return;
10001 }
10002
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010003 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010004 long uptime = SystemClock.uptimeMillis();
10005 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010006
10007 if (procs.size() == 1 || isCheckinRequest) {
10008 dumpAll = true;
10009 }
10010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010011 if (isCheckinRequest) {
10012 // short checkin version
10013 pw.println(uptime + "," + realtime);
10014 pw.flush();
10015 } else {
10016 pw.println("Applications Memory Usage (kB):");
10017 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10018 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010019
Dianne Hackbornb437e092011-08-05 17:50:29 -070010020 String[] innerArgs = new String[args.length-opti];
10021 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10022
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010023 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10024 long nativePss=0, dalvikPss=0, otherPss=0;
10025 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10026
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010027 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10028 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10029 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010030
10031 long totalPss = 0;
10032
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010033 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10034 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010036 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10038 pw.flush();
10039 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010040 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010041 if (dumpAll) {
10042 try {
10043 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10044 } catch (RemoteException e) {
10045 if (!isCheckinRequest) {
10046 pw.println("Got RemoteException!");
10047 pw.flush();
10048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010050 } else {
10051 mi = new Debug.MemoryInfo();
10052 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010054
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010055 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 long myTotalPss = mi.getTotalPss();
10057 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010058 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010059 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010060 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010061
10062 nativePss += mi.nativePss;
10063 dalvikPss += mi.dalvikPss;
10064 otherPss += mi.otherPss;
10065 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10066 long mem = mi.getOtherPss(j);
10067 miscPss[j] += mem;
10068 otherPss -= mem;
10069 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010070
10071 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010072 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10073 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010074 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010075 if (oomProcs[oomIndex] == null) {
10076 oomProcs[oomIndex] = new ArrayList<MemItem>();
10077 }
10078 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010079 break;
10080 }
10081 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 }
10084 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010085
10086 if (!isCheckinRequest && procs.size() > 1) {
10087 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10088
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010089 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10090 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10091 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010092 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010093 String label = Debug.MemoryInfo.getOtherLabel(j);
10094 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010095 }
10096
Dianne Hackbornb437e092011-08-05 17:50:29 -070010097 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10098 for (int j=0; j<oomPss.length; j++) {
10099 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010100 String label = DUMP_MEM_OOM_LABEL[j];
10101 MemItem item = new MemItem(label, label, oomPss[j],
10102 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010103 item.subitems = oomProcs[j];
10104 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010105 }
10106 }
10107
Dianne Hackborn672342c2011-11-29 11:29:02 -080010108 if (outTag != null || outStack != null) {
10109 if (outTag != null) {
10110 appendMemBucket(outTag, totalPss, "total", false);
10111 }
10112 if (outStack != null) {
10113 appendMemBucket(outStack, totalPss, "total", true);
10114 }
10115 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010116 for (int i=0; i<oomMems.size(); i++) {
10117 MemItem miCat = oomMems.get(i);
10118 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10119 continue;
10120 }
10121 if (miCat.id < ProcessList.SERVICE_ADJ
10122 || miCat.id == ProcessList.HOME_APP_ADJ
10123 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010124 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10125 outTag.append(" / ");
10126 }
10127 if (outStack != null) {
10128 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10129 if (firstLine) {
10130 outStack.append(":");
10131 firstLine = false;
10132 }
10133 outStack.append("\n\t at ");
10134 } else {
10135 outStack.append("$");
10136 }
10137 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010138 for (int j=0; j<miCat.subitems.size(); j++) {
10139 MemItem mi = miCat.subitems.get(j);
10140 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010141 if (outTag != null) {
10142 outTag.append(" ");
10143 }
10144 if (outStack != null) {
10145 outStack.append("$");
10146 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010147 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010148 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10149 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10150 }
10151 if (outStack != null) {
10152 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10153 }
10154 }
10155 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10156 outStack.append("(");
10157 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10158 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10159 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10160 outStack.append(":");
10161 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10162 }
10163 }
10164 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010165 }
10166 }
10167 }
10168 }
10169
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010170 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010171 pw.println();
10172 pw.println("Total PSS by process:");
10173 dumpMemItems(pw, " ", procMems, true);
10174 pw.println();
10175 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 pw.println("Total PSS by OOM adjustment:");
10177 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010178 if (!oomOnly) {
10179 PrintWriter out = categoryPw != null ? categoryPw : pw;
10180 out.println();
10181 out.println("Total PSS by category:");
10182 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010183 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010185 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010186 final int[] SINGLE_LONG_FORMAT = new int[] {
10187 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10188 };
10189 long[] longOut = new long[1];
10190 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10191 SINGLE_LONG_FORMAT, null, longOut, null);
10192 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10193 longOut[0] = 0;
10194 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10195 SINGLE_LONG_FORMAT, null, longOut, null);
10196 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10197 longOut[0] = 0;
10198 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10199 SINGLE_LONG_FORMAT, null, longOut, null);
10200 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10201 longOut[0] = 0;
10202 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10203 SINGLE_LONG_FORMAT, null, longOut, null);
10204 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10205 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10206 pw.print(shared); pw.println(" kB");
10207 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10208 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 }
10211
10212 /**
10213 * Searches array of arguments for the specified string
10214 * @param args array of argument strings
10215 * @param value value to search for
10216 * @return true if the value is contained in the array
10217 */
10218 private static boolean scanArgs(String[] args, String value) {
10219 if (args != null) {
10220 for (String arg : args) {
10221 if (value.equals(arg)) {
10222 return true;
10223 }
10224 }
10225 }
10226 return false;
10227 }
10228
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010229 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10230 ContentProviderRecord cpr, boolean always) {
10231 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10232
10233 if (!inLaunching || always) {
10234 synchronized (cpr) {
10235 cpr.launchingApp = null;
10236 cpr.notifyAll();
10237 }
10238 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
10239 String names[] = cpr.info.authority.split(";");
10240 for (int j = 0; j < names.length; j++) {
10241 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 }
10243 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010244
10245 for (int i=0; i<cpr.connections.size(); i++) {
10246 ContentProviderConnection conn = cpr.connections.get(i);
10247 if (conn.waiting) {
10248 // If this connection is waiting for the provider, then we don't
10249 // need to mess with its process unless we are always removing
10250 // or for some reason the provider is not currently launching.
10251 if (inLaunching && !always) {
10252 continue;
10253 }
10254 }
10255 ProcessRecord capp = conn.client;
10256 conn.dead = true;
10257 if (conn.stableCount > 0) {
10258 if (!capp.persistent && capp.thread != null
10259 && capp.pid != 0
10260 && capp.pid != MY_PID) {
10261 Slog.i(TAG, "Kill " + capp.processName
10262 + " (pid " + capp.pid + "): provider " + cpr.info.name
10263 + " in dying process " + (proc != null ? proc.processName : "??"));
10264 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10265 capp.processName, capp.setAdj, "dying provider "
10266 + cpr.name.toShortString());
10267 Process.killProcessQuiet(capp.pid);
10268 }
10269 } else if (capp.thread != null && conn.provider.provider != null) {
10270 try {
10271 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10272 } catch (RemoteException e) {
10273 }
10274 // In the protocol here, we don't expect the client to correctly
10275 // clean up this connection, we'll just remove it.
10276 cpr.connections.remove(i);
10277 conn.client.conProviders.remove(conn);
10278 }
10279 }
10280
10281 if (inLaunching && always) {
10282 mLaunchingProviders.remove(cpr);
10283 }
10284 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 }
10286
10287 /**
10288 * Main code for cleaning up a process when it has gone away. This is
10289 * called both as a result of the process dying, or directly when stopping
10290 * a process when running in single process mode.
10291 */
10292 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010293 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010295 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 }
10297
Dianne Hackborn36124872009-10-08 16:22:03 -070010298 mProcessesToGc.remove(app);
10299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010300 // Dismiss any open dialogs.
10301 if (app.crashDialog != null) {
10302 app.crashDialog.dismiss();
10303 app.crashDialog = null;
10304 }
10305 if (app.anrDialog != null) {
10306 app.anrDialog.dismiss();
10307 app.anrDialog = null;
10308 }
10309 if (app.waitDialog != null) {
10310 app.waitDialog.dismiss();
10311 app.waitDialog = null;
10312 }
10313
10314 app.crashing = false;
10315 app.notResponding = false;
10316
10317 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010318 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 app.thread = null;
10320 app.forcingToForeground = null;
10321 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010322 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010323 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010324 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010326 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327
10328 boolean restart = false;
10329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010330 // Remove published content providers.
10331 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010332 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010334 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010335
10336 final boolean always = app.bad || !allowRestart;
10337 if (removeDyingProviderLocked(app, cpr, always) || always) {
10338 // We left the provider in the launching list, need to
10339 // restart it.
10340 restart = true;
10341 }
10342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010343 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010344 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010345 }
10346 app.pubProviders.clear();
10347 }
10348
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010349 // Take care of any launching providers waiting for this process.
10350 if (checkAppInLaunchingProvidersLocked(app, false)) {
10351 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010354 // Unregister from connected content providers.
10355 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010356 for (int i=0; i<app.conProviders.size(); i++) {
10357 ContentProviderConnection conn = app.conProviders.get(i);
10358 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010359 }
10360 app.conProviders.clear();
10361 }
10362
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010363 // At this point there may be remaining entries in mLaunchingProviders
10364 // where we were the only one waiting, so they are no longer of use.
10365 // Look for these and clean up if found.
10366 // XXX Commented out for now. Trying to figure out a way to reproduce
10367 // the actual situation to identify what is actually going on.
10368 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010369 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010370 ContentProviderRecord cpr = (ContentProviderRecord)
10371 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010372 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010373 synchronized (cpr) {
10374 cpr.launchingApp = null;
10375 cpr.notifyAll();
10376 }
10377 }
10378 }
10379 }
10380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010381 skipCurrentReceiverLocked(app);
10382
10383 // Unregister any receivers.
10384 if (app.receivers.size() > 0) {
10385 Iterator<ReceiverList> it = app.receivers.iterator();
10386 while (it.hasNext()) {
10387 removeReceiverLocked(it.next());
10388 }
10389 app.receivers.clear();
10390 }
10391
Christopher Tate181fafa2009-05-14 11:12:14 -070010392 // If the app is undergoing backup, tell the backup manager about it
10393 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010394 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010395 try {
10396 IBackupManager bm = IBackupManager.Stub.asInterface(
10397 ServiceManager.getService(Context.BACKUP_SERVICE));
10398 bm.agentDisconnected(app.info.packageName);
10399 } catch (RemoteException e) {
10400 // can't happen; backup manager is local
10401 }
10402 }
10403
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010404 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10405 ProcessChangeItem item = mPendingProcessChanges.get(i);
10406 if (item.pid == app.pid) {
10407 mPendingProcessChanges.remove(i);
10408 mAvailProcessChanges.add(item);
10409 }
10410 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010411 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 // If the caller is restarting this app, then leave it in its
10414 // current lists and let the caller take care of it.
10415 if (restarting) {
10416 return;
10417 }
10418
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010419 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010420 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010422 mProcessNames.remove(app.processName, app.uid);
10423 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010424 if (mHeavyWeightProcess == app) {
10425 mHeavyWeightProcess = null;
10426 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 } else if (!app.removed) {
10429 // This app is persistent, so we need to keep its record around.
10430 // If it is not already on the pending app list, add it there
10431 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10433 mPersistentStartingProcesses.add(app);
10434 restart = true;
10435 }
10436 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010437 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10438 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439 mProcessesOnHold.remove(app);
10440
The Android Open Source Project4df24232009-03-05 14:34:35 -080010441 if (app == mHomeProcess) {
10442 mHomeProcess = null;
10443 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010444 if (app == mPreviousProcess) {
10445 mPreviousProcess = null;
10446 }
10447
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010448 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 // We have components that still need to be running in the
10450 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010451 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010452 startProcessLocked(app, "restart", app.processName);
10453 } else if (app.pid > 0 && app.pid != MY_PID) {
10454 // Goodbye!
10455 synchronized (mPidsSelfLocked) {
10456 mPidsSelfLocked.remove(app.pid);
10457 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10458 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010459 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 }
10461 }
10462
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010463 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10464 // Look through the content providers we are waiting to have launched,
10465 // and if any run in this process then either schedule a restart of
10466 // the process or kill the client waiting for it if this process has
10467 // gone bad.
10468 int NL = mLaunchingProviders.size();
10469 boolean restart = false;
10470 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010471 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010472 if (cpr.launchingApp == app) {
10473 if (!alwaysBad && !app.bad) {
10474 restart = true;
10475 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010476 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010477 NL = mLaunchingProviders.size();
10478 }
10479 }
10480 }
10481 return restart;
10482 }
10483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 // =========================================================
10485 // SERVICES
10486 // =========================================================
10487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10489 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010490 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010491 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010492 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 }
10494 }
10495
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010496 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010497 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010498 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010499 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010500 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010501 }
10502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010503 public ComponentName startService(IApplicationThread caller, Intent service,
10504 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010505 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010506 // Refuse possible leaked file descriptors
10507 if (service != null && service.hasFileDescriptors() == true) {
10508 throw new IllegalArgumentException("File descriptors passed in Intent");
10509 }
10510
Amith Yamasani742a6712011-05-04 14:49:28 -070010511 if (DEBUG_SERVICE)
10512 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 synchronized(this) {
10514 final int callingPid = Binder.getCallingPid();
10515 final int callingUid = Binder.getCallingUid();
10516 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010517 ComponentName res = mServices.startServiceLocked(caller, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 resolvedType, callingPid, callingUid);
10519 Binder.restoreCallingIdentity(origId);
10520 return res;
10521 }
10522 }
10523
10524 ComponentName startServiceInPackage(int uid,
10525 Intent service, String resolvedType) {
10526 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010527 if (DEBUG_SERVICE)
10528 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010530 ComponentName res = mServices.startServiceLocked(null, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010531 resolvedType, -1, uid);
10532 Binder.restoreCallingIdentity(origId);
10533 return res;
10534 }
10535 }
10536
10537 public int stopService(IApplicationThread caller, Intent service,
10538 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010539 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 // Refuse possible leaked file descriptors
10541 if (service != null && service.hasFileDescriptors() == true) {
10542 throw new IllegalArgumentException("File descriptors passed in Intent");
10543 }
10544
10545 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010546 return mServices.stopServiceLocked(caller, service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010548 }
10549
10550 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010551 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 // Refuse possible leaked file descriptors
10553 if (service != null && service.hasFileDescriptors() == true) {
10554 throw new IllegalArgumentException("File descriptors passed in Intent");
10555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010556 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010557 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 }
10560
10561 public boolean stopServiceToken(ComponentName className, IBinder token,
10562 int startId) {
10563 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010564 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 }
10567
10568 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010569 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010571 mServices.setServiceForegroundLocked(className, token, id, notification,
10572 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010573 }
10574 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010575
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010576 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10577 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010578 boolean result = false;
10579 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010580 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10581 if (ActivityManager.checkUidPermission(
10582 android.Manifest.permission.INTERACT_ACROSS_USERS,
10583 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10584 ComponentName comp = new ComponentName(aInfo.packageName, className);
10585 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10586 + " requests FLAG_SINGLE_USER, but app does not hold "
10587 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10588 Slog.w(TAG, msg);
10589 throw new SecurityException(msg);
10590 }
10591 result = true;
10592 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010593 } else if (componentProcessName == aInfo.packageName) {
10594 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10595 } else if ("system".equals(componentProcessName)) {
10596 result = true;
10597 }
10598 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010599 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10600 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010601 }
10602 return result;
10603 }
10604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 public int bindService(IApplicationThread caller, IBinder token,
10606 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010607 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010608 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010609 // Refuse possible leaked file descriptors
10610 if (service != null && service.hasFileDescriptors() == true) {
10611 throw new IllegalArgumentException("File descriptors passed in Intent");
10612 }
10613
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010614 checkValidCaller(Binder.getCallingUid(), userId);
10615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010617 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10618 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 }
10620 }
10621
10622 public boolean unbindService(IServiceConnection connection) {
10623 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010624 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010626 }
10627
10628 public void publishService(IBinder token, Intent intent, IBinder service) {
10629 // Refuse possible leaked file descriptors
10630 if (intent != null && intent.hasFileDescriptors() == true) {
10631 throw new IllegalArgumentException("File descriptors passed in Intent");
10632 }
10633
10634 synchronized(this) {
10635 if (!(token instanceof ServiceRecord)) {
10636 throw new IllegalArgumentException("Invalid service token");
10637 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010638 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 }
10640 }
10641
10642 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10643 // Refuse possible leaked file descriptors
10644 if (intent != null && intent.hasFileDescriptors() == true) {
10645 throw new IllegalArgumentException("File descriptors passed in Intent");
10646 }
10647
10648 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010649 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 }
10651 }
10652
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010653 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010654 synchronized(this) {
10655 if (!(token instanceof ServiceRecord)) {
10656 throw new IllegalArgumentException("Invalid service token");
10657 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010658 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 }
10661
10662 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010663 // BACKUP AND RESTORE
10664 // =========================================================
10665
10666 // Cause the target app to be launched if necessary and its backup agent
10667 // instantiated. The backup agent will invoke backupAgentCreated() on the
10668 // activity manager to announce its creation.
10669 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010670 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010671 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10672
10673 synchronized(this) {
10674 // !!! TODO: currently no check here that we're already bound
10675 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10676 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10677 synchronized (stats) {
10678 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10679 }
10680
Dianne Hackborne7f97212011-02-24 14:40:20 -080010681 // Backup agent is now in use, its package can't be stopped.
10682 try {
10683 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010684 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010685 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010686 } catch (IllegalArgumentException e) {
10687 Slog.w(TAG, "Failed trying to unstop package "
10688 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010689 }
10690
Christopher Tate181fafa2009-05-14 11:12:14 -070010691 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010692 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10693 ? new ComponentName(app.packageName, app.backupAgentName)
10694 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010695 // startProcessLocked() returns existing proc's record if it's already running
10696 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010697 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010698 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010699 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010700 return false;
10701 }
10702
10703 r.app = proc;
10704 mBackupTarget = r;
10705 mBackupAppName = app.packageName;
10706
Christopher Tate6fa95972009-06-05 18:43:55 -070010707 // Try not to kill the process during backup
10708 updateOomAdjLocked(proc);
10709
Christopher Tate181fafa2009-05-14 11:12:14 -070010710 // If the process is already attached, schedule the creation of the backup agent now.
10711 // If it is not yet live, this will be done when it attaches to the framework.
10712 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010713 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010714 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010715 proc.thread.scheduleCreateBackupAgent(app,
10716 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010717 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010718 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010719 }
10720 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010721 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010722 }
10723 // Invariants: at this point, the target app process exists and the application
10724 // is either already running or in the process of coming up. mBackupTarget and
10725 // mBackupAppName describe the app, so that when it binds back to the AM we
10726 // know that it's scheduled for a backup-agent operation.
10727 }
10728
10729 return true;
10730 }
10731
10732 // A backup agent has just come up
10733 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010734 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010735 + " = " + agent);
10736
10737 synchronized(this) {
10738 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010739 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010740 return;
10741 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010742 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010743
Dianne Hackborn06740692010-09-22 22:46:21 -070010744 long oldIdent = Binder.clearCallingIdentity();
10745 try {
10746 IBackupManager bm = IBackupManager.Stub.asInterface(
10747 ServiceManager.getService(Context.BACKUP_SERVICE));
10748 bm.agentConnected(agentPackageName, agent);
10749 } catch (RemoteException e) {
10750 // can't happen; the backup manager service is local
10751 } catch (Exception e) {
10752 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10753 e.printStackTrace();
10754 } finally {
10755 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010756 }
10757 }
10758
10759 // done with this agent
10760 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010761 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010762 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010763 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010764 return;
10765 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010766
10767 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010768 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010769 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010770 return;
10771 }
10772
Christopher Tate181fafa2009-05-14 11:12:14 -070010773 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010774 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010775 return;
10776 }
10777
Christopher Tate6fa95972009-06-05 18:43:55 -070010778 ProcessRecord proc = mBackupTarget.app;
10779 mBackupTarget = null;
10780 mBackupAppName = null;
10781
10782 // Not backing this app up any more; reset its OOM adjustment
10783 updateOomAdjLocked(proc);
10784
Christopher Tatec7b31e32009-06-10 15:49:30 -070010785 // If the app crashed during backup, 'thread' will be null here
10786 if (proc.thread != null) {
10787 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010788 proc.thread.scheduleDestroyBackupAgent(appInfo,
10789 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010790 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010791 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010792 e.printStackTrace();
10793 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010794 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010795 }
10796 }
10797 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 // BROADCASTS
10799 // =========================================================
10800
Josh Bartel7f208742010-02-25 11:01:44 -060010801 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 List cur) {
10803 final ContentResolver resolver = mContext.getContentResolver();
10804 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10805 if (list == null) {
10806 return cur;
10807 }
10808 int N = list.size();
10809 for (int i=0; i<N; i++) {
10810 Intent intent = list.get(i);
10811 if (filter.match(resolver, intent, true, TAG) >= 0) {
10812 if (cur == null) {
10813 cur = new ArrayList<Intent>();
10814 }
10815 cur.add(intent);
10816 }
10817 }
10818 return cur;
10819 }
10820
Christopher Tatef46723b2012-01-26 14:19:24 -080010821 boolean isPendingBroadcastProcessLocked(int pid) {
10822 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
10823 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
10824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825
Christopher Tatef46723b2012-01-26 14:19:24 -080010826 void skipPendingBroadcastLocked(int pid) {
10827 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
10828 for (BroadcastQueue queue : mBroadcastQueues) {
10829 queue.skipPendingBroadcastLocked(pid);
10830 }
10831 }
10832
10833 // The app just attached; send any pending broadcasts that it should receive
10834 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
10835 boolean didSomething = false;
10836 for (BroadcastQueue queue : mBroadcastQueues) {
10837 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010839 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010842 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010844 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010845 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010846 synchronized(this) {
10847 ProcessRecord callerApp = null;
10848 if (caller != null) {
10849 callerApp = getRecordForAppLocked(caller);
10850 if (callerApp == null) {
10851 throw new SecurityException(
10852 "Unable to find app for caller " + caller
10853 + " (pid=" + Binder.getCallingPid()
10854 + ") when registering receiver " + receiver);
10855 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010856 if (callerApp.info.uid != Process.SYSTEM_UID &&
10857 !callerApp.pkgList.contains(callerPackage)) {
10858 throw new SecurityException("Given caller package " + callerPackage
10859 + " is not running in process " + callerApp);
10860 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010861 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010862 } else {
10863 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010864 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 }
10866
10867 List allSticky = null;
10868
10869 // Look for any matching sticky broadcasts...
10870 Iterator actions = filter.actionsIterator();
10871 if (actions != null) {
10872 while (actions.hasNext()) {
10873 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010874 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010875 }
10876 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010877 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 }
10879
10880 // The first sticky in the list is returned directly back to
10881 // the client.
10882 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10883
Joe Onorato8a9b2202010-02-26 18:56:32 -080010884 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885 + ": " + sticky);
10886
10887 if (receiver == null) {
10888 return sticky;
10889 }
10890
10891 ReceiverList rl
10892 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10893 if (rl == null) {
10894 rl = new ReceiverList(this, callerApp,
10895 Binder.getCallingPid(),
10896 Binder.getCallingUid(), receiver);
10897 if (rl.app != null) {
10898 rl.app.receivers.add(rl);
10899 } else {
10900 try {
10901 receiver.asBinder().linkToDeath(rl, 0);
10902 } catch (RemoteException e) {
10903 return sticky;
10904 }
10905 rl.linkedToDeath = true;
10906 }
10907 mRegisteredReceivers.put(receiver.asBinder(), rl);
10908 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010909 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
10910 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010911 rl.add(bf);
10912 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010913 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010914 }
10915 mReceiverResolver.addFilter(bf);
10916
10917 // Enqueue broadcasts for all existing stickies that match
10918 // this filter.
10919 if (allSticky != null) {
10920 ArrayList receivers = new ArrayList();
10921 receivers.add(bf);
10922
10923 int N = allSticky.size();
10924 for (int i=0; i<N; i++) {
10925 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080010926 BroadcastQueue queue = broadcastQueueForIntent(intent);
10927 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010929 false, true, true, false);
Christopher Tatef46723b2012-01-26 14:19:24 -080010930 queue.enqueueParallelBroadcastLocked(r);
10931 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932 }
10933 }
10934
10935 return sticky;
10936 }
10937 }
10938
10939 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010940 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941
Christopher Tatef46723b2012-01-26 14:19:24 -080010942 final long origId = Binder.clearCallingIdentity();
10943 try {
10944 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945
Christopher Tatef46723b2012-01-26 14:19:24 -080010946 synchronized(this) {
10947 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080010949 if (rl != null) {
10950 if (rl.curBroadcast != null) {
10951 BroadcastRecord r = rl.curBroadcast;
10952 final boolean doNext = finishReceiverLocked(
10953 receiver.asBinder(), r.resultCode, r.resultData,
10954 r.resultExtras, r.resultAbort, true);
10955 if (doNext) {
10956 doTrim = true;
10957 r.queue.processNextBroadcast(false);
10958 }
10959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960
Christopher Tatef46723b2012-01-26 14:19:24 -080010961 if (rl.app != null) {
10962 rl.app.receivers.remove(rl);
10963 }
10964 removeReceiverLocked(rl);
10965 if (rl.linkedToDeath) {
10966 rl.linkedToDeath = false;
10967 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 }
10970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971
Christopher Tatef46723b2012-01-26 14:19:24 -080010972 // If we actually concluded any broadcasts, we might now be able
10973 // to trim the recipients' apps from our working set
10974 if (doTrim) {
10975 trimApplications();
10976 return;
10977 }
10978
10979 } finally {
10980 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 }
10983
10984 void removeReceiverLocked(ReceiverList rl) {
10985 mRegisteredReceivers.remove(rl.receiver.asBinder());
10986 int N = rl.size();
10987 for (int i=0; i<N; i++) {
10988 mReceiverResolver.removeFilter(rl.get(i));
10989 }
10990 }
10991
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070010992 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
10993 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10994 ProcessRecord r = mLruProcesses.get(i);
10995 if (r.thread != null) {
10996 try {
10997 r.thread.dispatchPackageBroadcast(cmd, packages);
10998 } catch (RemoteException ex) {
10999 }
11000 }
11001 }
11002 }
11003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011004 private final int broadcastIntentLocked(ProcessRecord callerApp,
11005 String callerPackage, Intent intent, String resolvedType,
11006 IIntentReceiver resultTo, int resultCode, String resultData,
11007 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011008 boolean ordered, boolean sticky, int callingPid, int callingUid,
11009 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 intent = new Intent(intent);
11011
Dianne Hackborne7f97212011-02-24 14:40:20 -080011012 // By default broadcasts do not go to stopped apps.
11013 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11014
Joe Onorato8a9b2202010-02-26 18:56:32 -080011015 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011017 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011019 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011021
11022 boolean onlySendToCaller = false;
11023
11024 // If the caller is trying to send this broadcast to a different
11025 // user, verify that is allowed.
11026 if (UserId.getUserId(callingUid) != userId) {
11027 if (checkComponentPermission(
11028 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11029 callingPid, callingUid, -1, true)
11030 != PackageManager.PERMISSION_GRANTED) {
11031 if (checkComponentPermission(
11032 android.Manifest.permission.INTERACT_ACROSS_USERS,
11033 callingPid, callingUid, -1, true)
11034 == PackageManager.PERMISSION_GRANTED) {
11035 onlySendToCaller = true;
11036 } else {
11037 String msg = "Permission Denial: " + intent.getAction()
11038 + " broadcast from " + callerPackage
11039 + " asks to send as user " + userId
11040 + " but is calling from user " + UserId.getUserId(callingUid)
11041 + "; this requires "
11042 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11043 Slog.w(TAG, msg);
11044 throw new SecurityException(msg);
11045 }
11046 }
11047 }
11048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 // Handle special intents: if this broadcast is from the package
11050 // manager about a package being removed, we need to remove all of
11051 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011052 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011054 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11055 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011056 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 || uidRemoved) {
11058 if (checkComponentPermission(
11059 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011060 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 == PackageManager.PERMISSION_GRANTED) {
11062 if (uidRemoved) {
11063 final Bundle intentExtras = intent.getExtras();
11064 final int uid = intentExtras != null
11065 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11066 if (uid >= 0) {
11067 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11068 synchronized (bs) {
11069 bs.removeUidStatsLocked(uid);
11070 }
11071 }
11072 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011073 // If resources are unvailble just force stop all
11074 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011075 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011076 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11077 if (list != null && (list.length > 0)) {
11078 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011079 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011080 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011081 sendPackageBroadcastLocked(
11082 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011083 }
11084 } else {
11085 Uri data = intent.getData();
11086 String ssp;
11087 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11088 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11089 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011090 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11091 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011092 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011093 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011094 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11095 new String[] {ssp});
11096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 }
11098 }
11099 }
11100 } else {
11101 String msg = "Permission Denial: " + intent.getAction()
11102 + " broadcast from " + callerPackage + " (pid=" + callingPid
11103 + ", uid=" + callingUid + ")"
11104 + " requires "
11105 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011106 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 throw new SecurityException(msg);
11108 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011109
11110 // Special case for adding a package: by default turn on compatibility
11111 // mode.
11112 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011113 Uri data = intent.getData();
11114 String ssp;
11115 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11116 mCompatModePackages.handlePackageAddedLocked(ssp,
11117 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011119 }
11120
11121 /*
11122 * If this is the time zone changed action, queue up a message that will reset the timezone
11123 * of all currently running processes. This message will get queued up before the broadcast
11124 * happens.
11125 */
11126 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11127 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11128 }
11129
Robert Greenwalt03595d02010-11-02 14:08:23 -070011130 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11131 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11132 }
11133
Robert Greenwalt434203a2010-10-11 16:00:27 -070011134 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11135 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11136 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11137 }
11138
Dianne Hackborn854060af2009-07-09 18:14:31 -070011139 /*
11140 * Prevent non-system code (defined here to be non-persistent
11141 * processes) from sending protected broadcasts.
11142 */
11143 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070011144 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11145 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070011146 // Always okay.
11147 } else if (callerApp == null || !callerApp.persistent) {
11148 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011149 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011150 intent.getAction())) {
11151 String msg = "Permission Denial: not allowed to send broadcast "
11152 + intent.getAction() + " from pid="
11153 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011154 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011155 throw new SecurityException(msg);
11156 }
11157 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011158 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011159 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070011160 }
11161 }
11162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 // Add to the sticky list if requested.
11164 if (sticky) {
11165 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11166 callingPid, callingUid)
11167 != PackageManager.PERMISSION_GRANTED) {
11168 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11169 + callingPid + ", uid=" + callingUid
11170 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011171 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 throw new SecurityException(msg);
11173 }
11174 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011175 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011177 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 }
11179 if (intent.getComponent() != null) {
11180 throw new SecurityException(
11181 "Sticky broadcasts can't target a specific component");
11182 }
11183 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11184 if (list == null) {
11185 list = new ArrayList<Intent>();
11186 mStickyBroadcasts.put(intent.getAction(), list);
11187 }
11188 int N = list.size();
11189 int i;
11190 for (i=0; i<N; i++) {
11191 if (intent.filterEquals(list.get(i))) {
11192 // This sticky already exists, replace it.
11193 list.set(i, new Intent(intent));
11194 break;
11195 }
11196 }
11197 if (i >= N) {
11198 list.add(new Intent(intent));
11199 }
11200 }
11201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 // Figure out who all will receive this broadcast.
11203 List receivers = null;
11204 List<BroadcastFilter> registeredReceivers = null;
11205 try {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011206 // Need to resolve the intent to interested receivers...
11207 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11208 == 0) {
11209 receivers = AppGlobals.getPackageManager().queryIntentReceivers(
11210 intent, resolvedType, STOCK_PM_FLAGS, userId);
11211 }
11212 if (intent.getComponent() == null) {
11213 registeredReceivers = mReceiverResolver.queryIntent(intent,
11214 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
11216 } catch (RemoteException ex) {
11217 // pm is in same process, this will never happen.
11218 }
11219
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011220 final boolean replacePending =
11221 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11222
Joe Onorato8a9b2202010-02-26 18:56:32 -080011223 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011224 + " replacePending=" + replacePending);
11225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011226 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11227 if (!ordered && NR > 0) {
11228 // If we are not serializing this broadcast, then send the
11229 // registered receivers separately so they don't wait for the
11230 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011231 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11232 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011233 callerPackage, callingPid, callingUid, requiredPermission,
11234 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011235 ordered, sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011236 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011237 TAG, "Enqueueing parallel broadcast " + r);
11238 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011239 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011240 queue.enqueueParallelBroadcastLocked(r);
11241 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 registeredReceivers = null;
11244 NR = 0;
11245 }
11246
11247 // Merge into one list.
11248 int ir = 0;
11249 if (receivers != null) {
11250 // A special case for PACKAGE_ADDED: do not allow the package
11251 // being added to see this broadcast. This prevents them from
11252 // using this as a back door to get run as soon as they are
11253 // installed. Maybe in the future we want to have a special install
11254 // broadcast or such for apps, but we'd like to deliberately make
11255 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011256 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011257 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11258 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11259 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011260 Uri data = intent.getData();
11261 if (data != null) {
11262 String pkgName = data.getSchemeSpecificPart();
11263 if (pkgName != null) {
11264 skipPackages = new String[] { pkgName };
11265 }
11266 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011267 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011268 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011269 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011270 if (skipPackages != null && (skipPackages.length > 0)) {
11271 for (String skipPackage : skipPackages) {
11272 if (skipPackage != null) {
11273 int NT = receivers.size();
11274 for (int it=0; it<NT; it++) {
11275 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11276 if (curt.activityInfo.packageName.equals(skipPackage)) {
11277 receivers.remove(it);
11278 it--;
11279 NT--;
11280 }
11281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 }
11283 }
11284 }
11285
11286 int NT = receivers != null ? receivers.size() : 0;
11287 int it = 0;
11288 ResolveInfo curt = null;
11289 BroadcastFilter curr = null;
11290 while (it < NT && ir < NR) {
11291 if (curt == null) {
11292 curt = (ResolveInfo)receivers.get(it);
11293 }
11294 if (curr == null) {
11295 curr = registeredReceivers.get(ir);
11296 }
11297 if (curr.getPriority() >= curt.priority) {
11298 // Insert this broadcast record into the final list.
11299 receivers.add(it, curr);
11300 ir++;
11301 curr = null;
11302 it++;
11303 NT++;
11304 } else {
11305 // Skip to the next ResolveInfo in the final list.
11306 it++;
11307 curt = null;
11308 }
11309 }
11310 }
11311 while (ir < NR) {
11312 if (receivers == null) {
11313 receivers = new ArrayList();
11314 }
11315 receivers.add(registeredReceivers.get(ir));
11316 ir++;
11317 }
11318
11319 if ((receivers != null && receivers.size() > 0)
11320 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011321 BroadcastQueue queue = broadcastQueueForIntent(intent);
11322 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011324 receivers, resultTo, resultCode, resultData, map, ordered,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011325 sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011326 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011328 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 if (DEBUG_BROADCAST) {
11330 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011331 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011333 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011334 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011335 queue.enqueueOrderedBroadcastLocked(r);
11336 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011338 }
11339
Dianne Hackborna4972e92012-03-14 10:38:05 -070011340 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 }
11342
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011343 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011344 // Refuse possible leaked file descriptors
11345 if (intent != null && intent.hasFileDescriptors() == true) {
11346 throw new IllegalArgumentException("File descriptors passed in Intent");
11347 }
11348
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011349 int flags = intent.getFlags();
11350
11351 if (!mProcessesReady) {
11352 // if the caller really truly claims to know what they're doing, go
11353 // ahead and allow the broadcast without launching any receivers
11354 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11355 intent = new Intent(intent);
11356 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11357 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11358 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11359 + " before boot completion");
11360 throw new IllegalStateException("Cannot broadcast before boot completed");
11361 }
11362 }
11363
11364 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11365 throw new IllegalArgumentException(
11366 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11367 }
11368
11369 return intent;
11370 }
11371
11372 public final int broadcastIntent(IApplicationThread caller,
11373 Intent intent, String resolvedType, IIntentReceiver resultTo,
11374 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011375 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011376 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011378 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011380 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11381 final int callingPid = Binder.getCallingPid();
11382 final int callingUid = Binder.getCallingUid();
11383 final long origId = Binder.clearCallingIdentity();
11384 int res = broadcastIntentLocked(callerApp,
11385 callerApp != null ? callerApp.info.packageName : null,
11386 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011387 resultCode, resultData, map, requiredPermission, serialized, sticky,
11388 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 Binder.restoreCallingIdentity(origId);
11390 return res;
11391 }
11392 }
11393
11394 int broadcastIntentInPackage(String packageName, int uid,
11395 Intent intent, String resolvedType, IIntentReceiver resultTo,
11396 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011397 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011398 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011399 intent = verifyBroadcastLocked(intent);
11400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 final long origId = Binder.clearCallingIdentity();
11402 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11403 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011404 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011405 Binder.restoreCallingIdentity(origId);
11406 return res;
11407 }
11408 }
11409
Amith Yamasani742a6712011-05-04 14:49:28 -070011410 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
11411 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 // Refuse possible leaked file descriptors
11413 if (intent != null && intent.hasFileDescriptors() == true) {
11414 throw new IllegalArgumentException("File descriptors passed in Intent");
11415 }
11416
11417 synchronized(this) {
11418 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11419 != PackageManager.PERMISSION_GRANTED) {
11420 String msg = "Permission Denial: unbroadcastIntent() from pid="
11421 + Binder.getCallingPid()
11422 + ", uid=" + Binder.getCallingUid()
11423 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011424 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011425 throw new SecurityException(msg);
11426 }
11427 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11428 if (list != null) {
11429 int N = list.size();
11430 int i;
11431 for (i=0; i<N; i++) {
11432 if (intent.filterEquals(list.get(i))) {
11433 list.remove(i);
11434 break;
11435 }
11436 }
11437 }
11438 }
11439 }
11440
11441 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11442 String resultData, Bundle resultExtras, boolean resultAbort,
11443 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011444 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11445 if (r == null) {
11446 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 return false;
11448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449
Christopher Tatef46723b2012-01-26 14:19:24 -080011450 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11451 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011452 }
11453
11454 public void finishReceiver(IBinder who, int resultCode, String resultData,
11455 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011456 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011457
11458 // Refuse possible leaked file descriptors
11459 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11460 throw new IllegalArgumentException("File descriptors passed in Bundle");
11461 }
11462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011464 try {
11465 boolean doNext = false;
11466 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467
Christopher Tatef46723b2012-01-26 14:19:24 -080011468 synchronized(this) {
11469 r = broadcastRecordForReceiverLocked(who);
11470 if (r != null) {
11471 doNext = r.queue.finishReceiverLocked(r, resultCode,
11472 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011475
Christopher Tatef46723b2012-01-26 14:19:24 -080011476 if (doNext) {
11477 r.queue.processNextBroadcast(false);
11478 }
11479 trimApplications();
11480 } finally {
11481 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 // =========================================================
11486 // INSTRUMENTATION
11487 // =========================================================
11488
11489 public boolean startInstrumentation(ComponentName className,
11490 String profileFile, int flags, Bundle arguments,
11491 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011492 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 // Refuse possible leaked file descriptors
11494 if (arguments != null && arguments.hasFileDescriptors()) {
11495 throw new IllegalArgumentException("File descriptors passed in Bundle");
11496 }
11497
11498 synchronized(this) {
11499 InstrumentationInfo ii = null;
11500 ApplicationInfo ai = null;
11501 try {
11502 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011503 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011505 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506 } catch (PackageManager.NameNotFoundException e) {
11507 }
11508 if (ii == null) {
11509 reportStartInstrumentationFailure(watcher, className,
11510 "Unable to find instrumentation info for: " + className);
11511 return false;
11512 }
11513 if (ai == null) {
11514 reportStartInstrumentationFailure(watcher, className,
11515 "Unable to find instrumentation target package: " + ii.targetPackage);
11516 return false;
11517 }
11518
11519 int match = mContext.getPackageManager().checkSignatures(
11520 ii.targetPackage, ii.packageName);
11521 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11522 String msg = "Permission Denial: starting instrumentation "
11523 + className + " from pid="
11524 + Binder.getCallingPid()
11525 + ", uid=" + Binder.getCallingPid()
11526 + " not allowed because package " + ii.packageName
11527 + " does not have a signature matching the target "
11528 + ii.targetPackage;
11529 reportStartInstrumentationFailure(watcher, className, msg);
11530 throw new SecurityException(msg);
11531 }
11532
Amith Yamasani483f3b02012-03-13 16:08:00 -070011533 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011535 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011536 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011537 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011539 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 app.instrumentationProfileFile = profileFile;
11541 app.instrumentationArguments = arguments;
11542 app.instrumentationWatcher = watcher;
11543 app.instrumentationResultClass = className;
11544 Binder.restoreCallingIdentity(origId);
11545 }
11546
11547 return true;
11548 }
11549
11550 /**
11551 * Report errors that occur while attempting to start Instrumentation. Always writes the
11552 * error to the logs, but if somebody is watching, send the report there too. This enables
11553 * the "am" command to report errors with more information.
11554 *
11555 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11556 * @param cn The component name of the instrumentation.
11557 * @param report The error report.
11558 */
11559 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11560 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011561 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 try {
11563 if (watcher != null) {
11564 Bundle results = new Bundle();
11565 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11566 results.putString("Error", report);
11567 watcher.instrumentationStatus(cn, -1, results);
11568 }
11569 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011570 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 }
11572 }
11573
11574 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11575 if (app.instrumentationWatcher != null) {
11576 try {
11577 // NOTE: IInstrumentationWatcher *must* be oneway here
11578 app.instrumentationWatcher.instrumentationFinished(
11579 app.instrumentationClass,
11580 resultCode,
11581 results);
11582 } catch (RemoteException e) {
11583 }
11584 }
11585 app.instrumentationWatcher = null;
11586 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011587 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011588 app.instrumentationProfileFile = null;
11589 app.instrumentationArguments = null;
11590
Amith Yamasani483f3b02012-03-13 16:08:00 -070011591 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 }
11593
11594 public void finishInstrumentation(IApplicationThread target,
11595 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011596 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 // Refuse possible leaked file descriptors
11598 if (results != null && results.hasFileDescriptors()) {
11599 throw new IllegalArgumentException("File descriptors passed in Intent");
11600 }
11601
11602 synchronized(this) {
11603 ProcessRecord app = getRecordForAppLocked(target);
11604 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011605 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 return;
11607 }
11608 final long origId = Binder.clearCallingIdentity();
11609 finishInstrumentationLocked(app, resultCode, results);
11610 Binder.restoreCallingIdentity(origId);
11611 }
11612 }
11613
11614 // =========================================================
11615 // CONFIGURATION
11616 // =========================================================
11617
11618 public ConfigurationInfo getDeviceConfigurationInfo() {
11619 ConfigurationInfo config = new ConfigurationInfo();
11620 synchronized (this) {
11621 config.reqTouchScreen = mConfiguration.touchscreen;
11622 config.reqKeyboardType = mConfiguration.keyboard;
11623 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011624 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11625 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11627 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011628 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11629 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011630 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11631 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011632 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 }
11634 return config;
11635 }
11636
11637 public Configuration getConfiguration() {
11638 Configuration ci;
11639 synchronized(this) {
11640 ci = new Configuration(mConfiguration);
11641 }
11642 return ci;
11643 }
11644
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011645 public void updatePersistentConfiguration(Configuration values) {
11646 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11647 "updateConfiguration()");
11648 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11649 "updateConfiguration()");
11650 if (values == null) {
11651 throw new NullPointerException("Configuration must not be null");
11652 }
11653
11654 synchronized(this) {
11655 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011656 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011657 Binder.restoreCallingIdentity(origId);
11658 }
11659 }
11660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 public void updateConfiguration(Configuration values) {
11662 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11663 "updateConfiguration()");
11664
11665 synchronized(this) {
11666 if (values == null && mWindowManager != null) {
11667 // sentinel: fetch the current configuration from the window manager
11668 values = mWindowManager.computeNewConfiguration();
11669 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011670
11671 if (mWindowManager != null) {
11672 mProcessList.applyDisplaySize(mWindowManager);
11673 }
11674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011676 if (values != null) {
11677 Settings.System.clearConfiguration(values);
11678 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011679 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011680 Binder.restoreCallingIdentity(origId);
11681 }
11682 }
11683
11684 /**
11685 * Do either or both things: (1) change the current configuration, and (2)
11686 * make sure the given activity is running with the (now) current
11687 * configuration. Returns true if the activity has been left running, or
11688 * false if <var>starting</var> is being destroyed to match the new
11689 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011690 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011692 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011693 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011694 // do nothing if we are headless
11695 if (mHeadless) return true;
11696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 int changes = 0;
11698
11699 boolean kept = true;
11700
11701 if (values != null) {
11702 Configuration newConfig = new Configuration(mConfiguration);
11703 changes = newConfig.updateFrom(values);
11704 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011705 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011706 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 }
11708
Doug Zongker2bec3d42009-12-04 12:52:44 -080011709 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710
Dianne Hackborn813075a62011-11-14 17:45:19 -080011711 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 saveLocaleLocked(values.locale,
11713 !values.locale.equals(mConfiguration.locale),
11714 values.userSetLocale);
11715 }
11716
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011717 mConfigurationSeq++;
11718 if (mConfigurationSeq <= 0) {
11719 mConfigurationSeq = 1;
11720 }
11721 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011723 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011724
11725 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070011726
11727 // TODO: If our config changes, should we auto dismiss any currently
11728 // showing dialogs?
11729 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011730
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011731 AttributeCache ac = AttributeCache.instance();
11732 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080011733 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011736 // Make sure all resources in our process are updated
11737 // right now, so that anyone who is going to retrieve
11738 // resource values after we return will be sure to get
11739 // the new ones. This is especially important during
11740 // boot, where the first config change needs to guarantee
11741 // all resources have that config before following boot
11742 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080011743 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011744
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011745 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011746 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011747 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011748 mHandler.sendMessage(msg);
11749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011750
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011751 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11752 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011753 try {
11754 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011755 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011756 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011757 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 }
11759 } catch (Exception e) {
11760 }
11761 }
11762 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11764 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011766 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011767 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11768 broadcastIntentLocked(null, null,
11769 new Intent(Intent.ACTION_LOCALE_CHANGED),
11770 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011771 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773 }
11774 }
11775
11776 if (changes != 0 && starting == null) {
11777 // If the configuration changed, and the caller is not already
11778 // in the process of starting an activity, then find the top
11779 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011780 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011781 }
11782
11783 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011784 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011785 // And we need to make sure at this point that all other activities
11786 // are made visible with the correct configuration.
11787 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 }
11789
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011790 if (values != null && mWindowManager != null) {
11791 mWindowManager.setNewConfiguration(mConfiguration);
11792 }
11793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 return kept;
11795 }
Joe Onorato54a4a412011-11-02 20:50:08 -070011796
11797 /**
11798 * Decide based on the configuration whether we should shouw the ANR,
11799 * crash, etc dialogs. The idea is that if there is no affordnace to
11800 * press the on-screen buttons, we shouldn't show the dialog.
11801 *
11802 * A thought: SystemUI might also want to get told about this, the Power
11803 * dialog / global actions also might want different behaviors.
11804 */
11805 private static final boolean shouldShowDialogs(Configuration config) {
11806 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
11807 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
11808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809
11810 /**
11811 * Save the locale. You must be inside a synchronized (this) block.
11812 */
11813 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11814 if(isDiff) {
11815 SystemProperties.set("user.language", l.getLanguage());
11816 SystemProperties.set("user.region", l.getCountry());
11817 }
11818
11819 if(isPersist) {
11820 SystemProperties.set("persist.sys.language", l.getLanguage());
11821 SystemProperties.set("persist.sys.country", l.getCountry());
11822 SystemProperties.set("persist.sys.localevar", l.getVariant());
11823 }
11824 }
11825
Adam Powelldd8fab22012-03-22 17:47:27 -070011826 @Override
11827 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
11828 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011829 return srec != null && srec.task.affinity != null &&
11830 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070011831 }
11832
11833 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
11834 Intent resultData) {
11835 ComponentName dest = destIntent.getComponent();
11836
11837 synchronized (this) {
11838 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011839 if (srec == null) {
11840 return false;
11841 }
Adam Powelldd8fab22012-03-22 17:47:27 -070011842 ArrayList<ActivityRecord> history = srec.stack.mHistory;
11843 final int start = history.indexOf(srec);
11844 if (start < 0) {
11845 // Current activity is not in history stack; do nothing.
11846 return false;
11847 }
11848 int finishTo = start - 1;
11849 ActivityRecord parent = null;
11850 boolean foundParentInTask = false;
11851 if (dest != null) {
11852 TaskRecord tr = srec.task;
11853 for (int i = start - 1; i >= 0; i--) {
11854 ActivityRecord r = history.get(i);
11855 if (tr != r.task) {
11856 // Couldn't find parent in the same task; stop at the one above this.
11857 // (Root of current task; in-app "home" behavior)
11858 // Always at least finish the current activity.
11859 finishTo = Math.min(start - 1, i + 1);
11860 parent = history.get(finishTo);
11861 break;
11862 } else if (r.info.packageName.equals(dest.getPackageName()) &&
11863 r.info.name.equals(dest.getClassName())) {
11864 finishTo = i;
11865 parent = r;
11866 foundParentInTask = true;
11867 break;
11868 }
11869 }
11870 }
11871
11872 if (mController != null) {
11873 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
11874 if (next != null) {
11875 // ask watcher if this is allowed
11876 boolean resumeOK = true;
11877 try {
11878 resumeOK = mController.activityResuming(next.packageName);
11879 } catch (RemoteException e) {
11880 mController = null;
11881 }
11882
11883 if (!resumeOK) {
11884 return false;
11885 }
11886 }
11887 }
11888 final long origId = Binder.clearCallingIdentity();
11889 for (int i = start; i > finishTo; i--) {
11890 ActivityRecord r = history.get(i);
11891 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
11892 "navigate-up");
11893 // Only return the supplied result for the first activity finished
11894 resultCode = Activity.RESULT_CANCELED;
11895 resultData = null;
11896 }
11897
11898 if (parent != null && foundParentInTask) {
11899 final int parentLaunchMode = parent.info.launchMode;
11900 final int destIntentFlags = destIntent.getFlags();
11901 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
11902 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
11903 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
11904 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070011905 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070011906 } else {
11907 try {
11908 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
11909 destIntent.getComponent(), 0, UserId.getCallingUserId());
11910 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
11911 null, aInfo, parent.appToken, null,
11912 0, -1, parent.launchedFromUid, 0, null, true, null);
11913 foundParentInTask = res == ActivityManager.START_SUCCESS;
11914 } catch (RemoteException e) {
11915 foundParentInTask = false;
11916 }
11917 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
11918 resultData, "navigate-up");
11919 }
11920 }
11921 Binder.restoreCallingIdentity(origId);
11922 return foundParentInTask;
11923 }
11924 }
11925
Dianne Hackborn5320eb82012-05-18 12:05:04 -070011926 public int getLaunchedFromUid(IBinder activityToken) {
11927 ActivityRecord srec = ActivityRecord.forToken(activityToken);
11928 if (srec == null) {
11929 return -1;
11930 }
11931 return srec.launchedFromUid;
11932 }
11933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934 // =========================================================
11935 // LIFETIME MANAGEMENT
11936 // =========================================================
11937
Christopher Tatef46723b2012-01-26 14:19:24 -080011938 // Returns which broadcast queue the app is the current [or imminent] receiver
11939 // on, or 'null' if the app is not an active broadcast recipient.
11940 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
11941 BroadcastRecord r = app.curReceiver;
11942 if (r != null) {
11943 return r.queue;
11944 }
11945
11946 // It's not the current receiver, but it might be starting up to become one
11947 synchronized (this) {
11948 for (BroadcastQueue queue : mBroadcastQueues) {
11949 r = queue.mPendingBroadcast;
11950 if (r != null && r.curApp == app) {
11951 // found it; report which queue it's in
11952 return queue;
11953 }
11954 }
11955 }
11956
11957 return null;
11958 }
11959
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011960 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070011961 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011963 // This adjustment has already been computed. If we are calling
11964 // from the top, we may have already computed our adjustment with
11965 // an earlier hidden adjustment that isn't really for us... if
11966 // so, use the new hidden adjustment.
11967 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070011968 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011969 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011970 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971 }
11972
11973 if (app.thread == null) {
11974 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011975 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070011976 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 }
11978
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011979 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
11980 app.adjSource = null;
11981 app.adjTarget = null;
11982 app.empty = false;
11983 app.hidden = false;
11984
11985 final int activitiesSize = app.activities.size();
11986
Dianne Hackborn7d608422011-08-07 16:24:18 -070011987 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011988 // The max adjustment doesn't allow this app to be anything
11989 // below foreground, so it is not worth doing work for it.
11990 app.adjType = "fixed";
11991 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070011992 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011993 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070011994 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011995 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011996 // System process can do UI, and when they do we want to have
11997 // them trim their memory after the user leaves the UI. To
11998 // facilitate this, here we need to determine whether or not it
11999 // is currently showing UI.
12000 app.systemNoUi = true;
12001 if (app == TOP_APP) {
12002 app.systemNoUi = false;
12003 } else if (activitiesSize > 0) {
12004 for (int j = 0; j < activitiesSize; j++) {
12005 final ActivityRecord r = app.activities.get(j);
12006 if (r.visible) {
12007 app.systemNoUi = false;
12008 break;
12009 }
12010 }
12011 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012012 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012013 }
12014
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012015 app.keeping = false;
12016 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017
The Android Open Source Project4df24232009-03-05 14:34:35 -080012018 // Determine the importance of the process, starting with most
12019 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012021 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012022 boolean foregroundActivities = false;
12023 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012024 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012025 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012026 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012027 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012028 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012029 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012030 foregroundActivities = true;
12031 interesting = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012032 } else if (app.instrumentationClass != null) {
12033 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012034 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012035 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012036 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012037 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012038 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012040 // counts as being in the foreground for OOM killer purposes.
12041 // It's placed in a sched group based on the nature of the
12042 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012043 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012044 schedGroup = (queue == mFgBroadcastQueue)
12045 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012046 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 } else if (app.executingServices.size() > 0) {
12048 // An app that is currently executing a service callback also
12049 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012050 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012051 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012052 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012053 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012055 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012057 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012058 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012059 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012061 // A very not-needed process. If this is lower in the lru list,
12062 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012063 adj = hiddenAdj;
12064 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012065 app.hidden = true;
12066 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012067 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012069
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012070 boolean hasStoppingActivities = false;
12071
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012072 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012073 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012074 for (int j = 0; j < activitiesSize; j++) {
12075 final ActivityRecord r = app.activities.get(j);
12076 if (r.visible) {
12077 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012078 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12079 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012080 app.adjType = "visible";
12081 }
12082 schedGroup = Process.THREAD_GROUP_DEFAULT;
12083 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012084 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012085 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012086 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012087 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12088 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012089 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012090 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012091 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012092 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012093 } else if (r.state == ActivityState.STOPPING) {
12094 // We will apply the actual adjustment later, because
12095 // we want to allow this process to immediately go through
12096 // any memory trimming that is in effect.
12097 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012098 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012099 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012100 }
12101 }
12102 }
12103
Dianne Hackborn7d608422011-08-07 16:24:18 -070012104 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012105 if (app.foregroundServices) {
12106 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012107 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012108 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012109 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012110 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012111 } else if (app.forcingToForeground != null) {
12112 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012113 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012114 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012115 app.adjType = "force-foreground";
12116 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012117 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012118 }
12119 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012120
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012121 if (app.foregroundServices) {
12122 interesting = true;
12123 }
12124
Dianne Hackborn7d608422011-08-07 16:24:18 -070012125 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012126 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012127 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012128 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012129 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012130 app.adjType = "heavy";
12131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132
Dianne Hackborn7d608422011-08-07 16:24:18 -070012133 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012134 // This process is hosting what we currently consider to be the
12135 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012136 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012137 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012138 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012139 app.adjType = "home";
12140 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012141
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012142 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12143 && app.activities.size() > 0) {
12144 // This was the previous process that showed UI to the user.
12145 // We want to try to keep it around more aggressively, to give
12146 // a good experience around switching between two apps.
12147 adj = ProcessList.PREVIOUS_APP_ADJ;
12148 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12149 app.hidden = false;
12150 app.adjType = "previous";
12151 }
12152
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012153 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12154 + " reason=" + app.adjType);
12155
The Android Open Source Project4df24232009-03-05 14:34:35 -080012156 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012157 // there are applications dependent on our services or providers, but
12158 // this gives us a baseline and makes sure we don't get into an
12159 // infinite recursion.
12160 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012161 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162
Christopher Tate6fa95972009-06-05 18:43:55 -070012163 if (mBackupTarget != null && app == mBackupTarget.app) {
12164 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012165 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012166 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012167 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012168 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012169 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012170 }
12171 }
12172
Dianne Hackborn7d608422011-08-07 16:24:18 -070012173 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012174 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012175 final long now = SystemClock.uptimeMillis();
12176 // This process is more important if the top activity is
12177 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012178 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012179 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012180 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012182 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012183 // If this process has shown some UI, let it immediately
12184 // go to the LRU list because it may be pretty heavy with
12185 // UI stuff. We'll tag it with a label just to help
12186 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012187 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012188 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012190 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012191 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012192 // This service has seen some activity within
12193 // recent memory, so we will keep its process ahead
12194 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012195 if (adj > ProcessList.SERVICE_ADJ) {
12196 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012197 app.adjType = "started-services";
12198 app.hidden = false;
12199 }
12200 }
12201 // If we have let the service slide into the background
12202 // state, still have some text describing what it is doing
12203 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012204 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012205 app.adjType = "started-bg-services";
12206 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012207 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012208 // Don't kill this process because it is doing work; it
12209 // has said it is doing work.
12210 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012212 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012213 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012214 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012216 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012217 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012218 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012219 // XXX should compute this based on the max of
12220 // all connected clients.
12221 ConnectionRecord cr = clist.get(i);
12222 if (cr.binding.client == app) {
12223 // Binding to ourself is not interesting.
12224 continue;
12225 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012226 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012227 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012228 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012229 int myHiddenAdj = hiddenAdj;
12230 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012231 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012232 myHiddenAdj = client.hiddenAdj;
12233 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012234 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012235 }
12236 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012237 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012238 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012239 String adjType = null;
12240 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12241 // Not doing bind OOM management, so treat
12242 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012243 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012244 // If this process has shown some UI, let it immediately
12245 // go to the LRU list because it may be pretty heavy with
12246 // UI stuff. We'll tag it with a label just to help
12247 // debug and understand what is going on.
12248 if (adj > clientAdj) {
12249 adjType = "bound-bg-ui-services";
12250 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012251 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012252 clientAdj = adj;
12253 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012254 if (now >= (s.lastActivity
12255 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012256 // This service has not seen activity within
12257 // recent memory, so allow it to drop to the
12258 // LRU list if there is no other reason to keep
12259 // it around. We'll also tag it with a label just
12260 // to help debug and undertand what is going on.
12261 if (adj > clientAdj) {
12262 adjType = "bound-bg-services";
12263 }
12264 clientAdj = adj;
12265 }
12266 }
12267 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012268 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012269 // If this process has recently shown UI, and
12270 // the process that is binding to it is less
12271 // important than being visible, then we don't
12272 // care about the binding as much as we care
12273 // about letting this process get into the LRU
12274 // list to be killed and restarted if needed for
12275 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012276 if (app.hasShownUi && app != mHomeProcess
12277 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012278 adjType = "bound-bg-ui-services";
12279 } else {
12280 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12281 |Context.BIND_IMPORTANT)) != 0) {
12282 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012283 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12284 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12285 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12286 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12287 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012288 adj = clientAdj;
12289 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012290 app.pendingUiClean = true;
12291 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12292 adj = ProcessList.VISIBLE_APP_ADJ;
12293 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012294 }
12295 if (!client.hidden) {
12296 app.hidden = false;
12297 }
12298 if (client.keeping) {
12299 app.keeping = true;
12300 }
12301 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012302 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012303 }
12304 if (adjType != null) {
12305 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012306 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12307 .REASON_SERVICE_IN_USE;
12308 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012309 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012310 app.adjTarget = s.name;
12311 }
12312 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12313 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12314 schedGroup = Process.THREAD_GROUP_DEFAULT;
12315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012316 }
12317 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012318 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12319 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012320 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012321 (a.visible || a.state == ActivityState.RESUMED
12322 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012323 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012324 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12325 schedGroup = Process.THREAD_GROUP_DEFAULT;
12326 }
12327 app.hidden = false;
12328 app.adjType = "service";
12329 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12330 .REASON_SERVICE_IN_USE;
12331 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012332 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012333 app.adjTarget = s.name;
12334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 }
12337 }
12338 }
12339 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012340
Dianne Hackborn287952c2010-09-22 22:34:31 -070012341 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012342 // would like to avoid killing it unless it would prevent the current
12343 // application from running. By default we put the process in
12344 // with the rest of the background processes; as we scan through
12345 // its services we may bump it up from there.
12346 if (adj > hiddenAdj) {
12347 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012348 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012349 app.adjType = "bg-services";
12350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 }
12352
Dianne Hackborn7d608422011-08-07 16:24:18 -070012353 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012354 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012355 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012356 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012357 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012358 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012359 for (int i = cpr.connections.size()-1;
12360 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12361 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12362 i--) {
12363 ContentProviderConnection conn = cpr.connections.get(i);
12364 ProcessRecord client = conn.client;
12365 if (client == app) {
12366 // Being our own client is not interesting.
12367 continue;
12368 }
12369 int myHiddenAdj = hiddenAdj;
12370 if (myHiddenAdj > client.hiddenAdj) {
12371 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12372 myHiddenAdj = client.hiddenAdj;
12373 } else {
12374 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012375 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012376 }
12377 int clientAdj = computeOomAdjLocked(
12378 client, myHiddenAdj, TOP_APP, true, doingAll);
12379 if (adj > clientAdj) {
12380 if (app.hasShownUi && app != mHomeProcess
12381 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12382 app.adjType = "bg-ui-provider";
12383 } else {
12384 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12385 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12386 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012388 if (!client.hidden) {
12389 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012391 if (client.keeping) {
12392 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012393 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012394 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12395 .REASON_PROVIDER_IN_USE;
12396 app.adjSource = client;
12397 app.adjSourceOom = clientAdj;
12398 app.adjTarget = cpr.name;
12399 }
12400 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12401 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 }
12403 }
12404 // If the provider has external (non-framework) process
12405 // dependencies, ensure that its adjustment is at least
12406 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012407 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012408 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12409 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012410 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012411 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012412 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012413 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012414 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415 }
12416 }
12417 }
12418 }
12419
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012420 if (adj == ProcessList.SERVICE_ADJ) {
12421 if (doingAll) {
12422 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12423 mNewNumServiceProcs++;
12424 }
12425 if (app.serviceb) {
12426 adj = ProcessList.SERVICE_B_ADJ;
12427 }
12428 } else {
12429 app.serviceb = false;
12430 }
12431
12432 app.nonStoppingAdj = adj;
12433
12434 if (hasStoppingActivities) {
12435 // Only upgrade adjustment.
12436 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12437 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12438 app.adjType = "stopping";
12439 }
12440 }
12441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 app.curRawAdj = adj;
12443
Joe Onorato8a9b2202010-02-26 18:56:32 -080012444 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12446 if (adj > app.maxAdj) {
12447 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012448 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012449 schedGroup = Process.THREAD_GROUP_DEFAULT;
12450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012452 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012453 app.keeping = true;
12454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012456 if (app.hasAboveClient) {
12457 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12458 // then we need to drop its adjustment to be lower than the service's
12459 // in order to honor the request. We want to drop it by one adjustment
12460 // level... but there is special meaning applied to various levels so
12461 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012462 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012463 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012464 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12465 adj = ProcessList.VISIBLE_APP_ADJ;
12466 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12467 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12468 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12469 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012470 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012471 adj++;
12472 }
12473 }
12474
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012475 int importance = app.memImportance;
12476 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12477 app.curAdj = adj;
12478 app.curSchedGroup = schedGroup;
12479 if (!interesting) {
12480 // For this reporting, if there is not something explicitly
12481 // interesting in this process then we will push it to the
12482 // background importance.
12483 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12484 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12485 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12486 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12487 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12488 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12489 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12490 } else if (adj >= ProcessList.SERVICE_ADJ) {
12491 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12492 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12493 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12494 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12495 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12496 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12497 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12498 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12499 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12500 } else {
12501 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12502 }
12503 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012504
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012505 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12506 if (foregroundActivities != app.foregroundActivities) {
12507 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12508 }
12509 if (changes != 0) {
12510 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12511 app.memImportance = importance;
12512 app.foregroundActivities = foregroundActivities;
12513 int i = mPendingProcessChanges.size()-1;
12514 ProcessChangeItem item = null;
12515 while (i >= 0) {
12516 item = mPendingProcessChanges.get(i);
12517 if (item.pid == app.pid) {
12518 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12519 break;
12520 }
12521 i--;
12522 }
12523 if (i < 0) {
12524 // No existing item in pending changes; need a new one.
12525 final int NA = mAvailProcessChanges.size();
12526 if (NA > 0) {
12527 item = mAvailProcessChanges.remove(NA-1);
12528 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12529 } else {
12530 item = new ProcessChangeItem();
12531 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12532 }
12533 item.changes = 0;
12534 item.pid = app.pid;
12535 item.uid = app.info.uid;
12536 if (mPendingProcessChanges.size() == 0) {
12537 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12538 "*** Enqueueing dispatch processes changed!");
12539 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12540 }
12541 mPendingProcessChanges.add(item);
12542 }
12543 item.changes |= changes;
12544 item.importance = importance;
12545 item.foregroundActivities = foregroundActivities;
12546 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12547 + Integer.toHexString(System.identityHashCode(item))
12548 + " " + app.toShortString() + ": changes=" + item.changes
12549 + " importance=" + item.importance
12550 + " foreground=" + item.foregroundActivities
12551 + " type=" + app.adjType + " source=" + app.adjSource
12552 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012553 }
12554
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012555 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556 }
12557
12558 /**
12559 * Ask a given process to GC right now.
12560 */
12561 final void performAppGcLocked(ProcessRecord app) {
12562 try {
12563 app.lastRequestedGc = SystemClock.uptimeMillis();
12564 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012565 if (app.reportLowMemory) {
12566 app.reportLowMemory = false;
12567 app.thread.scheduleLowMemory();
12568 } else {
12569 app.thread.processInBackground();
12570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 }
12572 } catch (Exception e) {
12573 // whatever.
12574 }
12575 }
12576
12577 /**
12578 * Returns true if things are idle enough to perform GCs.
12579 */
Josh Bartel7f208742010-02-25 11:01:44 -060012580 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012581 boolean processingBroadcasts = false;
12582 for (BroadcastQueue q : mBroadcastQueues) {
12583 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12584 processingBroadcasts = true;
12585 }
12586 }
12587 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012588 && (mSleeping || (mMainStack.mResumedActivity != null &&
12589 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012590 }
12591
12592 /**
12593 * Perform GCs on all processes that are waiting for it, but only
12594 * if things are idle.
12595 */
12596 final void performAppGcsLocked() {
12597 final int N = mProcessesToGc.size();
12598 if (N <= 0) {
12599 return;
12600 }
Josh Bartel7f208742010-02-25 11:01:44 -060012601 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602 while (mProcessesToGc.size() > 0) {
12603 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012604 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012605 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12606 <= SystemClock.uptimeMillis()) {
12607 // To avoid spamming the system, we will GC processes one
12608 // at a time, waiting a few seconds between each.
12609 performAppGcLocked(proc);
12610 scheduleAppGcsLocked();
12611 return;
12612 } else {
12613 // It hasn't been long enough since we last GCed this
12614 // process... put it in the list to wait for its time.
12615 addProcessToGcListLocked(proc);
12616 break;
12617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 }
12619 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012620
12621 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012622 }
12623 }
12624
12625 /**
12626 * If all looks good, perform GCs on all processes waiting for them.
12627 */
12628 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012629 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 performAppGcsLocked();
12631 return;
12632 }
12633 // Still not idle, wait some more.
12634 scheduleAppGcsLocked();
12635 }
12636
12637 /**
12638 * Schedule the execution of all pending app GCs.
12639 */
12640 final void scheduleAppGcsLocked() {
12641 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012642
12643 if (mProcessesToGc.size() > 0) {
12644 // Schedule a GC for the time to the next process.
12645 ProcessRecord proc = mProcessesToGc.get(0);
12646 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12647
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012648 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012649 long now = SystemClock.uptimeMillis();
12650 if (when < (now+GC_TIMEOUT)) {
12651 when = now + GC_TIMEOUT;
12652 }
12653 mHandler.sendMessageAtTime(msg, when);
12654 }
12655 }
12656
12657 /**
12658 * Add a process to the array of processes waiting to be GCed. Keeps the
12659 * list in sorted order by the last GC time. The process can't already be
12660 * on the list.
12661 */
12662 final void addProcessToGcListLocked(ProcessRecord proc) {
12663 boolean added = false;
12664 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12665 if (mProcessesToGc.get(i).lastRequestedGc <
12666 proc.lastRequestedGc) {
12667 added = true;
12668 mProcessesToGc.add(i+1, proc);
12669 break;
12670 }
12671 }
12672 if (!added) {
12673 mProcessesToGc.add(0, proc);
12674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012675 }
12676
12677 /**
12678 * Set up to ask a process to GC itself. This will either do it
12679 * immediately, or put it on the list of processes to gc the next
12680 * time things are idle.
12681 */
12682 final void scheduleAppGcLocked(ProcessRecord app) {
12683 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012684 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012685 return;
12686 }
12687 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012688 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012689 scheduleAppGcsLocked();
12690 }
12691 }
12692
Dianne Hackborn287952c2010-09-22 22:34:31 -070012693 final void checkExcessivePowerUsageLocked(boolean doKills) {
12694 updateCpuStatsNow();
12695
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012696 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012697 boolean doWakeKills = doKills;
12698 boolean doCpuKills = doKills;
12699 if (mLastPowerCheckRealtime == 0) {
12700 doWakeKills = false;
12701 }
12702 if (mLastPowerCheckUptime == 0) {
12703 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012704 }
12705 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012706 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012707 }
12708 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012709 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12710 final long curUptime = SystemClock.uptimeMillis();
12711 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12712 mLastPowerCheckRealtime = curRealtime;
12713 mLastPowerCheckUptime = curUptime;
12714 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12715 doWakeKills = false;
12716 }
12717 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12718 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012719 }
12720 int i = mLruProcesses.size();
12721 while (i > 0) {
12722 i--;
12723 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012724 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012725 long wtime;
12726 synchronized (stats) {
12727 wtime = stats.getProcessWakeTime(app.info.uid,
12728 app.pid, curRealtime);
12729 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012730 long wtimeUsed = wtime - app.lastWakeTime;
12731 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12732 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012733 StringBuilder sb = new StringBuilder(128);
12734 sb.append("Wake for ");
12735 app.toShortString(sb);
12736 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012737 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012738 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012739 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012740 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012741 sb.append((wtimeUsed*100)/realtimeSince);
12742 sb.append("%)");
12743 Slog.i(TAG, sb.toString());
12744 sb.setLength(0);
12745 sb.append("CPU for ");
12746 app.toShortString(sb);
12747 sb.append(": over ");
12748 TimeUtils.formatDuration(uptimeSince, sb);
12749 sb.append(" used ");
12750 TimeUtils.formatDuration(cputimeUsed, sb);
12751 sb.append(" (");
12752 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012753 sb.append("%)");
12754 Slog.i(TAG, sb.toString());
12755 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012756 // If a process has held a wake lock for more
12757 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012758 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012759 if (doWakeKills && realtimeSince > 0
12760 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12761 synchronized (stats) {
12762 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12763 realtimeSince, wtimeUsed);
12764 }
12765 Slog.w(TAG, "Excessive wake lock in " + app.processName
12766 + " (pid " + app.pid + "): held " + wtimeUsed
12767 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012768 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12769 app.processName, app.setAdj, "excessive wake lock");
12770 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012771 } else if (doCpuKills && uptimeSince > 0
12772 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12773 synchronized (stats) {
12774 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12775 uptimeSince, cputimeUsed);
12776 }
12777 Slog.w(TAG, "Excessive CPU in " + app.processName
12778 + " (pid " + app.pid + "): used " + cputimeUsed
12779 + " during " + uptimeSince);
12780 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12781 app.processName, app.setAdj, "excessive cpu");
12782 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012783 } else {
12784 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012785 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012786 }
12787 }
12788 }
12789 }
12790
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012791 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012792 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012793 app.hiddenAdj = hiddenAdj;
12794
12795 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012796 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012797 }
12798
Dianne Hackborn287952c2010-09-22 22:34:31 -070012799 final boolean wasKeeping = app.keeping;
12800
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012801 boolean success = true;
12802
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012803 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804
Jeff Brown10e89712011-07-08 18:52:57 -070012805 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070012806 if (wasKeeping && !app.keeping) {
12807 // This app is no longer something we want to keep. Note
12808 // its current wake lock time to later know to kill it if
12809 // it is not behaving well.
12810 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12811 synchronized (stats) {
12812 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12813 app.pid, SystemClock.elapsedRealtime());
12814 }
12815 app.lastCpuTime = app.curCpuTime;
12816 }
12817
12818 app.setRawAdj = app.curRawAdj;
12819 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012820
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012821 if (app.curAdj != app.setAdj) {
12822 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080012823 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012824 TAG, "Set " + app.pid + " " + app.processName +
12825 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012826 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070012827 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012828 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012829 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070012830 }
12831 }
12832 if (app.setSchedGroup != app.curSchedGroup) {
12833 app.setSchedGroup = app.curSchedGroup;
12834 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
12835 "Setting process group of " + app.processName
12836 + " to " + app.curSchedGroup);
12837 if (app.waitingToKill != null &&
12838 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
12839 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
12840 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12841 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070012842 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070012843 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012844 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070012845 } else {
12846 if (true) {
12847 long oldId = Binder.clearCallingIdentity();
12848 try {
12849 Process.setProcessGroup(app.pid, app.curSchedGroup);
12850 } catch (Exception e) {
12851 Slog.w(TAG, "Failed setting process group of " + app.pid
12852 + " to " + app.curSchedGroup);
12853 e.printStackTrace();
12854 } finally {
12855 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012856 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012857 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070012858 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012859 try {
Jeff Brown10e89712011-07-08 18:52:57 -070012860 app.thread.setSchedulingGroup(app.curSchedGroup);
12861 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012862 }
12863 }
12864 }
12865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012867 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 }
12869
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012870 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012871 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080012873 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012875 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 }
12877 }
12878 return resumedActivity;
12879 }
12880
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012881 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012882 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012883 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12884 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012885 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12886 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887
12888 mAdjSeq++;
12889
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012890 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012891 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12892 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012893 if (nowHidden != wasHidden) {
12894 // Changed to/from hidden state, so apps after it in the LRU
12895 // list may also be changed.
12896 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012898 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899 }
12900
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012901 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012902 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12904
12905 if (false) {
12906 RuntimeException e = new RuntimeException();
12907 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012908 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 }
12910
12911 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012912 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012914 // Let's determine how many processes we have running vs.
12915 // how many slots we have for background processes; we may want
12916 // to put multiple processes in a slot of there are enough of
12917 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012918 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012919 int factor = (mLruProcesses.size()-4)/numSlots;
12920 if (factor < 1) factor = 1;
12921 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012922 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012923 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012924
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012925 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012926 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012927 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012928 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 while (i > 0) {
12930 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012931 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012932 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012933 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
12934 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012935 && app.curAdj == curHiddenAdj) {
12936 step++;
12937 if (step >= factor) {
12938 step = 0;
12939 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012941 }
12942 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012944 numHidden++;
12945 if (numHidden > mProcessLimit) {
12946 Slog.i(TAG, "No longer want " + app.processName
12947 + " (pid " + app.pid + "): hidden #" + numHidden);
12948 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12949 app.processName, app.setAdj, "too many background");
12950 app.killedBackground = true;
12951 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070012952 }
12953 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012954 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
12955 // If this is an isolated process, and there are no
12956 // services running in it, then the process is no longer
12957 // needed. We agressively kill these because we can by
12958 // definition not re-use the same process again, and it is
12959 // good to avoid having whatever code was running in them
12960 // left sitting around after no longer needed.
12961 Slog.i(TAG, "Isolated process " + app.processName
12962 + " (pid " + app.pid + ") no longer needed");
12963 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12964 app.processName, app.setAdj, "isolated not needed");
12965 app.killedBackground = true;
12966 Process.killProcessQuiet(app.pid);
12967 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012968 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
12969 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
12970 && !app.killedBackground) {
12971 numTrimming++;
12972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 }
12974 }
12975
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012976 mNumServiceProcs = mNewNumServiceProcs;
12977
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012978 // Now determine the memory trimming level of background processes.
12979 // Unfortunately we need to start at the back of the list to do this
12980 // properly. We only do this if the number of background apps we
12981 // are managing to keep around is less than half the maximum we desire;
12982 // if we are keeping a good number around, we'll let them use whatever
12983 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012984 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012985 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012986 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080012987 int minFactor = 2;
12988 if (mHomeProcess != null) minFactor++;
12989 if (mPreviousProcess != null) minFactor++;
12990 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012991 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080012992 int fgTrimLevel;
12993 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
12994 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
12995 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
12996 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
12997 } else {
12998 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
12999 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013000 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013001 for (i=0; i<N; i++) {
13002 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013003 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13004 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013005 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013006 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13007 try {
13008 app.thread.scheduleTrimMemory(curLevel);
13009 } catch (RemoteException e) {
13010 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013011 if (false) {
13012 // For now we won't do this; our memory trimming seems
13013 // to be good enough at this point that destroying
13014 // activities causes more harm than good.
13015 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13016 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013017 // Need to do this on its own message because the stack may not
13018 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013019 // For these apps we will also finish their activities
13020 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013021 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013022 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013023 }
13024 }
13025 app.trimMemoryLevel = curLevel;
13026 step++;
13027 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013028 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013029 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013030 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13031 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013032 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013033 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13034 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013035 break;
13036 }
13037 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013038 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013039 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013040 && app.thread != null) {
13041 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013042 app.thread.scheduleTrimMemory(
13043 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013044 } catch (RemoteException e) {
13045 }
13046 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013047 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013048 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013049 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013050 && app.pendingUiClean) {
13051 // If this application is now in the background and it
13052 // had done UI, then give it the special trim level to
13053 // have it free UI resources.
13054 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13055 if (app.trimMemoryLevel < level && app.thread != null) {
13056 try {
13057 app.thread.scheduleTrimMemory(level);
13058 } catch (RemoteException e) {
13059 }
13060 }
13061 app.pendingUiClean = false;
13062 }
13063 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013064 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013065 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013066 } catch (RemoteException e) {
13067 }
13068 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013069 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013070 }
13071 }
13072 } else {
13073 final int N = mLruProcesses.size();
13074 for (i=0; i<N; i++) {
13075 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013076 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013077 && app.pendingUiClean) {
13078 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13079 && app.thread != null) {
13080 try {
13081 app.thread.scheduleTrimMemory(
13082 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13083 } catch (RemoteException e) {
13084 }
13085 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013086 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013087 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013088 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013089 }
13090 }
13091
13092 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013093 // Need to do this on its own message because the stack may not
13094 // be in a consistent state at this point.
13095 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013097 }
13098
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013099 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100 synchronized (this) {
13101 int i;
13102
13103 // First remove any unused application processes whose package
13104 // has been removed.
13105 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13106 final ProcessRecord app = mRemovedProcesses.get(i);
13107 if (app.activities.size() == 0
13108 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013109 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 TAG, "Exiting empty application process "
13111 + app.processName + " ("
13112 + (app.thread != null ? app.thread.asBinder() : null)
13113 + ")\n");
13114 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013115 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13116 app.processName, app.setAdj, "empty");
13117 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 } else {
13119 try {
13120 app.thread.scheduleExit();
13121 } catch (Exception e) {
13122 // Ignore exceptions.
13123 }
13124 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013125 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013126 mRemovedProcesses.remove(i);
13127
13128 if (app.persistent) {
13129 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013130 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013131 }
13132 }
13133 }
13134 }
13135
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013136 // Now update the oom adj for all processes.
13137 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013138 }
13139 }
13140
13141 /** This method sends the specified signal to each of the persistent apps */
13142 public void signalPersistentProcesses(int sig) throws RemoteException {
13143 if (sig != Process.SIGNAL_USR1) {
13144 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13145 }
13146
13147 synchronized (this) {
13148 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13149 != PackageManager.PERMISSION_GRANTED) {
13150 throw new SecurityException("Requires permission "
13151 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13152 }
13153
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013154 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13155 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013156 if (r.thread != null && r.persistent) {
13157 Process.sendSignal(r.pid, sig);
13158 }
13159 }
13160 }
13161 }
13162
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013163 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13164 if (proc == null || proc == mProfileProc) {
13165 proc = mProfileProc;
13166 path = mProfileFile;
13167 profileType = mProfileType;
13168 clearProfilerLocked();
13169 }
13170 if (proc == null) {
13171 return;
13172 }
13173 try {
13174 proc.thread.profilerControl(false, path, null, profileType);
13175 } catch (RemoteException e) {
13176 throw new IllegalStateException("Process disappeared");
13177 }
13178 }
13179
13180 private void clearProfilerLocked() {
13181 if (mProfileFd != null) {
13182 try {
13183 mProfileFd.close();
13184 } catch (IOException e) {
13185 }
13186 }
13187 mProfileApp = null;
13188 mProfileProc = null;
13189 mProfileFile = null;
13190 mProfileType = 0;
13191 mAutoStopProfiler = false;
13192 }
13193
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013194 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013195 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013196
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013197 try {
13198 synchronized (this) {
13199 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13200 // its own permission.
13201 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13202 != PackageManager.PERMISSION_GRANTED) {
13203 throw new SecurityException("Requires permission "
13204 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013205 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013206
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013207 if (start && fd == null) {
13208 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013209 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013210
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013211 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013212 if (process != null) {
13213 try {
13214 int pid = Integer.parseInt(process);
13215 synchronized (mPidsSelfLocked) {
13216 proc = mPidsSelfLocked.get(pid);
13217 }
13218 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013219 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013220
13221 if (proc == null) {
13222 HashMap<String, SparseArray<ProcessRecord>> all
13223 = mProcessNames.getMap();
13224 SparseArray<ProcessRecord> procs = all.get(process);
13225 if (procs != null && procs.size() > 0) {
13226 proc = procs.valueAt(0);
13227 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013228 }
13229 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013230
13231 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013232 throw new IllegalArgumentException("Unknown process: " + process);
13233 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013234
13235 if (start) {
13236 stopProfilerLocked(null, null, 0);
13237 setProfileApp(proc.info, proc.processName, path, fd, false);
13238 mProfileProc = proc;
13239 mProfileType = profileType;
13240 try {
13241 fd = fd.dup();
13242 } catch (IOException e) {
13243 fd = null;
13244 }
13245 proc.thread.profilerControl(start, path, fd, profileType);
13246 fd = null;
13247 mProfileFd = null;
13248 } else {
13249 stopProfilerLocked(proc, path, profileType);
13250 if (fd != null) {
13251 try {
13252 fd.close();
13253 } catch (IOException e) {
13254 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013255 }
13256 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013257
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013258 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013259 }
13260 } catch (RemoteException e) {
13261 throw new IllegalStateException("Process disappeared");
13262 } finally {
13263 if (fd != null) {
13264 try {
13265 fd.close();
13266 } catch (IOException e) {
13267 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013268 }
13269 }
13270 }
Andy McFadden824c5102010-07-09 16:26:57 -070013271
13272 public boolean dumpHeap(String process, boolean managed,
13273 String path, ParcelFileDescriptor fd) throws RemoteException {
13274
13275 try {
13276 synchronized (this) {
13277 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13278 // its own permission (same as profileControl).
13279 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13280 != PackageManager.PERMISSION_GRANTED) {
13281 throw new SecurityException("Requires permission "
13282 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13283 }
13284
13285 if (fd == null) {
13286 throw new IllegalArgumentException("null fd");
13287 }
13288
13289 ProcessRecord proc = null;
13290 try {
13291 int pid = Integer.parseInt(process);
13292 synchronized (mPidsSelfLocked) {
13293 proc = mPidsSelfLocked.get(pid);
13294 }
13295 } catch (NumberFormatException e) {
13296 }
13297
13298 if (proc == null) {
13299 HashMap<String, SparseArray<ProcessRecord>> all
13300 = mProcessNames.getMap();
13301 SparseArray<ProcessRecord> procs = all.get(process);
13302 if (procs != null && procs.size() > 0) {
13303 proc = procs.valueAt(0);
13304 }
13305 }
13306
13307 if (proc == null || proc.thread == null) {
13308 throw new IllegalArgumentException("Unknown process: " + process);
13309 }
13310
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013311 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13312 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013313 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13314 throw new SecurityException("Process not debuggable: " + proc);
13315 }
13316 }
13317
13318 proc.thread.dumpHeap(managed, path, fd);
13319 fd = null;
13320 return true;
13321 }
13322 } catch (RemoteException e) {
13323 throw new IllegalStateException("Process disappeared");
13324 } finally {
13325 if (fd != null) {
13326 try {
13327 fd.close();
13328 } catch (IOException e) {
13329 }
13330 }
13331 }
13332 }
13333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013334 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13335 public void monitor() {
13336 synchronized (this) { }
13337 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013338
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013339 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013340 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13341 ProcessRecord processRecord = mLruProcesses.get(i);
13342 try {
13343 if (processRecord.thread != null) {
13344 processRecord.thread.setCoreSettings(settings);
13345 }
13346 } catch (RemoteException re) {
13347 /* ignore */
13348 }
13349 }
13350 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013351
13352 // Multi-user methods
13353
Amith Yamasani742a6712011-05-04 14:49:28 -070013354 private int mCurrentUserId;
13355 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
13356
13357 public boolean switchUser(int userId) {
13358 final int callingUid = Binder.getCallingUid();
13359 if (callingUid != 0 && callingUid != Process.myUid()) {
13360 Slog.e(TAG, "Trying to switch user from unauthorized app");
13361 return false;
13362 }
13363 if (mCurrentUserId == userId)
13364 return true;
13365
13366 synchronized (this) {
13367 // Check if user is already logged in, otherwise check if user exists first before
13368 // adding to the list of logged in users.
13369 if (mLoggedInUsers.indexOfKey(userId) < 0) {
13370 if (!userExists(userId)) {
13371 return false;
13372 }
13373 mLoggedInUsers.append(userId, userId);
13374 }
13375
13376 mCurrentUserId = userId;
13377 boolean haveActivities = mMainStack.switchUser(userId);
13378 if (!haveActivities) {
13379 startHomeActivityLocked(userId);
13380 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013381
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013382 }
Amith Yamasani13593602012-03-22 16:16:17 -070013383
13384 // Inform of user switch
13385 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13386 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
13387 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
13388
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013389 return true;
13390 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013391
Amith Yamasani52f1d752012-03-28 18:19:29 -070013392 @Override
13393 public UserInfo getCurrentUser() throws RemoteException {
13394 final int callingUid = Binder.getCallingUid();
13395 if (callingUid != 0 && callingUid != Process.myUid()) {
13396 Slog.e(TAG, "Trying to get user from unauthorized app");
13397 return null;
13398 }
13399 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
13400 }
13401
Amith Yamasani13593602012-03-22 16:16:17 -070013402 private void onUserRemoved(Intent intent) {
13403 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
13404 if (extraUserId < 1) return;
13405
13406 // Kill all the processes for the user
13407 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
13408 synchronized (this) {
13409 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
13410 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
13411 SparseArray<ProcessRecord> uids = uidMap.getValue();
13412 for (int i = 0; i < uids.size(); i++) {
13413 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
13414 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
13415 }
13416 }
13417 }
13418
13419 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
13420 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
13421 false, false, true, true, extraUserId);
13422 }
13423 }
13424 }
13425
Amith Yamasani742a6712011-05-04 14:49:28 -070013426 private boolean userExists(int userId) {
13427 try {
Amith Yamasani13593602012-03-22 16:16:17 -070013428 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
13429 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013430 } catch (RemoteException re) {
13431 // Won't happen, in same process
13432 }
13433
13434 return false;
13435 }
13436
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013437 private void checkValidCaller(int uid, int userId) {
13438 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
13439
13440 throw new SecurityException("Caller uid=" + uid
13441 + " is not privileged to communicate with user=" + userId);
13442 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013443
13444 private int applyUserId(int uid, int userId) {
13445 return UserId.getUid(userId, uid);
13446 }
13447
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013448 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013449 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013450 ApplicationInfo newInfo = new ApplicationInfo(info);
13451 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013452 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13453 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013454 return newInfo;
13455 }
13456
13457 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013458 if (aInfo == null
13459 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013460 return aInfo;
13461 }
13462
13463 ActivityInfo info = new ActivityInfo(aInfo);
13464 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13465 return info;
13466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013467}