blob: 86f4bc080894def0a12a9347845f8f570844e2a2 [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;
37import android.app.ActivityThread;
38import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070039import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020040import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070042import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.IApplicationThread;
44import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070045import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070046import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IServiceConnection;
48import android.app.IThumbnailReceiver;
49import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070050import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070053import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080054import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020055import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080056import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080057import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070058import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070060import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ContentResolver;
62import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020063import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.Intent;
65import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070068import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.pm.ActivityInfo;
70import android.content.pm.ApplicationInfo;
71import android.content.pm.ConfigurationInfo;
72import android.content.pm.IPackageDataObserver;
73import android.content.pm.IPackageManager;
74import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080075import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070077import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ProviderInfo;
79import android.content.pm.ResolveInfo;
80import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070081import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070082import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040083import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.res.Configuration;
85import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070086import android.net.Proxy;
87import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.Uri;
89import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080090import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080091import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070092import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080093import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080095import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.FileUtils;
97import android.os.Handler;
98import android.os.IBinder;
99import android.os.IPermissionController;
100import android.os.Looper;
101import android.os.Message;
102import android.os.Parcel;
103import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700105import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.RemoteException;
107import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700108import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.SystemClock;
110import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700111import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700114import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800115import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.util.PrintWriterPrinter;
118import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700119import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700120import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.view.Gravity;
122import android.view.LayoutInflater;
123import android.view.View;
124import android.view.WindowManager;
125import android.view.WindowManagerPolicy;
126
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700127import java.io.BufferedInputStream;
128import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700129import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.DataInputStream;
131import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.File;
133import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200137import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800138import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700140import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.lang.IllegalStateException;
142import java.lang.ref.WeakReference;
143import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700144import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700145import java.util.Collections;
146import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.util.HashMap;
148import java.util.HashSet;
149import java.util.Iterator;
150import java.util.List;
151import java.util.Locale;
152import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700153import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700154import java.util.concurrent.atomic.AtomicBoolean;
155import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700157public final class ActivityManagerService extends ActivityManagerNative
158 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700159 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400163 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG_SWITCH = localLOGV || false;
165 static final boolean DEBUG_TASKS = localLOGV || false;
166 static final boolean DEBUG_PAUSE = localLOGV || false;
167 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
168 static final boolean DEBUG_TRANSITION = localLOGV || false;
169 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800170 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700171 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700173 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_VISBILITY = localLOGV || false;
175 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700176 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800177 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700179 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700180 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700181 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_POWER = localLOGV || false;
183 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700184 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean VALIDATE_TOKENS = false;
186 static final boolean SHOW_ACTIVITY_START_TIME = true;
187
188 // Control over CPU and battery monitoring.
189 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
190 static final boolean MONITOR_CPU_USAGE = true;
191 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
192 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
193 static final boolean MONITOR_THREAD_CPU_USAGE = false;
194
Dianne Hackborn1655be42009-05-08 14:29:01 -0700195 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700196 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800198 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // Maximum number of recent tasks that we can remember.
201 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700202
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700203 // Amount of time after a call to stopAppSwitches() during which we will
204 // prevent further untrusted switches from happening.
205 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
207 // How long we wait for a launched process to attach to the activity manager
208 // before we decide it's never going to come up for real.
209 static final int PROC_START_TIMEOUT = 10*1000;
210
Jeff Brown3f9dd282011-07-08 20:02:19 -0700211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real, when the process was
213 // started with a wrapper for instrumentation (such as Valgrind) because it
214 // could take much longer than usual.
215 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // How long to wait after going idle before forcing apps to GC.
218 static final int GC_TIMEOUT = 5*1000;
219
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700220 // The minimum amount of time between successive GC requests for a process.
221 static final int GC_MIN_INTERVAL = 60*1000;
222
Dianne Hackborn287952c2010-09-22 22:34:31 -0700223 // The rate at which we check for apps using excessive power -- 15 mins.
224 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
225
226 // The minimum sample duration we will allow before deciding we have
227 // enough data on wake locks to start killing things.
228 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on CPU usage to start killing things.
232 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800235 static final int BROADCAST_FG_TIMEOUT = 10*1000;
236 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // How long we wait for a service to finish executing.
239 static final int SERVICE_TIMEOUT = 20*1000;
240
241 // How long a service needs to be running until restarting its process
242 // is no longer considered to be a relaunch of the service.
243 static final int SERVICE_RESTART_DURATION = 5*1000;
244
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700245 // How long a service needs to be running until it will start back at
246 // SERVICE_RESTART_DURATION after being killed.
247 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
248
249 // Multiplying factor to increase restart duration time by, for each time
250 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
251 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
252
253 // The minimum amount of time between restarting services that we allow.
254 // That is, when multiple services are restarting, we won't allow each
255 // to restart less than this amount of time from the last one.
256 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // Maximum amount of time for there to be no activity on a service before
259 // we consider it non-essential and allow its process to go on the
260 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700261 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // How long we wait until we timeout on key dispatching.
264 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 // How long we wait until we timeout on key dispatching during instrumentation.
267 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
268
Dan Egnor42471dd2010-01-07 17:25:22 -0800269 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270
271 static final String[] EMPTY_STRING_ARRAY = new String[0];
272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700273 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700274
275 private final boolean mHeadless;
276
Joe Onorato54a4a412011-11-02 20:50:08 -0700277 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
278 // default actuion automatically. Important for devices without direct input
279 // devices.
280 private boolean mShowDialogs = true;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700283 * Description of a request to start a new activity, which has been held
284 * due to app switches being disabled.
285 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700286 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 ActivityRecord r;
288 ActivityRecord sourceRecord;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700289 Uri[] grantedUriPermissions;
290 int grantedMode;
291 boolean onlyIfNeeded;
292 }
293
294 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
295 = new ArrayList<PendingActivityLaunch>();
296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800298 BroadcastQueue mFgBroadcastQueue;
299 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800300 // Convenient for easy iteration over the queues. Foreground is first
301 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800302 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800303
304 BroadcastQueue broadcastQueueForIntent(Intent intent) {
305 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
306 if (DEBUG_BACKGROUND_BROADCAST) {
307 Slog.i(TAG, "Broadcast intent " + intent + " on "
308 + (isFg ? "foreground" : "background")
309 + " queue");
310 }
311 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
312 }
313
314 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
315 for (BroadcastQueue queue : mBroadcastQueues) {
316 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
317 if (r != null) {
318 return r;
319 }
320 }
321 return null;
322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
324 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * Activity we have told the window manager to have key focus.
326 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700327 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * List of intents that were used to start the most recent tasks.
330 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700331 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332
333 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700334 * Process management.
335 */
336 final ProcessList mProcessList = new ProcessList();
337
338 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 * All of the applications we currently have running organized by name.
340 * The keys are strings of the application package name (as
341 * returned by the package manager), and the keys are ApplicationRecord
342 * objects.
343 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700344 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345
346 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800347 * The currently running isolated processes.
348 */
349 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
350
351 /**
352 * Counter for assigning isolated process uids, to avoid frequently reusing the
353 * same ones.
354 */
355 int mNextIsolatedProcessUid = 0;
356
357 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700358 * The currently running heavy-weight process, if any.
359 */
360 ProcessRecord mHeavyWeightProcess = null;
361
362 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 * The last time that various processes have crashed.
364 */
365 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
366
367 /**
368 * Set of applications that we consider to be bad, and will reject
369 * incoming broadcasts from (which the user has no control over).
370 * Processes are added to this set when they have crashed twice within
371 * a minimum amount of time; they are removed from it when they are
372 * later restarted (hopefully due to some user action). The value is the
373 * time it was added to the list.
374 */
375 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
376
377 /**
378 * All of the processes we currently have running organized by pid.
379 * The keys are the pid running the application.
380 *
381 * <p>NOTE: This object is protected by its own lock, NOT the global
382 * activity manager lock!
383 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700384 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385
386 /**
387 * All of the processes that have been forced to be foreground. The key
388 * is the pid of the caller who requested it (we hold a death
389 * link on it).
390 */
391 abstract class ForegroundToken implements IBinder.DeathRecipient {
392 int pid;
393 IBinder token;
394 }
395 final SparseArray<ForegroundToken> mForegroundProcesses
396 = new SparseArray<ForegroundToken>();
397
398 /**
399 * List of records for processes that someone had tried to start before the
400 * system was ready. We don't start them at that point, but ensure they
401 * are started by the time booting is complete.
402 */
403 final ArrayList<ProcessRecord> mProcessesOnHold
404 = new ArrayList<ProcessRecord>();
405
406 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 * List of persistent applications that are in the process
408 * of being started.
409 */
410 final ArrayList<ProcessRecord> mPersistentStartingProcesses
411 = new ArrayList<ProcessRecord>();
412
413 /**
414 * Processes that are being forcibly torn down.
415 */
416 final ArrayList<ProcessRecord> mRemovedProcesses
417 = new ArrayList<ProcessRecord>();
418
419 /**
420 * List of running applications, sorted by recent usage.
421 * The first entry in the list is the least recently used.
422 * It contains ApplicationRecord objects. This list does NOT include
423 * any persistent application records (since we never want to exit them).
424 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800425 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 = new ArrayList<ProcessRecord>();
427
428 /**
429 * List of processes that should gc as soon as things are idle.
430 */
431 final ArrayList<ProcessRecord> mProcessesToGc
432 = new ArrayList<ProcessRecord>();
433
434 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800435 * This is the process holding what we currently consider to be
436 * the "home" activity.
437 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700438 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800439
440 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700441 * This is the process holding the activity the user last visited that
442 * is in a different process from the one they are currently in.
443 */
444 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800445
446 /**
447 * The time at which the previous process was last visible.
448 */
449 long mPreviousProcessVisibleTime;
450
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700451 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400452 * Packages that the user has asked to have run in screen size
453 * compatibility mode instead of filling the screen.
454 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700455 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400456
457 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 * Set of PendingResultRecord objects that are currently active.
459 */
460 final HashSet mPendingResultRecords = new HashSet();
461
462 /**
463 * Set of IntentSenderRecord objects that are currently active.
464 */
465 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
466 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
467
468 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800469 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700470 * already logged DropBox entries for. Guarded by itself. If
471 * something (rogue user app) forces this over
472 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
473 */
474 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
475 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
476
477 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700478 * Strict Mode background batched logging state.
479 *
480 * The string buffer is guarded by itself, and its lock is also
481 * used to determine if another batched write is already
482 * in-flight.
483 */
484 private final StringBuilder mStrictModeBuffer = new StringBuilder();
485
486 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 * Keeps track of all IIntentReceivers that have been registered for
488 * broadcasts. Hash keys are the receiver IBinder, hash value is
489 * a ReceiverList.
490 */
491 final HashMap mRegisteredReceivers = new HashMap();
492
493 /**
494 * Resolver for broadcast intents to registered receivers.
495 * Holds BroadcastFilter (subclass of IntentFilter).
496 */
497 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
498 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
499 @Override
500 protected boolean allowFilterResult(
501 BroadcastFilter filter, List<BroadcastFilter> dest) {
502 IBinder target = filter.receiverList.receiver.asBinder();
503 for (int i=dest.size()-1; i>=0; i--) {
504 if (dest.get(i).receiverList.receiver.asBinder() == target) {
505 return false;
506 }
507 }
508 return true;
509 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700510
511 @Override
512 protected String packageForFilter(BroadcastFilter filter) {
513 return filter.packageName;
514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 };
516
517 /**
518 * State of all active sticky broadcasts. Keys are the action of the
519 * sticky Intent, values are an ArrayList of all broadcasted intents with
520 * that action (which should usually be one).
521 */
522 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
523 new HashMap<String, ArrayList<Intent>>();
524
Amith Yamasani742a6712011-05-04 14:49:28 -0700525 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 /**
528 * All currently bound service connections. Keys are the IBinder of
529 * the client's IServiceConnection.
530 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700531 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
532 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533
534 /**
535 * List of services that we have been asked to start,
536 * but haven't yet been able to. It is used to hold start requests
537 * while waiting for their corresponding application thread to get
538 * going.
539 */
540 final ArrayList<ServiceRecord> mPendingServices
541 = new ArrayList<ServiceRecord>();
542
543 /**
544 * List of services that are scheduled to restart following a crash.
545 */
546 final ArrayList<ServiceRecord> mRestartingServices
547 = new ArrayList<ServiceRecord>();
548
549 /**
550 * List of services that are in the process of being stopped.
551 */
552 final ArrayList<ServiceRecord> mStoppingServices
553 = new ArrayList<ServiceRecord>();
554
555 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700556 * Backup/restore process management
557 */
558 String mBackupAppName = null;
559 BackupRecord mBackupTarget = null;
560
561 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 * List of PendingThumbnailsRecord objects of clients who are still
563 * waiting to receive all of the thumbnails for a task.
564 */
565 final ArrayList mPendingThumbnails = new ArrayList();
566
567 /**
568 * List of HistoryRecord objects that have been finished and must
569 * still report back to a pending thumbnail receiver.
570 */
571 final ArrayList mCancelledThumbnails = new ArrayList();
572
Amith Yamasani742a6712011-05-04 14:49:28 -0700573 final ProviderMap mProviderMap = new ProviderMap();
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 /**
576 * List of content providers who have clients waiting for them. The
577 * application is currently being launched and the provider will be
578 * removed from this list once it is published.
579 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700580 final ArrayList<ContentProviderRecord> mLaunchingProviders
581 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582
583 /**
584 * Global set of specific Uri permissions that have been granted.
585 */
586 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
587 = new SparseArray<HashMap<Uri, UriPermission>>();
588
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800589 CoreSettingsObserver mCoreSettingsObserver;
590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 /**
592 * Thread-local storage used to carry caller permissions over through
593 * indirect content-provider access.
594 * @see #ActivityManagerService.openContentUri()
595 */
596 private class Identity {
597 public int pid;
598 public int uid;
599
600 Identity(int _pid, int _uid) {
601 pid = _pid;
602 uid = _uid;
603 }
604 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
607
608 /**
609 * All information we have collected about the runtime performance of
610 * any user id that can impact battery performance.
611 */
612 final BatteryStatsService mBatteryStatsService;
613
614 /**
615 * information about component usage
616 */
617 final UsageStatsService mUsageStatsService;
618
619 /**
620 * Current configuration information. HistoryRecord objects are given
621 * a reference to this object to indicate which configuration they are
622 * currently running in, so this object must be kept immutable.
623 */
624 Configuration mConfiguration = new Configuration();
625
626 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800627 * Current sequencing integer of the configuration, for skipping old
628 * configurations.
629 */
630 int mConfigurationSeq = 0;
631
632 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700633 * Hardware-reported OpenGLES version.
634 */
635 final int GL_ES_VERSION;
636
637 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 * List of initialization arguments to pass to all processes when binding applications to them.
639 * For example, references to the commonly used services.
640 */
641 HashMap<String, IBinder> mAppBindArgs;
642
643 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700644 * Temporary to avoid allocations. Protected by main lock.
645 */
646 final StringBuilder mStringBuilder = new StringBuilder(256);
647
648 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 * Used to control how we initialize the service.
650 */
651 boolean mStartRunning = false;
652 ComponentName mTopComponent;
653 String mTopAction;
654 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700655 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 boolean mSystemReady = false;
657 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700658 boolean mWaitingUpdate = false;
659 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700660 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700661 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
663 Context mContext;
664
665 int mFactoryTest;
666
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700667 boolean mCheckedForSetup;
668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700670 * The time at which we will allow normal application switches again,
671 * after a call to {@link #stopAppSwitches()}.
672 */
673 long mAppSwitchesAllowedTime;
674
675 /**
676 * This is set to true after the first switch after mAppSwitchesAllowedTime
677 * is set; any switches after that will clear the time.
678 */
679 boolean mDidAppSwitch;
680
681 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700682 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700683 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 long mLastPowerCheckRealtime;
685
686 /**
687 * Last time (in uptime) at which we checked for power usage.
688 */
689 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700690
691 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 * Set while we are wanting to sleep, to prevent any
693 * activities from being started/resumed.
694 */
695 boolean mSleeping = false;
696
697 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700698 * Set if we are shutting down the system, similar to sleeping.
699 */
700 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 /**
703 * Task identifier that activities are currently being started
704 * in. Incremented each time a new task is created.
705 * todo: Replace this with a TokenSpace class that generates non-repeating
706 * integers that won't wrap.
707 */
708 int mCurTask = 1;
709
710 /**
711 * Current sequence id for oom_adj computation traversal.
712 */
713 int mAdjSeq = 0;
714
715 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700716 * Current sequence id for process LRU updating.
717 */
718 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
720 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700721 * Keep track of the number of service processes we last found, to
722 * determine on the next iteration which should be B services.
723 */
724 int mNumServiceProcs = 0;
725 int mNewNumServiceProcs = 0;
726
727 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 * System monitoring: number of processes that died since the last
729 * N procs were started.
730 */
731 int[] mProcDeaths = new int[20];
732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700733 /**
734 * This is set if we had to do a delayed dexopt of an app before launching
735 * it, to increasing the ANR timeouts in that case.
736 */
737 boolean mDidDexOpt;
738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 String mDebugApp = null;
740 boolean mWaitForDebugger = false;
741 boolean mDebugTransient = false;
742 String mOrigDebugApp = null;
743 boolean mOrigWaitForDebugger = false;
744 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700745 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700746 String mProfileApp = null;
747 ProcessRecord mProfileProc = null;
748 String mProfileFile;
749 ParcelFileDescriptor mProfileFd;
750 int mProfileType = 0;
751 boolean mAutoStopProfiler = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Jeff Sharkeya4620792011-05-20 15:29:23 -0700753 final RemoteCallbackList<IProcessObserver> mProcessObservers
754 = new RemoteCallbackList<IProcessObserver>();
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 /**
757 * Callback of last caller to {@link #requestPss}.
758 */
759 Runnable mRequestPssCallback;
760
761 /**
762 * Remaining processes for which we are waiting results from the last
763 * call to {@link #requestPss}.
764 */
765 final ArrayList<ProcessRecord> mRequestPssList
766 = new ArrayList<ProcessRecord>();
767
768 /**
769 * Runtime statistics collection thread. This object's lock is used to
770 * protect all related state.
771 */
772 final Thread mProcessStatsThread;
773
774 /**
775 * Used to collect process stats when showing not responding dialog.
776 * Protected by mProcessStatsThread.
777 */
778 final ProcessStats mProcessStats = new ProcessStats(
779 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700780 final AtomicLong mLastCpuTime = new AtomicLong(0);
781 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 long mLastWriteTime = 0;
784
785 /**
786 * Set to true after the system has finished booting.
787 */
788 boolean mBooted = false;
789
Dianne Hackborn7d608422011-08-07 16:24:18 -0700790 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700791 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792
793 WindowManagerService mWindowManager;
794
795 static ActivityManagerService mSelf;
796 static ActivityThread mSystemThread;
797
798 private final class AppDeathRecipient implements IBinder.DeathRecipient {
799 final ProcessRecord mApp;
800 final int mPid;
801 final IApplicationThread mAppThread;
802
803 AppDeathRecipient(ProcessRecord app, int pid,
804 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800805 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 TAG, "New death recipient " + this
807 + " for thread " + thread.asBinder());
808 mApp = app;
809 mPid = pid;
810 mAppThread = thread;
811 }
812
813 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800814 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 TAG, "Death received in " + this
816 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 synchronized(ActivityManagerService.this) {
818 appDiedLocked(mApp, mPid, mAppThread);
819 }
820 }
821 }
822
823 static final int SHOW_ERROR_MSG = 1;
824 static final int SHOW_NOT_RESPONDING_MSG = 2;
825 static final int SHOW_FACTORY_ERROR_MSG = 3;
826 static final int UPDATE_CONFIGURATION_MSG = 4;
827 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
828 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 static final int SERVICE_TIMEOUT_MSG = 12;
830 static final int UPDATE_TIME_ZONE = 13;
831 static final int SHOW_UID_ERROR_MSG = 14;
832 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700834 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700835 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800836 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700837 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
838 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700839 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700840 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700841 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700842 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700843 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700844 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
845 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700846 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800848 static final int FIRST_ACTIVITY_STACK_MSG = 100;
849 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
850 static final int FIRST_COMPAT_MODE_MSG = 300;
851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700853 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700854 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855
856 final Handler mHandler = new Handler() {
857 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800858 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 //}
860
861 public void handleMessage(Message msg) {
862 switch (msg.what) {
863 case SHOW_ERROR_MSG: {
864 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 synchronized (ActivityManagerService.this) {
866 ProcessRecord proc = (ProcessRecord)data.get("app");
867 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800868 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 return;
870 }
871 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700872 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800873 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 d.show();
875 proc.crashDialog = d;
876 } else {
877 // The device is asleep, so just pretend that the user
878 // saw a crash dialog and hit "force quit".
879 res.set(0);
880 }
881 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700882
883 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 } break;
885 case SHOW_NOT_RESPONDING_MSG: {
886 synchronized (ActivityManagerService.this) {
887 HashMap data = (HashMap) msg.obj;
888 ProcessRecord proc = (ProcessRecord)data.get("app");
889 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800890 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 return;
892 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800893
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700894 Intent intent = new Intent("android.intent.action.ANR");
895 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800896 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
897 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700898 }
899 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800900 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700901 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700904 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 d.show();
906 proc.anrDialog = d;
907 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700908
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700909 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700911 case SHOW_STRICT_MODE_VIOLATION_MSG: {
912 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
913 synchronized (ActivityManagerService.this) {
914 ProcessRecord proc = (ProcessRecord) data.get("app");
915 if (proc == null) {
916 Slog.e(TAG, "App not found when showing strict mode dialog.");
917 break;
918 }
919 if (proc.crashDialog != null) {
920 Slog.e(TAG, "App already has strict mode dialog: " + proc);
921 return;
922 }
923 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700924 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700925 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
926 d.show();
927 proc.crashDialog = d;
928 } else {
929 // The device is asleep, so just pretend that the user
930 // saw a crash dialog and hit "force quit".
931 res.set(0);
932 }
933 }
934 ensureBootCompleted();
935 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 case SHOW_FACTORY_ERROR_MSG: {
937 Dialog d = new FactoryErrorDialog(
938 mContext, msg.getData().getCharSequence("msg"));
939 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700940 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 } break;
942 case UPDATE_CONFIGURATION_MSG: {
943 final ContentResolver resolver = mContext.getContentResolver();
944 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
945 } break;
946 case GC_BACKGROUND_PROCESSES_MSG: {
947 synchronized (ActivityManagerService.this) {
948 performAppGcsIfAppropriateLocked();
949 }
950 } break;
951 case WAIT_FOR_DEBUGGER_MSG: {
952 synchronized (ActivityManagerService.this) {
953 ProcessRecord app = (ProcessRecord)msg.obj;
954 if (msg.arg1 != 0) {
955 if (!app.waitedForDebugger) {
956 Dialog d = new AppWaitingForDebuggerDialog(
957 ActivityManagerService.this,
958 mContext, app);
959 app.waitDialog = d;
960 app.waitedForDebugger = true;
961 d.show();
962 }
963 } else {
964 if (app.waitDialog != null) {
965 app.waitDialog.dismiss();
966 app.waitDialog = null;
967 }
968 }
969 }
970 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700972 if (mDidDexOpt) {
973 mDidDexOpt = false;
974 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
975 nmsg.obj = msg.obj;
976 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
977 return;
978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 serviceTimeout((ProcessRecord)msg.obj);
980 } break;
981 case UPDATE_TIME_ZONE: {
982 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800983 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
984 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 if (r.thread != null) {
986 try {
987 r.thread.updateTimeZone();
988 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991 }
992 }
993 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700994 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700995 case CLEAR_DNS_CACHE: {
996 synchronized (ActivityManagerService.this) {
997 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
998 ProcessRecord r = mLruProcesses.get(i);
999 if (r.thread != null) {
1000 try {
1001 r.thread.clearDnsCache();
1002 } catch (RemoteException ex) {
1003 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1004 }
1005 }
1006 }
1007 }
1008 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001009 case UPDATE_HTTP_PROXY: {
1010 ProxyProperties proxy = (ProxyProperties)msg.obj;
1011 String host = "";
1012 String port = "";
1013 String exclList = "";
1014 if (proxy != null) {
1015 host = proxy.getHost();
1016 port = Integer.toString(proxy.getPort());
1017 exclList = proxy.getExclusionList();
1018 }
1019 synchronized (ActivityManagerService.this) {
1020 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1021 ProcessRecord r = mLruProcesses.get(i);
1022 if (r.thread != null) {
1023 try {
1024 r.thread.setHttpProxy(host, port, exclList);
1025 } catch (RemoteException ex) {
1026 Slog.w(TAG, "Failed to update http proxy for: " +
1027 r.info.processName);
1028 }
1029 }
1030 }
1031 }
1032 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001034 String title = "System UIDs Inconsistent";
1035 String text = "UIDs on the system are inconsistent, you need to wipe your"
1036 + " data partition or your device will be unstable.";
1037 Log.e(TAG, title + ": " + text);
1038 if (mShowDialogs) {
1039 // XXX This is a temporary dialog, no need to localize.
1040 AlertDialog d = new BaseErrorDialog(mContext);
1041 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1042 d.setCancelable(false);
1043 d.setTitle(title);
1044 d.setMessage(text);
1045 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1046 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1047 mUidAlert = d;
1048 d.show();
1049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 } break;
1051 case IM_FEELING_LUCKY_MSG: {
1052 if (mUidAlert != null) {
1053 mUidAlert.dismiss();
1054 mUidAlert = null;
1055 }
1056 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001058 if (mDidDexOpt) {
1059 mDidDexOpt = false;
1060 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1061 nmsg.obj = msg.obj;
1062 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1063 return;
1064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 ProcessRecord app = (ProcessRecord)msg.obj;
1066 synchronized (ActivityManagerService.this) {
1067 processStartTimedOutLocked(app);
1068 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001069 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001070 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1071 synchronized (ActivityManagerService.this) {
1072 doPendingActivityLaunchesLocked(true);
1073 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001074 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001075 case KILL_APPLICATION_MSG: {
1076 synchronized (ActivityManagerService.this) {
1077 int uid = msg.arg1;
1078 boolean restart = (msg.arg2 == 1);
1079 String pkg = (String) msg.obj;
Christopher Tate3dacd842011-08-19 14:56:15 -07001080 forceStopPackageLocked(pkg, uid, restart, false, true, false);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001081 }
1082 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001083 case FINALIZE_PENDING_INTENT_MSG: {
1084 ((PendingIntentRecord)msg.obj).completeFinalize();
1085 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001086 case POST_HEAVY_NOTIFICATION_MSG: {
1087 INotificationManager inm = NotificationManager.getService();
1088 if (inm == null) {
1089 return;
1090 }
1091
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001092 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001093 ProcessRecord process = root.app;
1094 if (process == null) {
1095 return;
1096 }
1097
1098 try {
1099 Context context = mContext.createPackageContext(process.info.packageName, 0);
1100 String text = mContext.getString(R.string.heavy_weight_notification,
1101 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1102 Notification notification = new Notification();
1103 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1104 notification.when = 0;
1105 notification.flags = Notification.FLAG_ONGOING_EVENT;
1106 notification.tickerText = text;
1107 notification.defaults = 0; // please be quiet
1108 notification.sound = null;
1109 notification.vibrate = null;
1110 notification.setLatestEventInfo(context, text,
1111 mContext.getText(R.string.heavy_weight_notification_detail),
1112 PendingIntent.getActivity(mContext, 0, root.intent,
1113 PendingIntent.FLAG_CANCEL_CURRENT));
1114
1115 try {
1116 int[] outId = new int[1];
1117 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1118 notification, outId);
1119 } catch (RuntimeException e) {
1120 Slog.w(ActivityManagerService.TAG,
1121 "Error showing notification for heavy-weight app", e);
1122 } catch (RemoteException e) {
1123 }
1124 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001125 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001126 }
1127 } break;
1128 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1129 INotificationManager inm = NotificationManager.getService();
1130 if (inm == null) {
1131 return;
1132 }
1133 try {
1134 inm.cancelNotification("android",
1135 R.string.heavy_weight_notification);
1136 } catch (RuntimeException e) {
1137 Slog.w(ActivityManagerService.TAG,
1138 "Error canceling notification for service", e);
1139 } catch (RemoteException e) {
1140 }
1141 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001142 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1143 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001144 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001145 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001146 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1147 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001148 }
1149 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001150 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1151 synchronized (ActivityManagerService.this) {
1152 ActivityRecord ar = (ActivityRecord)msg.obj;
1153 if (mCompatModeDialog != null) {
1154 if (mCompatModeDialog.mAppInfo.packageName.equals(
1155 ar.info.applicationInfo.packageName)) {
1156 return;
1157 }
1158 mCompatModeDialog.dismiss();
1159 mCompatModeDialog = null;
1160 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001161 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001162 if (mCompatModePackages.getPackageAskCompatModeLocked(
1163 ar.packageName)) {
1164 int mode = mCompatModePackages.computeCompatModeLocked(
1165 ar.info.applicationInfo);
1166 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1167 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1168 mCompatModeDialog = new CompatModeDialog(
1169 ActivityManagerService.this, mContext,
1170 ar.info.applicationInfo);
1171 mCompatModeDialog.show();
1172 }
1173 }
1174 }
1175 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001176 break;
1177 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001178 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001179 final int pid = msg.arg1;
1180 final int uid = msg.arg2;
1181 final boolean foregroundActivities = (Boolean) msg.obj;
1182 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001183 break;
1184 }
1185 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001186 final int pid = msg.arg1;
1187 final int uid = msg.arg2;
1188 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001189 break;
1190 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001191 case REPORT_MEM_USAGE: {
1192 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1193 if (!isDebuggable) {
1194 return;
1195 }
1196 synchronized (ActivityManagerService.this) {
1197 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001198 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1199 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001200 // avoid spamming.
1201 return;
1202 }
1203 mLastMemUsageReportTime = now;
1204 }
1205 Thread thread = new Thread() {
1206 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001207 StringBuilder dropBuilder = new StringBuilder(1024);
1208 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001209 StringWriter oomSw = new StringWriter();
1210 PrintWriter oomPw = new PrintWriter(oomSw);
1211 StringWriter catSw = new StringWriter();
1212 PrintWriter catPw = new PrintWriter(catSw);
1213 String[] emptyArgs = new String[] { };
1214 StringBuilder tag = new StringBuilder(128);
1215 StringBuilder stack = new StringBuilder(128);
1216 tag.append("Low on memory -- ");
1217 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1218 tag, stack);
1219 dropBuilder.append(stack);
1220 dropBuilder.append('\n');
1221 dropBuilder.append('\n');
1222 String oomString = oomSw.toString();
1223 dropBuilder.append(oomString);
1224 dropBuilder.append('\n');
1225 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001226 try {
1227 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1228 "procrank", });
1229 final InputStreamReader converter = new InputStreamReader(
1230 proc.getInputStream());
1231 BufferedReader in = new BufferedReader(converter);
1232 String line;
1233 while (true) {
1234 line = in.readLine();
1235 if (line == null) {
1236 break;
1237 }
1238 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001239 logBuilder.append(line);
1240 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001241 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001242 dropBuilder.append(line);
1243 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001244 }
1245 converter.close();
1246 } catch (IOException e) {
1247 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001248 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001249 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001250 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001251 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001252 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001254 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001255 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001256 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001257 addErrorToDropBox("lowmem", null, "system_server", null,
1258 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001259 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 synchronized (ActivityManagerService.this) {
1261 long now = SystemClock.uptimeMillis();
1262 if (mLastMemUsageReportTime < now) {
1263 mLastMemUsageReportTime = now;
1264 }
1265 }
1266 }
1267 };
1268 thread.start();
1269 break;
1270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 }
1273 };
1274
1275 public static void setSystemProcess() {
1276 try {
1277 ActivityManagerService m = mSelf;
1278
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001279 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001281 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001282 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 if (MONITOR_CPU_USAGE) {
1284 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 ServiceManager.addService("permission", new PermissionController(m));
1287
1288 ApplicationInfo info =
1289 mSelf.mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -07001290 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001291 mSystemThread.installSystemApplicationInfo(info);
1292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 synchronized (mSelf) {
1294 ProcessRecord app = mSelf.newProcessRecordLocked(
1295 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001296 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001298 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001299 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001300 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 synchronized (mSelf.mPidsSelfLocked) {
1302 mSelf.mPidsSelfLocked.put(app.pid, app);
1303 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001304 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 } catch (PackageManager.NameNotFoundException e) {
1307 throw new RuntimeException(
1308 "Unable to find android system package", e);
1309 }
1310 }
1311
1312 public void setWindowManager(WindowManagerService wm) {
1313 mWindowManager = wm;
1314 }
1315
1316 public static final Context main(int factoryTest) {
1317 AThread thr = new AThread();
1318 thr.start();
1319
1320 synchronized (thr) {
1321 while (thr.mService == null) {
1322 try {
1323 thr.wait();
1324 } catch (InterruptedException e) {
1325 }
1326 }
1327 }
1328
1329 ActivityManagerService m = thr.mService;
1330 mSelf = m;
1331 ActivityThread at = ActivityThread.systemMain();
1332 mSystemThread = at;
1333 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001334 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 m.mContext = context;
1336 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001337 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338
1339 m.mBatteryStatsService.publish(context);
1340 m.mUsageStatsService.publish(context);
1341
1342 synchronized (thr) {
1343 thr.mReady = true;
1344 thr.notifyAll();
1345 }
1346
1347 m.startRunning(null, null, null, null);
1348
1349 return context;
1350 }
1351
1352 public static ActivityManagerService self() {
1353 return mSelf;
1354 }
1355
1356 static class AThread extends Thread {
1357 ActivityManagerService mService;
1358 boolean mReady = false;
1359
1360 public AThread() {
1361 super("ActivityManager");
1362 }
1363
1364 public void run() {
1365 Looper.prepare();
1366
1367 android.os.Process.setThreadPriority(
1368 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001369 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370
1371 ActivityManagerService m = new ActivityManagerService();
1372
1373 synchronized (this) {
1374 mService = m;
1375 notifyAll();
1376 }
1377
1378 synchronized (this) {
1379 while (!mReady) {
1380 try {
1381 wait();
1382 } catch (InterruptedException e) {
1383 }
1384 }
1385 }
1386
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001387 // For debug builds, log event loop stalls to dropbox for analysis.
1388 if (StrictMode.conditionallyEnableDebugLogging()) {
1389 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1390 }
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 Looper.loop();
1393 }
1394 }
1395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 static class MemBinder extends Binder {
1397 ActivityManagerService mActivityManagerService;
1398 MemBinder(ActivityManagerService activityManagerService) {
1399 mActivityManagerService = activityManagerService;
1400 }
1401
1402 @Override
1403 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001404 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1405 != PackageManager.PERMISSION_GRANTED) {
1406 pw.println("Permission Denial: can't dump meminfo from from pid="
1407 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1408 + " without permission " + android.Manifest.permission.DUMP);
1409 return;
1410 }
1411
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001412 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001413 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 }
1416
Chet Haase9c1e23b2011-03-24 10:51:31 -07001417 static class GraphicsBinder extends Binder {
1418 ActivityManagerService mActivityManagerService;
1419 GraphicsBinder(ActivityManagerService activityManagerService) {
1420 mActivityManagerService = activityManagerService;
1421 }
1422
1423 @Override
1424 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001425 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1426 != PackageManager.PERMISSION_GRANTED) {
1427 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1428 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1429 + " without permission " + android.Manifest.permission.DUMP);
1430 return;
1431 }
1432
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001433 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001434 }
1435 }
1436
Jeff Brown6754ba22011-12-14 20:20:01 -08001437 static class DbBinder extends Binder {
1438 ActivityManagerService mActivityManagerService;
1439 DbBinder(ActivityManagerService activityManagerService) {
1440 mActivityManagerService = activityManagerService;
1441 }
1442
1443 @Override
1444 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1445 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1446 != PackageManager.PERMISSION_GRANTED) {
1447 pw.println("Permission Denial: can't dump dbinfo from from pid="
1448 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1449 + " without permission " + android.Manifest.permission.DUMP);
1450 return;
1451 }
1452
1453 mActivityManagerService.dumpDbInfo(fd, pw, args);
1454 }
1455 }
1456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 static class CpuBinder extends Binder {
1458 ActivityManagerService mActivityManagerService;
1459 CpuBinder(ActivityManagerService activityManagerService) {
1460 mActivityManagerService = activityManagerService;
1461 }
1462
1463 @Override
1464 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001465 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1466 != PackageManager.PERMISSION_GRANTED) {
1467 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1468 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1469 + " without permission " + android.Manifest.permission.DUMP);
1470 return;
1471 }
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001474 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1475 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1476 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 }
1478 }
1479 }
1480
1481 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001482 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001483
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001484 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1485 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1486 mBroadcastQueues[0] = mFgBroadcastQueue;
1487 mBroadcastQueues[1] = mBgBroadcastQueue;
1488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 File dataDir = Environment.getDataDirectory();
1490 File systemDir = new File(dataDir, "system");
1491 systemDir.mkdirs();
1492 mBatteryStatsService = new BatteryStatsService(new File(
1493 systemDir, "batterystats.bin").toString());
1494 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001495 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001496 mOnBattery = DEBUG_POWER ? true
1497 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001498 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001500 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001501 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001502 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
Jack Palevichb90d28c2009-07-22 15:35:24 -07001504 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1505 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1506
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001507 mConfiguration.setToDefaults();
1508 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001509 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 mProcessStats.init();
1511
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001512 mCompatModePackages = new CompatModePackages(this, systemDir);
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 // Add ourself to the Watchdog monitors.
1515 Watchdog.getInstance().addMonitor(this);
1516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 mProcessStatsThread = new Thread("ProcessStats") {
1518 public void run() {
1519 while (true) {
1520 try {
1521 try {
1522 synchronized(this) {
1523 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001524 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001526 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 // + ", write delay=" + nextWriteDelay);
1528 if (nextWriteDelay < nextCpuDelay) {
1529 nextCpuDelay = nextWriteDelay;
1530 }
1531 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001532 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 this.wait(nextCpuDelay);
1534 }
1535 }
1536 } catch (InterruptedException e) {
1537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 updateCpuStatsNow();
1539 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001540 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543 }
1544 };
1545 mProcessStatsThread.start();
1546 }
1547
1548 @Override
1549 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1550 throws RemoteException {
1551 try {
1552 return super.onTransact(code, data, reply, flags);
1553 } catch (RuntimeException e) {
1554 // The activity manager only throws security exceptions, so let's
1555 // log all others.
1556 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 throw e;
1560 }
1561 }
1562
1563 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001564 final long now = SystemClock.uptimeMillis();
1565 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1566 return;
1567 }
1568 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1569 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 mProcessStatsThread.notify();
1571 }
1572 }
1573 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 void updateCpuStatsNow() {
1576 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001577 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 final long now = SystemClock.uptimeMillis();
1579 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001582 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1583 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 haveNewCpuStats = true;
1585 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 //Slog.i(TAG, mProcessStats.printCurrentState());
1587 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 // + mProcessStats.getTotalCpuPercent() + "%");
1589
Joe Onorato8a9b2202010-02-26 18:56:32 -08001590 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 if ("true".equals(SystemProperties.get("events.cpu"))) {
1592 int user = mProcessStats.getLastUserTime();
1593 int system = mProcessStats.getLastSystemTime();
1594 int iowait = mProcessStats.getLastIoWaitTime();
1595 int irq = mProcessStats.getLastIrqTime();
1596 int softIrq = mProcessStats.getLastSoftIrqTime();
1597 int idle = mProcessStats.getLastIdleTime();
1598
1599 int total = user + system + iowait + irq + softIrq + idle;
1600 if (total == 0) total = 1;
1601
Doug Zongker2bec3d42009-12-04 12:52:44 -08001602 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 ((user+system+iowait+irq+softIrq) * 100) / total,
1604 (user * 100) / total,
1605 (system * 100) / total,
1606 (iowait * 100) / total,
1607 (irq * 100) / total,
1608 (softIrq * 100) / total);
1609 }
1610 }
1611
Amith Yamasanie43530a2009-08-21 13:11:37 -07001612 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001613 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001614 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 synchronized(mPidsSelfLocked) {
1616 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001617 if (mOnBattery) {
1618 int perc = bstats.startAddingCpuLocked();
1619 int totalUTime = 0;
1620 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001621 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001623 ProcessStats.Stats st = mProcessStats.getStats(i);
1624 if (!st.working) {
1625 continue;
1626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001628 int otherUTime = (st.rel_utime*perc)/100;
1629 int otherSTime = (st.rel_stime*perc)/100;
1630 totalUTime += otherUTime;
1631 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 if (pr != null) {
1633 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001634 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1635 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001636 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001637 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001638 } else {
1639 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001640 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001641 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001642 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1643 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001644 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001648 bstats.finishAddingCpuLocked(perc, totalUTime,
1649 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
1652 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1655 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001656 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658 }
1659 }
1660 }
1661
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001662 @Override
1663 public void batteryNeedsCpuUpdate() {
1664 updateCpuStatsNow();
1665 }
1666
1667 @Override
1668 public void batteryPowerChanged(boolean onBattery) {
1669 // When plugging in, update the CPU stats first before changing
1670 // the plug state.
1671 updateCpuStatsNow();
1672 synchronized (this) {
1673 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001674 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001675 }
1676 }
1677 }
1678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 /**
1680 * Initialize the application bind args. These are passed to each
1681 * process when the bindApplication() IPC is sent to the process. They're
1682 * lazily setup to make sure the services are running when they're asked for.
1683 */
1684 private HashMap<String, IBinder> getCommonServicesLocked() {
1685 if (mAppBindArgs == null) {
1686 mAppBindArgs = new HashMap<String, IBinder>();
1687
1688 // Setup the application init args
1689 mAppBindArgs.put("package", ServiceManager.getService("package"));
1690 mAppBindArgs.put("window", ServiceManager.getService("window"));
1691 mAppBindArgs.put(Context.ALARM_SERVICE,
1692 ServiceManager.getService(Context.ALARM_SERVICE));
1693 }
1694 return mAppBindArgs;
1695 }
1696
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001697 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (mFocusedActivity != r) {
1699 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001700 if (r != null) {
1701 mWindowManager.setFocusedApp(r.appToken, true);
1702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704 }
1705
Dianne Hackborn906497c2010-05-10 15:57:38 -07001706 private final void updateLruProcessInternalLocked(ProcessRecord app,
1707 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001709 int lrui = mLruProcesses.indexOf(app);
1710 if (lrui >= 0) mLruProcesses.remove(lrui);
1711
1712 int i = mLruProcesses.size()-1;
1713 int skipTop = 0;
1714
Dianne Hackborn906497c2010-05-10 15:57:38 -07001715 app.lruSeq = mLruSeq;
1716
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001717 // compute the new weight for this process.
1718 if (updateActivityTime) {
1719 app.lastActivityTime = SystemClock.uptimeMillis();
1720 }
1721 if (app.activities.size() > 0) {
1722 // If this process has activities, we more strongly want to keep
1723 // it around.
1724 app.lruWeight = app.lastActivityTime;
1725 } else if (app.pubProviders.size() > 0) {
1726 // If this process contains content providers, we want to keep
1727 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001728 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001729 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001730 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001731 } else {
1732 // If this process doesn't have activities, we less strongly
1733 // want to keep it around, and generally want to avoid getting
1734 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001735 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001736 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001737 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001739
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 while (i >= 0) {
1741 ProcessRecord p = mLruProcesses.get(i);
1742 // If this app shouldn't be in front of the first N background
1743 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001744 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 skipTop--;
1746 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001747 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 mLruProcesses.add(i+1, app);
1749 break;
1750 }
1751 i--;
1752 }
1753 if (i < 0) {
1754 mLruProcesses.add(0, app);
1755 }
1756
Dianne Hackborn906497c2010-05-10 15:57:38 -07001757 // If the app is currently using a content provider or service,
1758 // bump those processes as well.
1759 if (app.connections.size() > 0) {
1760 for (ConnectionRecord cr : app.connections) {
1761 if (cr.binding != null && cr.binding.service != null
1762 && cr.binding.service.app != null
1763 && cr.binding.service.app.lruSeq != mLruSeq) {
1764 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1765 updateActivityTime, i+1);
1766 }
1767 }
1768 }
1769 if (app.conProviders.size() > 0) {
1770 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001771 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1772 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001773 updateActivityTime, i+1);
1774 }
1775 }
1776 }
1777
Joe Onorato8a9b2202010-02-26 18:56:32 -08001778 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 if (oomAdj) {
1780 updateOomAdjLocked();
1781 }
1782 }
1783
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001784 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001785 boolean oomAdj, boolean updateActivityTime) {
1786 mLruSeq++;
1787 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1788 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001789
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001790 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 String processName, int uid) {
1792 if (uid == Process.SYSTEM_UID) {
1793 // The system gets to run in any process. If there are multiple
1794 // processes with the same uid, just pick the first (this
1795 // should never happen).
1796 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1797 processName);
1798 return procs != null ? procs.valueAt(0) : null;
1799 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001800 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 ProcessRecord proc = mProcessNames.get(processName, uid);
1802 return proc;
1803 }
1804
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001805 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001806 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001807 try {
1808 if (pm.performDexOpt(packageName)) {
1809 mDidDexOpt = true;
1810 }
1811 } catch (RemoteException e) {
1812 }
1813 }
1814
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 int transit = mWindowManager.getPendingAppTransition();
1817 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1818 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1819 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1820 }
1821
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001822 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001824 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1825 boolean isolated) {
1826 ProcessRecord app;
1827 if (!isolated) {
1828 app = getProcessRecordLocked(processName, info.uid);
1829 } else {
1830 // If this is an isolated process, it can't re-use an existing process.
1831 app = null;
1832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 // We don't have to do anything more if:
1834 // (1) There is an existing application record; and
1835 // (2) The caller doesn't think it is dead, OR there is no thread
1836 // object attached to it so we know it couldn't have crashed; and
1837 // (3) There is a pid assigned to it, so it is either starting or
1838 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 + " app=" + app + " knownToBeDead=" + knownToBeDead
1841 + " thread=" + (app != null ? app.thread : null)
1842 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001843 if (app != null && app.pid > 0) {
1844 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001845 // We already have the app running, or are waiting for it to
1846 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001847 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001848 // If this is a new package in the process, add the package to the list
1849 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001850 return app;
1851 } else {
1852 // An application record is attached to a previous process,
1853 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001854 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001855 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 String hostingNameStr = hostingName != null
1860 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001861
1862 if (!isolated) {
1863 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1864 // If we are in the background, then check to see if this process
1865 // is bad. If so, we will just silently fail.
1866 if (mBadProcesses.get(info.processName, info.uid) != null) {
1867 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1868 + "/" + info.processName);
1869 return null;
1870 }
1871 } else {
1872 // When the user is explicitly starting a process, then clear its
1873 // crash count so that we won't make it bad until they see at
1874 // least one crash dialog again, and make the process good again
1875 // if it had been bad.
1876 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001877 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001878 mProcessCrashTimes.remove(info.processName, info.uid);
1879 if (mBadProcesses.get(info.processName, info.uid) != null) {
1880 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1881 info.processName);
1882 mBadProcesses.remove(info.processName, info.uid);
1883 if (app != null) {
1884 app.bad = false;
1885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 }
1888 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001891 app = newProcessRecordLocked(null, info, processName, isolated);
1892 if (app == null) {
1893 Slog.w(TAG, "Failed making new process record for "
1894 + processName + "/" + info.uid + " isolated=" + isolated);
1895 return null;
1896 }
1897 mProcessNames.put(processName, app.uid, app);
1898 if (isolated) {
1899 mIsolatedProcesses.put(app.uid, app);
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 } else {
1902 // If this is a new package in the process, add the package to the list
1903 app.addPackage(info.packageName);
1904 }
1905
1906 // If the system is not ready yet, then hold off on starting this
1907 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001908 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001909 && !isAllowedWhileBooting(info)
1910 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (!mProcessesOnHold.contains(app)) {
1912 mProcessesOnHold.add(app);
1913 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001914 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 return app;
1916 }
1917
1918 startProcessLocked(app, hostingType, hostingNameStr);
1919 return (app.pid != 0) ? app : null;
1920 }
1921
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001922 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1923 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1924 }
1925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 private final void startProcessLocked(ProcessRecord app,
1927 String hostingType, String hostingNameStr) {
1928 if (app.pid > 0 && app.pid != MY_PID) {
1929 synchronized (mPidsSelfLocked) {
1930 mPidsSelfLocked.remove(app.pid);
1931 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1932 }
1933 app.pid = 0;
1934 }
1935
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001936 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1937 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 mProcessesOnHold.remove(app);
1939
1940 updateCpuStats();
1941
1942 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1943 mProcDeaths[0] = 0;
1944
1945 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001946 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001949 if (!app.isolated) {
1950 try {
1951 gids = mContext.getPackageManager().getPackageGids(
1952 app.info.packageName);
1953 } catch (PackageManager.NameNotFoundException e) {
1954 Slog.w(TAG, "Unable to retrieve gids", e);
1955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1958 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1959 && mTopComponent != null
1960 && app.processName.equals(mTopComponent.getPackageName())) {
1961 uid = 0;
1962 }
1963 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1964 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1965 uid = 0;
1966 }
1967 }
1968 int debugFlags = 0;
1969 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1970 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001971 // Also turn on CheckJNI for debuggable apps. It's quite
1972 // awkward to turn on otherwise.
1973 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001975 // Run the app in safe mode if its manifest requests so or the
1976 // system is booted in safe mode.
1977 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1978 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001979 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1982 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1983 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001984 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1985 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if ("1".equals(SystemProperties.get("debug.assert"))) {
1988 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1989 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001990
1991 // Start the process. It will either succeed and return a result containing
1992 // the PID of the new process, or else throw a RuntimeException.
1993 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001994 app.processName, uid, uid, gids, debugFlags,
1995 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
1998 synchronized (bs) {
1999 if (bs.isOnBattery()) {
2000 app.batteryStats.incStartsLocked();
2001 }
2002 }
2003
Jeff Brown3f9dd282011-07-08 20:02:19 -07002004 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 app.processName, hostingType,
2006 hostingNameStr != null ? hostingNameStr : "");
2007
2008 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002009 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 }
2011
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002012 StringBuilder buf = mStringBuilder;
2013 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 buf.append("Start proc ");
2015 buf.append(app.processName);
2016 buf.append(" for ");
2017 buf.append(hostingType);
2018 if (hostingNameStr != null) {
2019 buf.append(" ");
2020 buf.append(hostingNameStr);
2021 }
2022 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002023 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 buf.append(" uid=");
2025 buf.append(uid);
2026 buf.append(" gids={");
2027 if (gids != null) {
2028 for (int gi=0; gi<gids.length; gi++) {
2029 if (gi != 0) buf.append(", ");
2030 buf.append(gids[gi]);
2031
2032 }
2033 }
2034 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002035 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002036 app.pid = startResult.pid;
2037 app.usingWrapper = startResult.usingWrapper;
2038 app.removed = false;
2039 synchronized (mPidsSelfLocked) {
2040 this.mPidsSelfLocked.put(startResult.pid, app);
2041 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2042 msg.obj = app;
2043 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2044 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046 } catch (RuntimeException e) {
2047 // XXX do better error recovery.
2048 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002049 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 }
2052
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002053 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (resumed) {
2055 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2056 } else {
2057 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2058 }
2059 }
2060
Amith Yamasani742a6712011-05-04 14:49:28 -07002061 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002062 if (mHeadless) {
2063 // Added because none of the other calls to ensureBootCompleted seem to fire
2064 // when running headless.
2065 ensureBootCompleted();
2066 return false;
2067 }
2068
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002069 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2070 && mTopAction == null) {
2071 // We are running in factory test mode, but unable to find
2072 // the factory test app, so just sit around displaying the
2073 // error message and don't try to start anything.
2074 return false;
2075 }
2076 Intent intent = new Intent(
2077 mTopAction,
2078 mTopData != null ? Uri.parse(mTopData) : null);
2079 intent.setComponent(mTopComponent);
2080 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2081 intent.addCategory(Intent.CATEGORY_HOME);
2082 }
2083 ActivityInfo aInfo =
2084 intent.resolveActivityInfo(mContext.getPackageManager(),
2085 STOCK_PM_FLAGS);
2086 if (aInfo != null) {
2087 intent.setComponent(new ComponentName(
2088 aInfo.applicationInfo.packageName, aInfo.name));
2089 // Don't do this if the home app is currently being
2090 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002091 aInfo = new ActivityInfo(aInfo);
2092 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002093 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2094 aInfo.applicationInfo.uid);
2095 if (app == null || app.instrumentationClass == null) {
2096 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097 mMainStack.startActivityLocked(null, intent, null, null, 0, aInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002098 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002099 }
2100 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002101
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002102 return true;
2103 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002104
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002105 /**
2106 * Starts the "new version setup screen" if appropriate.
2107 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002108 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002109 // Only do this once per boot.
2110 if (mCheckedForSetup) {
2111 return;
2112 }
2113
2114 // We will show this screen if the current one is a different
2115 // version than the last one shown, and we are not running in
2116 // low-level factory test mode.
2117 final ContentResolver resolver = mContext.getContentResolver();
2118 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2119 Settings.Secure.getInt(resolver,
2120 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2121 mCheckedForSetup = true;
2122
2123 // See if we should be showing the platform update setup UI.
2124 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2125 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2126 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2127
2128 // We don't allow third party apps to replace this.
2129 ResolveInfo ri = null;
2130 for (int i=0; ris != null && i<ris.size(); i++) {
2131 if ((ris.get(i).activityInfo.applicationInfo.flags
2132 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2133 ri = ris.get(i);
2134 break;
2135 }
2136 }
2137
2138 if (ri != null) {
2139 String vers = ri.activityInfo.metaData != null
2140 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2141 : null;
2142 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2143 vers = ri.activityInfo.applicationInfo.metaData.getString(
2144 Intent.METADATA_SETUP_VERSION);
2145 }
2146 String lastVers = Settings.Secure.getString(
2147 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2148 if (vers != null && !vers.equals(lastVers)) {
2149 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2150 intent.setComponent(new ComponentName(
2151 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002152 mMainStack.startActivityLocked(null, intent, null, null, 0, ri.activityInfo,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002153 null, null, 0, 0, 0, false, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002154 }
2155 }
2156 }
2157 }
2158
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002159 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002160 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002161 }
2162
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002163 void enforceNotIsolatedCaller(String caller) {
2164 if (UserId.isIsolated(Binder.getCallingUid())) {
2165 throw new SecurityException("Isolated process not allowed to call " + caller);
2166 }
2167 }
2168
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002169 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002170 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002171 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002172 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2173 }
2174 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002175
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002176 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002177 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2178 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002179 synchronized (this) {
2180 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2181 }
2182 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002183
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002184 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002185 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002186 synchronized (this) {
2187 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2188 }
2189 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002190
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002191 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002192 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2193 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 synchronized (this) {
2195 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002196 }
2197 }
2198
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002199 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002200 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002201 synchronized (this) {
2202 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2203 }
2204 }
2205
2206 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002207 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2208 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002209 synchronized (this) {
2210 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2211 }
2212 }
2213
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002214 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002215 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002216
2217 final int identHash = System.identityHashCode(r);
2218 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220
Jeff Sharkeya4620792011-05-20 15:29:23 -07002221 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2222 int i = mProcessObservers.beginBroadcast();
2223 while (i > 0) {
2224 i--;
2225 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2226 if (observer != null) {
2227 try {
2228 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2229 } catch (RemoteException e) {
2230 }
2231 }
2232 }
2233 mProcessObservers.finishBroadcast();
2234 }
2235
2236 private void dispatchProcessDied(int pid, int uid) {
2237 int i = mProcessObservers.beginBroadcast();
2238 while (i > 0) {
2239 i--;
2240 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2241 if (observer != null) {
2242 try {
2243 observer.onProcessDied(pid, uid);
2244 } catch (RemoteException e) {
2245 }
2246 }
2247 }
2248 mProcessObservers.finishBroadcast();
2249 }
2250
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002251 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002252 final int N = mPendingActivityLaunches.size();
2253 if (N <= 0) {
2254 return;
2255 }
2256 for (int i=0; i<N; i++) {
2257 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002258 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002259 pal.grantedUriPermissions, pal.grantedMode, pal.onlyIfNeeded,
2260 doResume && i == (N-1));
2261 }
2262 mPendingActivityLaunches.clear();
2263 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002264
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002265 public final int startActivity(IApplicationThread caller,
2266 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2267 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002268 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2269 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002270 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002271 int userId = 0;
2272 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2273 // Requesting home, set the identity to the current user
2274 // HACK!
2275 userId = mCurrentUserId;
2276 } else {
2277 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2278 // the current user's userId
2279 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2280 userId = 0;
2281 } else {
2282 userId = Binder.getOrigCallingUser();
2283 }
2284 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Amith Yamasani742a6712011-05-04 14:49:28 -07002286 grantedUriPermissions, grantedMode, resultTo, resultWho, requestCode, onlyIfNeeded,
2287 debug, profileFile, profileFd, autoStopProfiler, null, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002288 }
2289
2290 public final WaitResult startActivityAndWait(IApplicationThread caller,
2291 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2292 int grantedMode, IBinder resultTo,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002293 String resultWho, int requestCode, boolean onlyIfNeeded, boolean debug,
2294 String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002295 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002296 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002297 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002298 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002299 grantedUriPermissions, grantedMode, resultTo, resultWho,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002300 requestCode, onlyIfNeeded, debug, profileFile, profileFd, autoStopProfiler,
Amith Yamasani742a6712011-05-04 14:49:28 -07002301 res, null, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002302 return res;
2303 }
2304
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002305 public final int startActivityWithConfig(IApplicationThread caller,
2306 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2307 int grantedMode, IBinder resultTo,
2308 String resultWho, int requestCode, boolean onlyIfNeeded,
2309 boolean debug, Configuration config) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002310 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002311 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002312 grantedUriPermissions, grantedMode, resultTo, resultWho,
Amith Yamasani742a6712011-05-04 14:49:28 -07002313 requestCode, onlyIfNeeded,
2314 debug, null, null, false, null, config, Binder.getOrigCallingUser());
2315 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002316 }
2317
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002318 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002319 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002320 IBinder resultTo, String resultWho, int requestCode,
2321 int flagsMask, int flagsValues) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002322 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002323 // Refuse possible leaked file descriptors
2324 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2325 throw new IllegalArgumentException("File descriptors passed in Intent");
2326 }
2327
2328 IIntentSender sender = intent.getTarget();
2329 if (!(sender instanceof PendingIntentRecord)) {
2330 throw new IllegalArgumentException("Bad PendingIntent object");
2331 }
2332
2333 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002334
2335 synchronized (this) {
2336 // If this is coming from the currently resumed activity, it is
2337 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002338 if (mMainStack.mResumedActivity != null
2339 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002340 Binder.getCallingUid()) {
2341 mAppSwitchesAllowedTime = 0;
2342 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002343 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002344 int ret = pir.sendInner(0, fillInIntent, resolvedType, null,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002345 null, resultTo, resultWho, requestCode, flagsMask, flagsValues);
Amith Yamasani742a6712011-05-04 14:49:28 -07002346 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002347 }
2348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 public boolean startNextMatchingActivity(IBinder callingActivity,
2350 Intent intent) {
2351 // Refuse possible leaked file descriptors
2352 if (intent != null && intent.hasFileDescriptors() == true) {
2353 throw new IllegalArgumentException("File descriptors passed in Intent");
2354 }
2355
2356 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002357 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2358 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 return false;
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 if (r.app == null || r.app.thread == null) {
2362 // The caller is not running... d'oh!
2363 return false;
2364 }
2365 intent = new Intent(intent);
2366 // The caller is not allowed to change the data.
2367 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2368 // And we are resetting to find the next component...
2369 intent.setComponent(null);
2370
2371 ActivityInfo aInfo = null;
2372 try {
2373 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002374 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 intent, r.resolvedType,
Dianne Hackborn1655be42009-05-08 14:29:01 -07002376 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377
2378 // Look for the original activity in the list...
2379 final int N = resolves != null ? resolves.size() : 0;
2380 for (int i=0; i<N; i++) {
2381 ResolveInfo rInfo = resolves.get(i);
2382 if (rInfo.activityInfo.packageName.equals(r.packageName)
2383 && rInfo.activityInfo.name.equals(r.info.name)) {
2384 // We found the current one... the next matching is
2385 // after it.
2386 i++;
2387 if (i<N) {
2388 aInfo = resolves.get(i).activityInfo;
2389 }
2390 break;
2391 }
2392 }
2393 } catch (RemoteException e) {
2394 }
2395
2396 if (aInfo == null) {
2397 // Nobody who is next!
2398 return false;
2399 }
2400
2401 intent.setComponent(new ComponentName(
2402 aInfo.applicationInfo.packageName, aInfo.name));
2403 intent.setFlags(intent.getFlags()&~(
2404 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2405 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2406 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2407 Intent.FLAG_ACTIVITY_NEW_TASK));
2408
2409 // Okay now we need to start the new activity, replacing the
2410 // currently running activity. This is a little tricky because
2411 // we want to start the new one as if the current one is finished,
2412 // but not finish the current one first so that there is no flicker.
2413 // And thus...
2414 final boolean wasFinishing = r.finishing;
2415 r.finishing = true;
2416
2417 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002418 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 final String resultWho = r.resultWho;
2420 final int requestCode = r.requestCode;
2421 r.resultTo = null;
2422 if (resultTo != null) {
2423 resultTo.removeResultsLocked(r, resultWho, requestCode);
2424 }
2425
2426 final long origId = Binder.clearCallingIdentity();
2427 // XXX we are not dealing with propagating grantedUriPermissions...
2428 // those are not yet exposed to user code, so there is no need.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002430 r.resolvedType, null, 0, aInfo,
2431 resultTo != null ? resultTo.appToken : null, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002432 requestCode, -1, r.launchedFromUid, false, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 Binder.restoreCallingIdentity(origId);
2434
2435 r.finishing = wasFinishing;
2436 if (res != START_SUCCESS) {
2437 return false;
2438 }
2439 return true;
2440 }
2441 }
2442
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 Intent intent, String resolvedType, IBinder resultTo,
2445 String resultWho, int requestCode, boolean onlyIfNeeded) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002446
2447 // This is so super not safe, that only the system (or okay root)
2448 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002449 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002450 final int callingUid = Binder.getCallingUid();
2451 if (callingUid != 0 && callingUid != Process.myUid()) {
2452 throw new SecurityException(
2453 "startActivityInPackage only available to the system");
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455
Amith Yamasani742a6712011-05-04 14:49:28 -07002456 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002457 null, 0, resultTo, resultWho, requestCode, onlyIfNeeded, false,
Amith Yamasani742a6712011-05-04 14:49:28 -07002458 null, null, false, null, null, userId);
2459 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002460 }
2461
2462 public final int startActivities(IApplicationThread caller,
2463 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002464 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
2466 Binder.getOrigCallingUser());
2467 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002468 }
2469
2470 public final int startActivitiesInPackage(int uid,
2471 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2472
2473 // This is so super not safe, that only the system (or okay root)
2474 // can do it.
2475 final int callingUid = Binder.getCallingUid();
2476 if (callingUid != 0 && callingUid != Process.myUid()) {
2477 throw new SecurityException(
2478 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002480 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
2481 UserId.getUserId(uid));
2482 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002487 // Quick case: check if the top-most recent task is the same.
2488 if (N > 0 && mRecentTasks.get(0) == task) {
2489 return;
2490 }
2491 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 for (int i=0; i<N; i++) {
2493 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002494 if (task.userId == tr.userId
2495 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2496 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 mRecentTasks.remove(i);
2498 i--;
2499 N--;
2500 if (task.intent == null) {
2501 // If the new recent task we are adding is not fully
2502 // specified, then replace it with the existing recent task.
2503 task = tr;
2504 }
2505 }
2506 }
2507 if (N >= MAX_RECENT_TASKS) {
2508 mRecentTasks.remove(N-1);
2509 }
2510 mRecentTasks.add(0, task);
2511 }
2512
2513 public void setRequestedOrientation(IBinder token,
2514 int requestedOrientation) {
2515 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002516 ActivityRecord r = mMainStack.isInStackLocked(token);
2517 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 return;
2519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002521 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002523 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002524 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 if (config != null) {
2526 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002527 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002528 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
2530 }
2531 Binder.restoreCallingIdentity(origId);
2532 }
2533 }
2534
2535 public int getRequestedOrientation(IBinder token) {
2536 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002537 ActivityRecord r = mMainStack.isInStackLocked(token);
2538 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2540 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002541 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543 }
2544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 /**
2546 * This is the internal entry point for handling Activity.finish().
2547 *
2548 * @param token The Binder token referencing the Activity we want to finish.
2549 * @param resultCode Result code, if any, from this Activity.
2550 * @param resultData Result data (Intent), if any, from this Activity.
2551 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002552 * @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 -08002553 */
2554 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2555 // Refuse possible leaked file descriptors
2556 if (resultData != null && resultData.hasFileDescriptors() == true) {
2557 throw new IllegalArgumentException("File descriptors passed in Intent");
2558 }
2559
2560 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002561 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (next != null) {
2565 // ask watcher if this is allowed
2566 boolean resumeOK = true;
2567 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002568 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002570 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572
2573 if (!resumeOK) {
2574 return false;
2575 }
2576 }
2577 }
2578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002579 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 resultData, "app-request");
2581 Binder.restoreCallingIdentity(origId);
2582 return res;
2583 }
2584 }
2585
Dianne Hackborn860755f2010-06-03 18:47:52 -07002586 public final void finishHeavyWeightApp() {
2587 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2588 != PackageManager.PERMISSION_GRANTED) {
2589 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2590 + Binder.getCallingPid()
2591 + ", uid=" + Binder.getCallingUid()
2592 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2593 Slog.w(TAG, msg);
2594 throw new SecurityException(msg);
2595 }
2596
2597 synchronized(this) {
2598 if (mHeavyWeightProcess == null) {
2599 return;
2600 }
2601
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002602 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002603 mHeavyWeightProcess.activities);
2604 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002605 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002606 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002607 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002608 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002610 null, "finish-heavy");
2611 }
2612 }
2613 }
2614
2615 mHeavyWeightProcess = null;
2616 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2617 }
2618 }
2619
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002620 public void crashApplication(int uid, int initialPid, String packageName,
2621 String message) {
2622 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2623 != PackageManager.PERMISSION_GRANTED) {
2624 String msg = "Permission Denial: crashApplication() from pid="
2625 + Binder.getCallingPid()
2626 + ", uid=" + Binder.getCallingUid()
2627 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2628 Slog.w(TAG, msg);
2629 throw new SecurityException(msg);
2630 }
2631
2632 synchronized(this) {
2633 ProcessRecord proc = null;
2634
2635 // Figure out which process to kill. We don't trust that initialPid
2636 // still has any relation to current pids, so must scan through the
2637 // list.
2638 synchronized (mPidsSelfLocked) {
2639 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2640 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002641 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002642 continue;
2643 }
2644 if (p.pid == initialPid) {
2645 proc = p;
2646 break;
2647 }
2648 for (String str : p.pkgList) {
2649 if (str.equals(packageName)) {
2650 proc = p;
2651 }
2652 }
2653 }
2654 }
2655
2656 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002657 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002658 + " initialPid=" + initialPid
2659 + " packageName=" + packageName);
2660 return;
2661 }
2662
2663 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002664 if (proc.pid == Process.myPid()) {
2665 Log.w(TAG, "crashApplication: trying to crash self!");
2666 return;
2667 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002668 long ident = Binder.clearCallingIdentity();
2669 try {
2670 proc.thread.scheduleCrash(message);
2671 } catch (RemoteException e) {
2672 }
2673 Binder.restoreCallingIdentity(ident);
2674 }
2675 }
2676 }
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 public final void finishSubActivity(IBinder token, String resultWho,
2679 int requestCode) {
2680 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002681 ActivityRecord self = mMainStack.isInStackLocked(token);
2682 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 return;
2684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685
2686 final long origId = Binder.clearCallingIdentity();
2687
2688 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002689 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2690 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 if (r.resultTo == self && r.requestCode == requestCode) {
2692 if ((r.resultWho == null && resultWho == null) ||
2693 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002694 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 Activity.RESULT_CANCELED, null, "request-sub");
2696 }
2697 }
2698 }
2699
2700 Binder.restoreCallingIdentity(origId);
2701 }
2702 }
2703
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002704 public boolean willActivityBeVisible(IBinder token) {
2705 synchronized(this) {
2706 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2708 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002709 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002710 return true;
2711 }
2712 if (r.fullscreen && !r.finishing) {
2713 return false;
2714 }
2715 }
2716 return true;
2717 }
2718 }
2719
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002720 public void overridePendingTransition(IBinder token, String packageName,
2721 int enterAnim, int exitAnim) {
2722 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002723 ActivityRecord self = mMainStack.isInStackLocked(token);
2724 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002725 return;
2726 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002727
2728 final long origId = Binder.clearCallingIdentity();
2729
2730 if (self.state == ActivityState.RESUMED
2731 || self.state == ActivityState.PAUSING) {
2732 mWindowManager.overridePendingAppTransition(packageName,
2733 enterAnim, exitAnim);
2734 }
2735
2736 Binder.restoreCallingIdentity(origId);
2737 }
2738 }
2739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 * Main function for removing an existing process from the activity manager
2742 * as a result of that process going away. Clears out all connections
2743 * to the process.
2744 */
2745 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002746 boolean restarting, boolean allowRestart) {
2747 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002749 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 }
2751
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002752 if (mProfileProc == app) {
2753 clearProfilerLocked();
2754 }
2755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002757 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2758 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2759 mMainStack.mPausingActivity = null;
2760 }
2761 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2762 mMainStack.mLastPausedActivity = null;
2763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764
2765 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767
2768 boolean atTop = true;
2769 boolean hasVisibleActivities = false;
2770
2771 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002772 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002773 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 TAG, "Removing app " + app + " from history with " + i + " entries");
2775 while (i > 0) {
2776 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002778 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2780 if (r.app == app) {
2781 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002782 if (ActivityStack.DEBUG_ADD_REMOVE) {
2783 RuntimeException here = new RuntimeException("here");
2784 here.fillInStackTrace();
2785 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2786 + ": haveState=" + r.haveState
2787 + " stateNotNeeded=" + r.stateNotNeeded
2788 + " finishing=" + r.finishing
2789 + " state=" + r.state, here);
2790 }
2791 if (!r.finishing) {
2792 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002793 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2794 System.identityHashCode(r),
2795 r.task.taskId, r.shortComponentName,
2796 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002797 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002798 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799
2800 } else {
2801 // We have the current state for this activity, so
2802 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002803 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 TAG, "Keeping entry, setting app to null");
2805 if (r.visible) {
2806 hasVisibleActivities = true;
2807 }
2808 r.app = null;
2809 r.nowVisible = false;
2810 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002811 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2812 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 r.icicle = null;
2814 }
2815 }
2816
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002817 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819 atTop = false;
2820 }
2821
2822 app.activities.clear();
2823
2824 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002825 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 + " running instrumentation " + app.instrumentationClass);
2827 Bundle info = new Bundle();
2828 info.putString("shortMsg", "Process crashed.");
2829 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2830 }
2831
2832 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 // If there was nothing to resume, and we are not already
2835 // restarting this process, but there is a visible activity that
2836 // is hosted by the process... then make sure all visible
2837 // activities are running, taking care of restarting this
2838 // process.
2839 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842 }
2843 }
2844 }
2845
2846 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2847 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002849 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2850 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2852 return i;
2853 }
2854 }
2855 return -1;
2856 }
2857
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002858 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 IApplicationThread thread) {
2860 if (thread == null) {
2861 return null;
2862 }
2863
2864 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002865 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 IApplicationThread thread) {
2870
2871 mProcDeaths[0]++;
2872
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002873 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2874 synchronized (stats) {
2875 stats.noteProcessDiedLocked(app.info.uid, pid);
2876 }
2877
Magnus Edlund7bb25812010-02-24 15:45:06 +01002878 // Clean up already done if the process has been re-started.
2879 if (app.pid == pid && app.thread != null &&
2880 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002881 if (!app.killedBackground) {
2882 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2883 + ") has died.");
2884 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002885 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002886 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 TAG, "Dying app: " + app + ", pid: " + pid
2888 + ", thread: " + thread.asBinder());
2889 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002890 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891
2892 if (doLowMem) {
2893 // If there are no longer any background processes running,
2894 // and the app that died was not running instrumentation,
2895 // then tell everyone we are now low on memory.
2896 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002897 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2898 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002899 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 haveBg = true;
2901 break;
2902 }
2903 }
2904
2905 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002906 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002907 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002908 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2909 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002910 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002911 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2912 // The low memory report is overriding any current
2913 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002914 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002915 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002916 rec.lastRequestedGc = 0;
2917 } else {
2918 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002920 rec.reportLowMemory = true;
2921 rec.lastLowMemory = now;
2922 mProcessesToGc.remove(rec);
2923 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002926 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002930 } else if (app.pid != pid) {
2931 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002932 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002933 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002934 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002935 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002936 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 + thread.asBinder());
2938 }
2939 }
2940
Dan Egnor42471dd2010-01-07 17:25:22 -08002941 /**
2942 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002943 * @param clearTraces causes the dump file to be erased prior to the new
2944 * traces being written, if true; when false, the new traces will be
2945 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002946 * @param firstPids of dalvik VM processes to dump stack traces for first
2947 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 * @return file containing stack traces, or null if no dump file is configured
2949 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002950 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2951 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002952 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2953 if (tracesPath == null || tracesPath.length() == 0) {
2954 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002956
2957 File tracesFile = new File(tracesPath);
2958 try {
2959 File tracesDir = tracesFile.getParentFile();
2960 if (!tracesDir.exists()) tracesFile.mkdirs();
2961 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2962
Christopher Tate6ee412d2010-05-28 12:01:56 -07002963 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002964 tracesFile.createNewFile();
2965 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2966 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002967 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002968 return null;
2969 }
2970
2971 // Use a FileObserver to detect when traces finish writing.
2972 // The order of traces is considered important to maintain for legibility.
2973 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2974 public synchronized void onEvent(int event, String path) { notify(); }
2975 };
2976
2977 try {
2978 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002979
2980 // First collect all of the stacks of the most important pids.
2981 try {
2982 int num = firstPids.size();
2983 for (int i = 0; i < num; i++) {
2984 synchronized (observer) {
2985 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2986 observer.wait(200); // Wait for write-close, give up after 200msec
2987 }
2988 }
2989 } catch (InterruptedException e) {
2990 Log.wtf(TAG, e);
2991 }
2992
2993 // Next measure CPU usage.
2994 if (processStats != null) {
2995 processStats.init();
2996 System.gc();
2997 processStats.update();
2998 try {
2999 synchronized (processStats) {
3000 processStats.wait(500); // measure over 1/2 second.
3001 }
3002 } catch (InterruptedException e) {
3003 }
3004 processStats.update();
3005
3006 // We'll take the stack crawls of just the top apps using CPU.
3007 final int N = processStats.countWorkingStats();
3008 int numProcs = 0;
3009 for (int i=0; i<N && numProcs<5; i++) {
3010 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3011 if (lastPids.indexOfKey(stats.pid) >= 0) {
3012 numProcs++;
3013 try {
3014 synchronized (observer) {
3015 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3016 observer.wait(200); // Wait for write-close, give up after 200msec
3017 }
3018 } catch (InterruptedException e) {
3019 Log.wtf(TAG, e);
3020 }
3021
3022 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003023 }
3024 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003025
3026 return tracesFile;
3027
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 } finally {
3029 observer.stopWatching();
3030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003033 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3034 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3036 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3037
Dianne Hackborn287952c2010-09-22 22:34:31 -07003038 if (mController != null) {
3039 try {
3040 // 0 == continue, -1 = kill process immediately
3041 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3042 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3043 } catch (RemoteException e) {
3044 mController = null;
3045 }
3046 }
3047
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003048 long anrTime = SystemClock.uptimeMillis();
3049 if (MONITOR_CPU_USAGE) {
3050 updateCpuStatsNow();
3051 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003052
3053 synchronized (this) {
3054 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3055 if (mShuttingDown) {
3056 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3057 return;
3058 } else if (app.notResponding) {
3059 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3060 return;
3061 } else if (app.crashing) {
3062 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3063 return;
3064 }
3065
3066 // In case we come through here for the same app before completing
3067 // this one, mark as anring now so we will bail out.
3068 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003069
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003070 // Log the ANR to the event log.
3071 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3072 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003073
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003074 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003076
3077 int parentPid = app.pid;
3078 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003080
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003081 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003082
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003083 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3084 ProcessRecord r = mLruProcesses.get(i);
3085 if (r != null && r.thread != null) {
3086 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003087 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3088 if (r.persistent) {
3089 firstPids.add(pid);
3090 } else {
3091 lastPids.put(pid, Boolean.TRUE);
3092 }
3093 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
3096 }
3097
Dan Egnor42471dd2010-01-07 17:25:22 -08003098 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003099 StringBuilder info = mStringBuilder;
3100 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003101 info.append("ANR in ").append(app.processName);
3102 if (activity != null && activity.shortComponentName != null) {
3103 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003104 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003105 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003107 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003109 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003110 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112
Dianne Hackborn287952c2010-09-22 22:34:31 -07003113 final ProcessStats processStats = new ProcessStats(true);
3114
3115 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3116
Dan Egnor42471dd2010-01-07 17:25:22 -08003117 String cpuInfo = null;
3118 if (MONITOR_CPU_USAGE) {
3119 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003120 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003121 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003122 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003123 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003124 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003127 info.append(processStats.printCurrentState(anrTime));
3128
Joe Onorato8a9b2202010-02-26 18:56:32 -08003129 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003130 if (tracesFile == null) {
3131 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3132 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3133 }
3134
Jeff Sharkeya353d262011-10-28 11:12:06 -07003135 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3136 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003137
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003138 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003140 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3141 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003143 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3144 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
3146 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003147 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 }
3149 }
3150
Dan Egnor42471dd2010-01-07 17:25:22 -08003151 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3152 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3153 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003154
3155 synchronized (this) {
3156 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003157 Slog.w(TAG, "Killing " + app + ": background ANR");
3158 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3159 app.processName, app.setAdj, "background ANR");
3160 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003161 return;
3162 }
3163
3164 // Set the app's notResponding state, and look up the errorReportReceiver
3165 makeAppNotRespondingLocked(app,
3166 activity != null ? activity.shortComponentName : null,
3167 annotation != null ? "ANR " + annotation : "ANR",
3168 info.toString());
3169
3170 // Bring up the infamous App Not Responding dialog
3171 Message msg = Message.obtain();
3172 HashMap map = new HashMap();
3173 msg.what = SHOW_NOT_RESPONDING_MSG;
3174 msg.obj = map;
3175 map.put("app", app);
3176 if (activity != null) {
3177 map.put("activity", activity);
3178 }
3179
3180 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 }
3183
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003184 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3185 if (!mLaunchWarningShown) {
3186 mLaunchWarningShown = true;
3187 mHandler.post(new Runnable() {
3188 @Override
3189 public void run() {
3190 synchronized (ActivityManagerService.this) {
3191 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3192 d.show();
3193 mHandler.postDelayed(new Runnable() {
3194 @Override
3195 public void run() {
3196 synchronized (ActivityManagerService.this) {
3197 d.dismiss();
3198 mLaunchWarningShown = false;
3199 }
3200 }
3201 }, 4000);
3202 }
3203 }
3204 });
3205 }
3206 }
3207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003209 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003210 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 int uid = Binder.getCallingUid();
3212 int pid = Binder.getCallingPid();
3213 long callingId = Binder.clearCallingIdentity();
3214 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003215 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 int pkgUid = -1;
3217 synchronized(this) {
3218 try {
3219 pkgUid = pm.getPackageUid(packageName);
3220 } catch (RemoteException e) {
3221 }
3222 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003223 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 return false;
3225 }
3226 if (uid == pkgUid || checkComponentPermission(
3227 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003228 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003230 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 } else {
3232 throw new SecurityException(pid+" does not have permission:"+
3233 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3234 "for process:"+packageName);
3235 }
3236 }
3237
3238 try {
3239 //clear application user data
3240 pm.clearApplicationUserData(packageName, observer);
3241 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3242 Uri.fromParts("package", packageName, null));
3243 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003244 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003245 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 } catch (RemoteException e) {
3247 }
3248 } finally {
3249 Binder.restoreCallingIdentity(callingId);
3250 }
3251 return true;
3252 }
3253
Dianne Hackborn03abb812010-01-04 18:43:19 -08003254 public void killBackgroundProcesses(final String packageName) {
3255 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3256 != PackageManager.PERMISSION_GRANTED &&
3257 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3258 != PackageManager.PERMISSION_GRANTED) {
3259 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 + Binder.getCallingPid()
3261 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003262 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003263 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 throw new SecurityException(msg);
3265 }
3266
3267 long callingId = Binder.clearCallingIdentity();
3268 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003269 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 int pkgUid = -1;
3271 synchronized(this) {
3272 try {
3273 pkgUid = pm.getPackageUid(packageName);
3274 } catch (RemoteException e) {
3275 }
3276 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003277 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 return;
3279 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003280 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003281 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3282 }
3283 } finally {
3284 Binder.restoreCallingIdentity(callingId);
3285 }
3286 }
3287
3288 public void killAllBackgroundProcesses() {
3289 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3290 != PackageManager.PERMISSION_GRANTED) {
3291 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3292 + Binder.getCallingPid()
3293 + ", uid=" + Binder.getCallingUid()
3294 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3295 Slog.w(TAG, msg);
3296 throw new SecurityException(msg);
3297 }
3298
3299 long callingId = Binder.clearCallingIdentity();
3300 try {
3301 synchronized(this) {
3302 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3303 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3304 final int NA = apps.size();
3305 for (int ia=0; ia<NA; ia++) {
3306 ProcessRecord app = apps.valueAt(ia);
3307 if (app.persistent) {
3308 // we don't kill persistent processes
3309 continue;
3310 }
3311 if (app.removed) {
3312 procs.add(app);
3313 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3314 app.removed = true;
3315 procs.add(app);
3316 }
3317 }
3318 }
3319
3320 int N = procs.size();
3321 for (int i=0; i<N; i++) {
3322 removeProcessLocked(procs.get(i), false, true, "kill all background");
3323 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003324 }
3325 } finally {
3326 Binder.restoreCallingIdentity(callingId);
3327 }
3328 }
3329
3330 public void forceStopPackage(final String packageName) {
3331 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3332 != PackageManager.PERMISSION_GRANTED) {
3333 String msg = "Permission Denial: forceStopPackage() from pid="
3334 + Binder.getCallingPid()
3335 + ", uid=" + Binder.getCallingUid()
3336 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003337 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003338 throw new SecurityException(msg);
3339 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003340 final int userId = Binder.getOrigCallingUser();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003341 long callingId = Binder.clearCallingIdentity();
3342 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003343 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003344 int pkgUid = -1;
3345 synchronized(this) {
3346 try {
3347 pkgUid = pm.getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07003348 // Convert the uid to the one for the calling user
3349 pkgUid = UserId.getUid(userId, pkgUid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003350 } catch (RemoteException e) {
3351 }
3352 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003353 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003354 return;
3355 }
3356 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003357 try {
3358 pm.setPackageStoppedState(packageName, true);
3359 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003360 } catch (IllegalArgumentException e) {
3361 Slog.w(TAG, "Failed trying to unstop package "
3362 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365 } finally {
3366 Binder.restoreCallingIdentity(callingId);
3367 }
3368 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003369
3370 /*
3371 * The pkg name and uid have to be specified.
3372 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3373 */
3374 public void killApplicationWithUid(String pkg, int uid) {
3375 if (pkg == null) {
3376 return;
3377 }
3378 // Make sure the uid is valid.
3379 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003380 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003381 return;
3382 }
3383 int callerUid = Binder.getCallingUid();
3384 // Only the system server can kill an application
3385 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003386 // Post an aysnc message to kill the application
3387 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3388 msg.arg1 = uid;
3389 msg.arg2 = 0;
3390 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003391 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003392 } else {
3393 throw new SecurityException(callerUid + " cannot kill pkg: " +
3394 pkg);
3395 }
3396 }
3397
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003398 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003399 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003400 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003401 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003402 if (reason != null) {
3403 intent.putExtra("reason", reason);
3404 }
3405
3406 final int uid = Binder.getCallingUid();
3407 final long origId = Binder.clearCallingIdentity();
3408 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003409 mWindowManager.closeSystemDialogs(reason);
3410
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003411 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003412 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003413 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003414 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003415 Activity.RESULT_CANCELED, null, "close-sys");
3416 }
3417 }
3418
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003419 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003420 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003421 }
3422 Binder.restoreCallingIdentity(origId);
3423 }
3424
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003425 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003426 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003427 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003428 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3429 for (int i=pids.length-1; i>=0; i--) {
3430 infos[i] = new Debug.MemoryInfo();
3431 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003432 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003433 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003434 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003435
Dianne Hackbornb437e092011-08-05 17:50:29 -07003436 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003437 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003438 long[] pss = new long[pids.length];
3439 for (int i=pids.length-1; i>=0; i--) {
3440 pss[i] = Debug.getPss(pids[i]);
3441 }
3442 return pss;
3443 }
3444
Christopher Tate5e1ab332009-09-01 20:32:49 -07003445 public void killApplicationProcess(String processName, int uid) {
3446 if (processName == null) {
3447 return;
3448 }
3449
3450 int callerUid = Binder.getCallingUid();
3451 // Only the system server can kill an application
3452 if (callerUid == Process.SYSTEM_UID) {
3453 synchronized (this) {
3454 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003455 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003456 try {
3457 app.thread.scheduleSuicide();
3458 } catch (RemoteException e) {
3459 // If the other end already died, then our work here is done.
3460 }
3461 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003462 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003463 + processName + " / " + uid);
3464 }
3465 }
3466 } else {
3467 throw new SecurityException(callerUid + " cannot kill app process: " +
3468 processName);
3469 }
3470 }
3471
Dianne Hackborn03abb812010-01-04 18:43:19 -08003472 private void forceStopPackageLocked(final String packageName, int uid) {
Christopher Tate3dacd842011-08-19 14:56:15 -07003473 forceStopPackageLocked(packageName, uid, false, false, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3475 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003476 if (!mProcessesReady) {
3477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 intent.putExtra(Intent.EXTRA_UID, uid);
3480 broadcastIntentLocked(null, null, intent,
3481 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003482 false, false,
3483 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 }
3485
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003486 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003487 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003488 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003489 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490
Dianne Hackborn03abb812010-01-04 18:43:19 -08003491 // Remove all processes this package may have touched: all with the
3492 // same UID (except for the system or root user), and all whose name
3493 // matches the package name.
3494 final String procNamePrefix = packageName + ":";
3495 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3496 final int NA = apps.size();
3497 for (int ia=0; ia<NA; ia++) {
3498 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003499 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003500 // we don't kill persistent processes
3501 continue;
3502 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003503 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003504 if (doit) {
3505 procs.add(app);
3506 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003507 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3508 || app.processName.equals(packageName)
3509 || app.processName.startsWith(procNamePrefix)) {
3510 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003511 if (!doit) {
3512 return true;
3513 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003514 app.removed = true;
3515 procs.add(app);
3516 }
3517 }
3518 }
3519 }
3520
3521 int N = procs.size();
3522 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003523 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003524 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003525 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003527
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003528 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003529 boolean callerWillRestart, boolean purgeCache, boolean doit,
3530 boolean evenPersistent) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003531 int i;
3532 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 if (uid < 0) {
3535 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003536 uid = AppGlobals.getPackageManager().getPackageUid(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 } catch (RemoteException e) {
3538 }
3539 }
3540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003541 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003542 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003543
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003544 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3545 while (badApps.hasNext()) {
3546 SparseArray<Long> ba = badApps.next();
3547 if (ba.get(uid) != null) {
3548 badApps.remove();
3549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003552
3553 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003554 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003556 TaskRecord lastTask = null;
3557 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003558 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003559 final boolean samePackage = r.packageName.equals(name);
3560 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003561 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003562 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003563 if (r.finishing) {
3564 // If this activity is just finishing, then it is not
3565 // interesting as far as something to stop.
3566 continue;
3567 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003568 return true;
3569 }
3570 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003571 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003572 if (samePackage) {
3573 if (r.app != null) {
3574 r.app.removed = true;
3575 }
3576 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003578 lastTask = r.task;
3579 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3580 null, "force-stop")) {
3581 i--;
3582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
3584 }
3585
3586 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003587 int userId = UserId.getUserId(uid);
3588 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003589 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003590 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003591 if (!doit) {
3592 return true;
3593 }
3594 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003595 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 if (service.app != null) {
3597 service.app.removed = true;
3598 }
3599 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003600 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 services.add(service);
3602 }
3603 }
3604
3605 N = services.size();
3606 for (i=0; i<N; i++) {
3607 bringDownServiceLocked(services.get(i), true);
3608 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003609
3610 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003611 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003612 if (provider.info.packageName.equals(name)
3613 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3614 if (!doit) {
3615 return true;
3616 }
3617 didSomething = true;
3618 providers.add(provider);
3619 }
3620 }
3621
3622 N = providers.size();
3623 for (i=0; i<N; i++) {
3624 removeDyingProviderLocked(null, providers.get(i));
3625 }
3626
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003627 if (doit) {
3628 if (purgeCache) {
3629 AttributeCache ac = AttributeCache.instance();
3630 if (ac != null) {
3631 ac.removePackage(name);
3632 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003633 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003634 if (mBooted) {
3635 mMainStack.resumeTopActivityLocked(null);
3636 mMainStack.scheduleIdleLocked();
3637 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003638 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003639
3640 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003643 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003644 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003646 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003647 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003648 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 + "/" + uid + ")");
3650
3651 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003652 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003653 if (mHeavyWeightProcess == app) {
3654 mHeavyWeightProcess = null;
3655 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 boolean needRestart = false;
3658 if (app.pid > 0 && app.pid != MY_PID) {
3659 int pid = app.pid;
3660 synchronized (mPidsSelfLocked) {
3661 mPidsSelfLocked.remove(pid);
3662 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3663 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003665 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003666 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003667 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003669 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003671 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 } else {
3673 needRestart = true;
3674 }
3675 }
3676 } else {
3677 mRemovedProcesses.add(app);
3678 }
3679
3680 return needRestart;
3681 }
3682
3683 private final void processStartTimedOutLocked(ProcessRecord app) {
3684 final int pid = app.pid;
3685 boolean gone = false;
3686 synchronized (mPidsSelfLocked) {
3687 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3688 if (knownApp != null && knownApp.thread == null) {
3689 mPidsSelfLocked.remove(pid);
3690 gone = true;
3691 }
3692 }
3693
3694 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003695 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003696 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003697 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003698 mProcessNames.remove(app.processName, app.uid);
3699 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003700 if (mHeavyWeightProcess == app) {
3701 mHeavyWeightProcess = null;
3702 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3703 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003704 // Take care of any launching providers waiting for this process.
3705 checkAppInLaunchingProvidersLocked(app, true);
3706 // Take care of any services that are waiting for the process.
3707 for (int i=0; i<mPendingServices.size(); i++) {
3708 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003709 if ((app.uid == sr.appInfo.uid
3710 && app.processName.equals(sr.processName))
3711 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003712 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003713 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003714 mPendingServices.remove(i);
3715 i--;
3716 bringDownServiceLocked(sr, true);
3717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003719 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3720 app.processName, app.setAdj, "start timeout");
3721 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003722 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003723 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003724 try {
3725 IBackupManager bm = IBackupManager.Stub.asInterface(
3726 ServiceManager.getService(Context.BACKUP_SERVICE));
3727 bm.agentDisconnected(app.info.packageName);
3728 } catch (RemoteException e) {
3729 // Can't happen; the backup manager is local
3730 }
3731 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003732 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003733 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003734 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003737 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
3739 }
3740
3741 private final boolean attachApplicationLocked(IApplicationThread thread,
3742 int pid) {
3743
3744 // Find the application record that is being attached... either via
3745 // the pid if we are running in multiple processes, or just pull the
3746 // next app record if we are emulating process with anonymous threads.
3747 ProcessRecord app;
3748 if (pid != MY_PID && pid >= 0) {
3749 synchronized (mPidsSelfLocked) {
3750 app = mPidsSelfLocked.get(pid);
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 } else {
3753 app = null;
3754 }
3755
3756 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003757 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003759 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003761 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 } else {
3763 try {
3764 thread.scheduleExit();
3765 } catch (Exception e) {
3766 // Ignore exceptions.
3767 }
3768 }
3769 return false;
3770 }
3771
3772 // If this application record is still attached to a previous
3773 // process, clean it up now.
3774 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003775 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
3777
3778 // Tell the process all about itself.
3779
Joe Onorato8a9b2202010-02-26 18:56:32 -08003780 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 TAG, "Binding process pid " + pid + " to record " + app);
3782
3783 String processName = app.processName;
3784 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003785 AppDeathRecipient adr = new AppDeathRecipient(
3786 app, pid, thread);
3787 thread.asBinder().linkToDeath(adr, 0);
3788 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 } catch (RemoteException e) {
3790 app.resetPackageList();
3791 startProcessLocked(app, "link fail", processName);
3792 return false;
3793 }
3794
Doug Zongker2bec3d42009-12-04 12:52:44 -08003795 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796
3797 app.thread = thread;
3798 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003799 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3800 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 app.forcingToForeground = null;
3802 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003803 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 app.debugging = false;
3805
3806 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3807
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003808 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003809 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003811 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003812 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003813 }
3814
Joe Onorato8a9b2202010-02-26 18:56:32 -08003815 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 TAG, "New app record " + app
3817 + " thread=" + thread.asBinder() + " pid=" + pid);
3818 try {
3819 int testMode = IApplicationThread.DEBUG_OFF;
3820 if (mDebugApp != null && mDebugApp.equals(processName)) {
3821 testMode = mWaitForDebugger
3822 ? IApplicationThread.DEBUG_WAIT
3823 : IApplicationThread.DEBUG_ON;
3824 app.debugging = true;
3825 if (mDebugTransient) {
3826 mDebugApp = mOrigDebugApp;
3827 mWaitForDebugger = mOrigWaitForDebugger;
3828 }
3829 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003830 String profileFile = app.instrumentationProfileFile;
3831 ParcelFileDescriptor profileFd = null;
3832 boolean profileAutoStop = false;
3833 if (mProfileApp != null && mProfileApp.equals(processName)) {
3834 mProfileProc = app;
3835 profileFile = mProfileFile;
3836 profileFd = mProfileFd;
3837 profileAutoStop = mAutoStopProfiler;
3838 }
3839
Christopher Tate181fafa2009-05-14 11:12:14 -07003840 // If the app is being launched for restore or full backup, set it up specially
3841 boolean isRestrictedBackupMode = false;
3842 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3843 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003844 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003845 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3846 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003847
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003848 ensurePackageDexOpt(app.instrumentationInfo != null
3849 ? app.instrumentationInfo.packageName
3850 : app.info.packageName);
3851 if (app.instrumentationClass != null) {
3852 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003853 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003855 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003856 ApplicationInfo appInfo = app.instrumentationInfo != null
3857 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003858 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003859 if (profileFd != null) {
3860 profileFd = profileFd.dup();
3861 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003862 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003863 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 app.instrumentationArguments, app.instrumentationWatcher, testMode,
Dianne Hackborn5d927c22011-09-02 12:22:18 -07003865 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003866 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003867 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003868 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003869 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 } catch (Exception e) {
3871 // todo: Yikes! What should we do? For now we will try to
3872 // start another process, but that could easily get us in
3873 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003874 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875
3876 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003877 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 startProcessLocked(app, "bind fail", processName);
3879 return false;
3880 }
3881
3882 // Remove this record from the list of starting applications.
3883 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003884 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3885 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 mProcessesOnHold.remove(app);
3887
3888 boolean badApp = false;
3889 boolean didSomething = false;
3890
3891 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003892 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003893 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003894 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 && processName.equals(hr.processName)) {
3896 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003897 if (mHeadless) {
3898 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3899 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 didSomething = true;
3901 }
3902 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003903 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 + hr.intent.getComponent().flattenToShortString(), e);
3905 badApp = true;
3906 }
3907 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 }
3910 }
3911
3912 // Find any services that should be running in this process...
3913 if (!badApp && mPendingServices.size() > 0) {
3914 ServiceRecord sr = null;
3915 try {
3916 for (int i=0; i<mPendingServices.size(); i++) {
3917 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003918 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
3919 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 continue;
3921 }
3922
3923 mPendingServices.remove(i);
3924 i--;
3925 realStartServiceLocked(sr, app);
3926 didSomething = true;
3927 }
3928 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003929 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 + sr.shortName, e);
3931 badApp = true;
3932 }
3933 }
3934
Christopher Tatef46723b2012-01-26 14:19:24 -08003935 // Check if a next-broadcast receiver is in this process...
3936 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08003938 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08003940 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 }
3943 }
3944
Christopher Tate181fafa2009-05-14 11:12:14 -07003945 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003946 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003947 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003948 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07003949 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003950 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
3951 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
3952 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07003953 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003954 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07003955 e.printStackTrace();
3956 }
3957 }
3958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 if (badApp) {
3960 // todo: Also need to kill application to deal with all
3961 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003962 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 return false;
3964 }
3965
3966 if (!didSomething) {
3967 updateOomAdjLocked();
3968 }
3969
3970 return true;
3971 }
3972
3973 public final void attachApplication(IApplicationThread thread) {
3974 synchronized (this) {
3975 int callingPid = Binder.getCallingPid();
3976 final long origId = Binder.clearCallingIdentity();
3977 attachApplicationLocked(thread, callingPid);
3978 Binder.restoreCallingIdentity(origId);
3979 }
3980 }
3981
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003982 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003984 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
3985 if (stopProfiling) {
3986 synchronized (this) {
3987 if (mProfileProc == r.app) {
3988 if (mProfileFd != null) {
3989 try {
3990 mProfileFd.close();
3991 } catch (IOException e) {
3992 }
3993 clearProfilerLocked();
3994 }
3995 }
3996 }
3997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 Binder.restoreCallingIdentity(origId);
3999 }
4000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004002 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004003 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 mWindowManager.enableScreenAfterBoot();
4005 }
4006
Dianne Hackborn661cd522011-08-22 00:26:20 -07004007 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004008 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004009 mWindowManager.showBootMessage(msg, always);
4010 }
4011
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004012 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004013 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004014 synchronized (this) {
4015 mMainStack.dismissKeyguardOnNextActivityLocked();
4016 }
4017 }
4018
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004019 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004020 IntentFilter pkgFilter = new IntentFilter();
4021 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4022 pkgFilter.addDataScheme("package");
4023 mContext.registerReceiver(new BroadcastReceiver() {
4024 @Override
4025 public void onReceive(Context context, Intent intent) {
4026 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4027 if (pkgs != null) {
4028 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004029 synchronized (ActivityManagerService.this) {
Christopher Tate3dacd842011-08-19 14:56:15 -07004030 if (forceStopPackageLocked(pkg, -1, false, false, false, false)) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004031 setResultCode(Activity.RESULT_OK);
4032 return;
4033 }
4034 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004035 }
4036 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004037 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004038 }, pkgFilter);
4039
4040 synchronized (this) {
4041 // Ensure that any processes we had put on hold are now started
4042 // up.
4043 final int NP = mProcessesOnHold.size();
4044 if (NP > 0) {
4045 ArrayList<ProcessRecord> procs =
4046 new ArrayList<ProcessRecord>(mProcessesOnHold);
4047 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004048 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4049 + procs.get(ip));
4050 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004051 }
4052 }
4053
4054 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004055 // Start looking for apps that are abusing wake locks.
4056 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004057 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004058 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004059 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004060 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004061 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004062 broadcastIntentLocked(null, null,
4063 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4064 null, null, 0, null, null,
4065 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004066 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004067 }
4068 }
4069 }
4070
4071 final void ensureBootCompleted() {
4072 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004073 boolean enableScreen;
4074 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004075 booting = mBooting;
4076 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004077 enableScreen = !mBooted;
4078 mBooted = true;
4079 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004080
4081 if (booting) {
4082 finishBooting();
4083 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004084
4085 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004086 enableScreenAfterBoot();
4087 }
4088 }
4089
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004090 public final void activityPaused(IBinder token) {
4091 final long origId = Binder.clearCallingIdentity();
4092 mMainStack.activityPaused(token, false);
4093 Binder.restoreCallingIdentity(origId);
4094 }
4095
4096 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4097 CharSequence description) {
4098 if (localLOGV) Slog.v(
4099 TAG, "Activity stopped: token=" + token);
4100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 // Refuse possible leaked file descriptors
4102 if (icicle != null && icicle.hasFileDescriptors()) {
4103 throw new IllegalArgumentException("File descriptors passed in Bundle");
4104 }
4105
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004106 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107
4108 final long origId = Binder.clearCallingIdentity();
4109
4110 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004111 r = mMainStack.isInStackLocked(token);
4112 if (r != null) {
4113 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 }
4115 }
4116
4117 if (r != null) {
4118 sendPendingThumbnail(r, null, null, null, false);
4119 }
4120
4121 trimApplications();
4122
4123 Binder.restoreCallingIdentity(origId);
4124 }
4125
4126 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004127 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004128 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 }
4130
4131 public String getCallingPackage(IBinder token) {
4132 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004133 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004134 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136 }
4137
4138 public ComponentName getCallingActivity(IBinder token) {
4139 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004140 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 return r != null ? r.intent.getComponent() : null;
4142 }
4143 }
4144
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004145 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004146 ActivityRecord r = mMainStack.isInStackLocked(token);
4147 if (r == null) {
4148 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004150 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 }
4152
4153 public ComponentName getActivityClassForToken(IBinder token) {
4154 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004155 ActivityRecord r = mMainStack.isInStackLocked(token);
4156 if (r == null) {
4157 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004159 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 }
4161 }
4162
4163 public String getPackageForToken(IBinder token) {
4164 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004165 ActivityRecord r = mMainStack.isInStackLocked(token);
4166 if (r == null) {
4167 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004169 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 }
4171 }
4172
4173 public IIntentSender getIntentSender(int type,
4174 String packageName, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004175 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004176 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004178 if (intents != null) {
4179 if (intents.length < 1) {
4180 throw new IllegalArgumentException("Intents array length must be >= 1");
4181 }
4182 for (int i=0; i<intents.length; i++) {
4183 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004184 if (intent != null) {
4185 if (intent.hasFileDescriptors()) {
4186 throw new IllegalArgumentException("File descriptors passed in Intent");
4187 }
4188 if (type == INTENT_SENDER_BROADCAST &&
4189 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4190 throw new IllegalArgumentException(
4191 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4192 }
4193 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004194 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004195 }
4196 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004197 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004198 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004199 }
4200 }
4201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 synchronized(this) {
4203 int callingUid = Binder.getCallingUid();
4204 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004205 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004206 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 .getPackageUid(packageName);
Amith Yamasani742a6712011-05-04 14:49:28 -07004208 if (UserId.getAppId(callingUid) != uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 String msg = "Permission Denial: getIntentSender() from pid="
4210 + Binder.getCallingPid()
4211 + ", uid=" + Binder.getCallingUid()
4212 + ", (need uid=" + uid + ")"
4213 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004214 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 throw new SecurityException(msg);
4216 }
4217 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004218
Amith Yamasani742a6712011-05-04 14:49:28 -07004219 if (DEBUG_MU)
4220 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4221 + Binder.getOrigCallingUid());
4222 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004223 token, resultWho, requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 } catch (RemoteException e) {
4226 throw new SecurityException(e);
4227 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004228 }
4229 }
4230
4231 IIntentSender getIntentSenderLocked(int type,
4232 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004233 int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004234 if (DEBUG_MU)
4235 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004236 ActivityRecord activity = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004237 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004238 activity = mMainStack.isInStackLocked(token);
4239 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004240 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004242 if (activity.finishing) {
4243 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004245 }
4246
4247 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4248 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4249 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4250 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4251 |PendingIntent.FLAG_UPDATE_CURRENT);
4252
4253 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4254 type, packageName, activity, resultWho,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004255 requestCode, intents, resolvedTypes, flags);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004256 WeakReference<PendingIntentRecord> ref;
4257 ref = mIntentSenderRecords.get(key);
4258 PendingIntentRecord rec = ref != null ? ref.get() : null;
4259 if (rec != null) {
4260 if (!cancelCurrent) {
4261 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004262 if (rec.key.requestIntent != null) {
4263 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4264 }
4265 if (intents != null) {
4266 intents[intents.length-1] = rec.key.requestIntent;
4267 rec.key.allIntents = intents;
4268 rec.key.allResolvedTypes = resolvedTypes;
4269 } else {
4270 rec.key.allIntents = null;
4271 rec.key.allResolvedTypes = null;
4272 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 return rec;
4275 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004276 rec.canceled = true;
4277 mIntentSenderRecords.remove(key);
4278 }
4279 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 return rec;
4281 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004282 rec = new PendingIntentRecord(this, key, callingUid);
4283 mIntentSenderRecords.put(key, rec.ref);
4284 if (type == INTENT_SENDER_ACTIVITY_RESULT) {
4285 if (activity.pendingResults == null) {
4286 activity.pendingResults
4287 = new HashSet<WeakReference<PendingIntentRecord>>();
4288 }
4289 activity.pendingResults.add(rec.ref);
4290 }
4291 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
4293
4294 public void cancelIntentSender(IIntentSender sender) {
4295 if (!(sender instanceof PendingIntentRecord)) {
4296 return;
4297 }
4298 synchronized(this) {
4299 PendingIntentRecord rec = (PendingIntentRecord)sender;
4300 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004301 int uid = AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 .getPackageUid(rec.key.packageName);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004303 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 String msg = "Permission Denial: cancelIntentSender() from pid="
4305 + Binder.getCallingPid()
4306 + ", uid=" + Binder.getCallingUid()
4307 + " is not allowed to cancel packges "
4308 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 throw new SecurityException(msg);
4311 }
4312 } catch (RemoteException e) {
4313 throw new SecurityException(e);
4314 }
4315 cancelIntentSenderLocked(rec, true);
4316 }
4317 }
4318
4319 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4320 rec.canceled = true;
4321 mIntentSenderRecords.remove(rec.key);
4322 if (cleanActivity && rec.key.activity != null) {
4323 rec.key.activity.pendingResults.remove(rec.ref);
4324 }
4325 }
4326
4327 public String getPackageForIntentSender(IIntentSender pendingResult) {
4328 if (!(pendingResult instanceof PendingIntentRecord)) {
4329 return null;
4330 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004331 try {
4332 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4333 return res.key.packageName;
4334 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 }
4336 return null;
4337 }
4338
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004339 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4340 if (!(pendingResult instanceof PendingIntentRecord)) {
4341 return false;
4342 }
4343 try {
4344 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4345 if (res.key.allIntents == null) {
4346 return false;
4347 }
4348 for (int i=0; i<res.key.allIntents.length; i++) {
4349 Intent intent = res.key.allIntents[i];
4350 if (intent.getPackage() != null && intent.getComponent() != null) {
4351 return false;
4352 }
4353 }
4354 return true;
4355 } catch (ClassCastException e) {
4356 }
4357 return false;
4358 }
4359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 public void setProcessLimit(int max) {
4361 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4362 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004363 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004364 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004365 mProcessLimitOverride = max;
4366 }
4367 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 }
4369
4370 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004371 synchronized (this) {
4372 return mProcessLimitOverride;
4373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 }
4375
4376 void foregroundTokenDied(ForegroundToken token) {
4377 synchronized (ActivityManagerService.this) {
4378 synchronized (mPidsSelfLocked) {
4379 ForegroundToken cur
4380 = mForegroundProcesses.get(token.pid);
4381 if (cur != token) {
4382 return;
4383 }
4384 mForegroundProcesses.remove(token.pid);
4385 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4386 if (pr == null) {
4387 return;
4388 }
4389 pr.forcingToForeground = null;
4390 pr.foregroundServices = false;
4391 }
4392 updateOomAdjLocked();
4393 }
4394 }
4395
4396 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4397 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4398 "setProcessForeground()");
4399 synchronized(this) {
4400 boolean changed = false;
4401
4402 synchronized (mPidsSelfLocked) {
4403 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004404 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004405 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 return;
4407 }
4408 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4409 if (oldToken != null) {
4410 oldToken.token.unlinkToDeath(oldToken, 0);
4411 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004412 if (pr != null) {
4413 pr.forcingToForeground = null;
4414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 changed = true;
4416 }
4417 if (isForeground && token != null) {
4418 ForegroundToken newToken = new ForegroundToken() {
4419 public void binderDied() {
4420 foregroundTokenDied(this);
4421 }
4422 };
4423 newToken.pid = pid;
4424 newToken.token = token;
4425 try {
4426 token.linkToDeath(newToken, 0);
4427 mForegroundProcesses.put(pid, newToken);
4428 pr.forcingToForeground = token;
4429 changed = true;
4430 } catch (RemoteException e) {
4431 // If the process died while doing this, we will later
4432 // do the cleanup with the process death link.
4433 }
4434 }
4435 }
4436
4437 if (changed) {
4438 updateOomAdjLocked();
4439 }
4440 }
4441 }
4442
4443 // =========================================================
4444 // PERMISSIONS
4445 // =========================================================
4446
4447 static class PermissionController extends IPermissionController.Stub {
4448 ActivityManagerService mActivityManagerService;
4449 PermissionController(ActivityManagerService activityManagerService) {
4450 mActivityManagerService = activityManagerService;
4451 }
4452
4453 public boolean checkPermission(String permission, int pid, int uid) {
4454 return mActivityManagerService.checkPermission(permission, pid,
4455 uid) == PackageManager.PERMISSION_GRANTED;
4456 }
4457 }
4458
4459 /**
4460 * This can be called with or without the global lock held.
4461 */
4462 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004463 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 // We might be performing an operation on behalf of an indirect binder
4465 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4466 // client identity accordingly before proceeding.
4467 Identity tlsIdentity = sCallerIdentity.get();
4468 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004469 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4471 uid = tlsIdentity.uid;
4472 pid = tlsIdentity.pid;
4473 }
4474
4475 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004476 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 return PackageManager.PERMISSION_GRANTED;
4478 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004479 // Isolated processes don't get any permissions.
4480 if (UserId.isIsolated(uid)) {
4481 return PackageManager.PERMISSION_DENIED;
4482 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004483 // If there is a uid that owns whatever is being accessed, it has
4484 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004485 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004486 return PackageManager.PERMISSION_GRANTED;
4487 }
4488 // If the target is not exported, then nobody else can get to it.
4489 if (!exported) {
4490 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 return PackageManager.PERMISSION_DENIED;
4492 }
4493 if (permission == null) {
4494 return PackageManager.PERMISSION_GRANTED;
4495 }
4496 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004497 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 .checkUidPermission(permission, uid);
4499 } catch (RemoteException e) {
4500 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004501 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503 return PackageManager.PERMISSION_DENIED;
4504 }
4505
4506 /**
4507 * As the only public entry point for permissions checking, this method
4508 * can enforce the semantic that requesting a check on a null global
4509 * permission is automatically denied. (Internally a null permission
4510 * string is used when calling {@link #checkComponentPermission} in cases
4511 * when only uid-based security is needed.)
4512 *
4513 * This can be called with or without the global lock held.
4514 */
4515 public int checkPermission(String permission, int pid, int uid) {
4516 if (permission == null) {
4517 return PackageManager.PERMISSION_DENIED;
4518 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004519 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521
4522 /**
4523 * Binder IPC calls go through the public entry point.
4524 * This can be called with or without the global lock held.
4525 */
4526 int checkCallingPermission(String permission) {
4527 return checkPermission(permission,
4528 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004529 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531
4532 /**
4533 * This can be called with or without the global lock held.
4534 */
4535 void enforceCallingPermission(String permission, String func) {
4536 if (checkCallingPermission(permission)
4537 == PackageManager.PERMISSION_GRANTED) {
4538 return;
4539 }
4540
4541 String msg = "Permission Denial: " + func + " from pid="
4542 + Binder.getCallingPid()
4543 + ", uid=" + Binder.getCallingUid()
4544 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004545 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 throw new SecurityException(msg);
4547 }
4548
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004549 /**
4550 * Determine if UID is holding permissions required to access {@link Uri} in
4551 * the given {@link ProviderInfo}. Final permission checking is always done
4552 * in {@link ContentProvider}.
4553 */
4554 private final boolean checkHoldingPermissionsLocked(
4555 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004556 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4557 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004558
4559 if (pi.applicationInfo.uid == uid) {
4560 return true;
4561 } else if (!pi.exported) {
4562 return false;
4563 }
4564
4565 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4566 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004568 // check if target holds top-level <provider> permissions
4569 if (!readMet && pi.readPermission != null
4570 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4571 readMet = true;
4572 }
4573 if (!writeMet && pi.writePermission != null
4574 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4575 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004577
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004578 // track if unprotected read/write is allowed; any denied
4579 // <path-permission> below removes this ability
4580 boolean allowDefaultRead = pi.readPermission == null;
4581 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004582
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004583 // check if target holds any <path-permission> that match uri
4584 final PathPermission[] pps = pi.pathPermissions;
4585 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004586 final String path = uri.getPath();
4587 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004588 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004589 i--;
4590 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004591 if (pp.match(path)) {
4592 if (!readMet) {
4593 final String pprperm = pp.getReadPermission();
4594 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4595 + pprperm + " for " + pp.getPath()
4596 + ": match=" + pp.match(path)
4597 + " check=" + pm.checkUidPermission(pprperm, uid));
4598 if (pprperm != null) {
4599 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4600 readMet = true;
4601 } else {
4602 allowDefaultRead = false;
4603 }
4604 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004605 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004606 if (!writeMet) {
4607 final String ppwperm = pp.getWritePermission();
4608 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4609 + ppwperm + " for " + pp.getPath()
4610 + ": match=" + pp.match(path)
4611 + " check=" + pm.checkUidPermission(ppwperm, uid));
4612 if (ppwperm != null) {
4613 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4614 writeMet = true;
4615 } else {
4616 allowDefaultWrite = false;
4617 }
4618 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004619 }
4620 }
4621 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004622 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004623
4624 // grant unprotected <provider> read/write, if not blocked by
4625 // <path-permission> above
4626 if (allowDefaultRead) readMet = true;
4627 if (allowDefaultWrite) writeMet = true;
4628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 } catch (RemoteException e) {
4630 return false;
4631 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004632
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004633 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 }
4635
4636 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4637 int modeFlags) {
4638 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004639 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 return true;
4641 }
4642 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4643 if (perms == null) return false;
4644 UriPermission perm = perms.get(uri);
4645 if (perm == null) return false;
4646 return (modeFlags&perm.modeFlags) == modeFlags;
4647 }
4648
4649 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004650 enforceNotIsolatedCaller("checkUriPermission");
4651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 // Another redirected-binder-call permissions check as in
4653 // {@link checkComponentPermission}.
4654 Identity tlsIdentity = sCallerIdentity.get();
4655 if (tlsIdentity != null) {
4656 uid = tlsIdentity.uid;
4657 pid = tlsIdentity.pid;
4658 }
4659
Amith Yamasani742a6712011-05-04 14:49:28 -07004660 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 // Our own process gets to do everything.
4662 if (pid == MY_PID) {
4663 return PackageManager.PERMISSION_GRANTED;
4664 }
4665 synchronized(this) {
4666 return checkUriPermissionLocked(uri, uid, modeFlags)
4667 ? PackageManager.PERMISSION_GRANTED
4668 : PackageManager.PERMISSION_DENIED;
4669 }
4670 }
4671
Dianne Hackborn39792d22010-08-19 18:01:52 -07004672 /**
4673 * Check if the targetPkg can be granted permission to access uri by
4674 * the callingUid using the given modeFlags. Throws a security exception
4675 * if callingUid is not allowed to do this. Returns the uid of the target
4676 * if the URI permission grant should be performed; returns -1 if it is not
4677 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004678 * If you already know the uid of the target, you can supply it in
4679 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004680 */
4681 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004682 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4684 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4685 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004686 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 }
4688
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004689 if (targetPkg != null) {
4690 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4691 "Checking grant " + targetPkg + " permission to " + uri);
4692 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004693
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004694 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695
4696 // If this is not a content: uri, we can't do anything with it.
4697 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004698 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004699 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004700 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 }
4702
4703 String name = uri.getAuthority();
4704 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004705 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4706 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 if (cpr != null) {
4708 pi = cpr.info;
4709 } else {
4710 try {
4711 pi = pm.resolveContentProvider(name,
4712 PackageManager.GET_URI_PERMISSION_PATTERNS);
4713 } catch (RemoteException ex) {
4714 }
4715 }
4716 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004717 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004718 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
4720
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004721 int targetUid = lastTargetUid;
4722 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004723 try {
4724 targetUid = pm.getPackageUid(targetPkg);
4725 if (targetUid < 0) {
4726 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4727 "Can't grant URI permission no uid for: " + targetPkg);
4728 return -1;
4729 }
4730 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004731 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 }
4734
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004735 if (targetUid >= 0) {
4736 // First... does the target actually need this permission?
4737 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4738 // No need to grant the target this permission.
4739 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4740 "Target " + targetPkg + " already has full permission to " + uri);
4741 return -1;
4742 }
4743 } else {
4744 // First... there is no target package, so can anyone access it?
4745 boolean allowed = pi.exported;
4746 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4747 if (pi.readPermission != null) {
4748 allowed = false;
4749 }
4750 }
4751 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4752 if (pi.writePermission != null) {
4753 allowed = false;
4754 }
4755 }
4756 if (allowed) {
4757 return -1;
4758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 }
4760
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004761 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 if (!pi.grantUriPermissions) {
4763 throw new SecurityException("Provider " + pi.packageName
4764 + "/" + pi.name
4765 + " does not allow granting of Uri permissions (uri "
4766 + uri + ")");
4767 }
4768 if (pi.uriPermissionPatterns != null) {
4769 final int N = pi.uriPermissionPatterns.length;
4770 boolean allowed = false;
4771 for (int i=0; i<N; i++) {
4772 if (pi.uriPermissionPatterns[i] != null
4773 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4774 allowed = true;
4775 break;
4776 }
4777 }
4778 if (!allowed) {
4779 throw new SecurityException("Provider " + pi.packageName
4780 + "/" + pi.name
4781 + " does not allow granting of permission to path of Uri "
4782 + uri);
4783 }
4784 }
4785
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004786 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004788 if (callingUid != Process.myUid()) {
4789 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4790 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4791 throw new SecurityException("Uid " + callingUid
4792 + " does not have permission to uri " + uri);
4793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 }
4795 }
4796
Dianne Hackborn39792d22010-08-19 18:01:52 -07004797 return targetUid;
4798 }
4799
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004800 public int checkGrantUriPermission(int callingUid, String targetPkg,
4801 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004802 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004803 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004804 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004805 }
4806 }
4807
Dianne Hackborn39792d22010-08-19 18:01:52 -07004808 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4809 Uri uri, int modeFlags, UriPermissionOwner owner) {
4810 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4811 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4812 if (modeFlags == 0) {
4813 return;
4814 }
4815
4816 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 // to the uri, and the target doesn't. Let's now give this to
4818 // the target.
4819
Joe Onorato8a9b2202010-02-26 18:56:32 -08004820 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004821 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 HashMap<Uri, UriPermission> targetUris
4824 = mGrantedUriPermissions.get(targetUid);
4825 if (targetUris == null) {
4826 targetUris = new HashMap<Uri, UriPermission>();
4827 mGrantedUriPermissions.put(targetUid, targetUris);
4828 }
4829
4830 UriPermission perm = targetUris.get(uri);
4831 if (perm == null) {
4832 perm = new UriPermission(targetUid, uri);
4833 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004837 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004839 } else {
4840 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4841 perm.readOwners.add(owner);
4842 owner.addReadPermission(perm);
4843 }
4844 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4845 perm.writeOwners.add(owner);
4846 owner.addWritePermission(perm);
4847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
4849 }
4850
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004851 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4852 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004853 if (targetPkg == null) {
4854 throw new NullPointerException("targetPkg");
4855 }
4856
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004857 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004858 if (targetUid < 0) {
4859 return;
4860 }
4861
4862 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4863 }
4864
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004865 static class NeededUriGrants extends ArrayList<Uri> {
4866 final String targetPkg;
4867 final int targetUid;
4868 final int flags;
4869
4870 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4871 targetPkg = _targetPkg;
4872 targetUid = _targetUid;
4873 flags = _flags;
4874 }
4875 }
4876
Dianne Hackborn39792d22010-08-19 18:01:52 -07004877 /**
4878 * Like checkGrantUriPermissionLocked, but takes an Intent.
4879 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004880 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4881 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004882 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004883 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4884 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004885 + " from " + intent + "; flags=0x"
4886 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4887
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004888 if (targetPkg == null) {
4889 throw new NullPointerException("targetPkg");
4890 }
4891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004893 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 }
4895 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004896 ClipData clip = intent.getClipData();
4897 if (data == null && clip == null) {
4898 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004899 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004900 if (data != null) {
4901 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4902 mode, needed != null ? needed.targetUid : -1);
4903 if (target > 0) {
4904 if (needed == null) {
4905 needed = new NeededUriGrants(targetPkg, target, mode);
4906 }
4907 needed.add(data);
4908 }
4909 }
4910 if (clip != null) {
4911 for (int i=0; i<clip.getItemCount(); i++) {
4912 Uri uri = clip.getItemAt(i).getUri();
4913 if (uri != null) {
4914 int target = -1;
4915 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
4916 mode, needed != null ? needed.targetUid : -1);
4917 if (target > 0) {
4918 if (needed == null) {
4919 needed = new NeededUriGrants(targetPkg, target, mode);
4920 }
4921 needed.add(uri);
4922 }
4923 } else {
4924 Intent clipIntent = clip.getItemAt(i).getIntent();
4925 if (clipIntent != null) {
4926 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
4927 callingUid, targetPkg, clipIntent, mode, needed);
4928 if (newNeeded != null) {
4929 needed = newNeeded;
4930 }
4931 }
4932 }
4933 }
4934 }
4935
4936 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004937 }
4938
4939 /**
4940 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
4941 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004942 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
4943 UriPermissionOwner owner) {
4944 if (needed != null) {
4945 for (int i=0; i<needed.size(); i++) {
4946 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
4947 needed.get(i), needed.flags, owner);
4948 }
4949 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004950 }
4951
4952 void grantUriPermissionFromIntentLocked(int callingUid,
4953 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004954 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08004955 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004956 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 return;
4958 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07004959
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004960 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004961 }
4962
4963 public void grantUriPermission(IApplicationThread caller, String targetPkg,
4964 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004965 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 synchronized(this) {
4967 final ProcessRecord r = getRecordForAppLocked(caller);
4968 if (r == null) {
4969 throw new SecurityException("Unable to find app for caller "
4970 + caller
4971 + " when granting permission to uri " + uri);
4972 }
4973 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004974 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 }
4976 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07004977 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004978 }
4979
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004980 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 null);
4982 }
4983 }
4984
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004985 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
4987 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
4988 HashMap<Uri, UriPermission> perms
4989 = mGrantedUriPermissions.get(perm.uid);
4990 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004991 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004992 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 perms.remove(perm.uri);
4994 if (perms.size() == 0) {
4995 mGrantedUriPermissions.remove(perm.uid);
4996 }
4997 }
4998 }
4999 }
5000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5002 int modeFlags) {
5003 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5004 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5005 if (modeFlags == 0) {
5006 return;
5007 }
5008
Joe Onorato8a9b2202010-02-26 18:56:32 -08005009 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005010 "Revoking all granted permissions to " + uri);
5011
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005012 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013
5014 final String authority = uri.getAuthority();
5015 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005016 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority,
5017 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 if (cpr != null) {
5019 pi = cpr.info;
5020 } else {
5021 try {
5022 pi = pm.resolveContentProvider(authority,
5023 PackageManager.GET_URI_PERMISSION_PATTERNS);
5024 } catch (RemoteException ex) {
5025 }
5026 }
5027 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005028 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 return;
5030 }
5031
5032 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005033 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 // Right now, if you are not the original owner of the permission,
5035 // you are not allowed to revoke it.
5036 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5037 throw new SecurityException("Uid " + callingUid
5038 + " does not have permission to uri " + uri);
5039 //}
5040 }
5041
5042 // Go through all of the permissions and remove any that match.
5043 final List<String> SEGMENTS = uri.getPathSegments();
5044 if (SEGMENTS != null) {
5045 final int NS = SEGMENTS.size();
5046 int N = mGrantedUriPermissions.size();
5047 for (int i=0; i<N; i++) {
5048 HashMap<Uri, UriPermission> perms
5049 = mGrantedUriPermissions.valueAt(i);
5050 Iterator<UriPermission> it = perms.values().iterator();
5051 toploop:
5052 while (it.hasNext()) {
5053 UriPermission perm = it.next();
5054 Uri targetUri = perm.uri;
5055 if (!authority.equals(targetUri.getAuthority())) {
5056 continue;
5057 }
5058 List<String> targetSegments = targetUri.getPathSegments();
5059 if (targetSegments == null) {
5060 continue;
5061 }
5062 if (targetSegments.size() < NS) {
5063 continue;
5064 }
5065 for (int j=0; j<NS; j++) {
5066 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5067 continue toploop;
5068 }
5069 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005070 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005071 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 perm.clearModes(modeFlags);
5073 if (perm.modeFlags == 0) {
5074 it.remove();
5075 }
5076 }
5077 if (perms.size() == 0) {
5078 mGrantedUriPermissions.remove(
5079 mGrantedUriPermissions.keyAt(i));
5080 N--;
5081 i--;
5082 }
5083 }
5084 }
5085 }
5086
5087 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5088 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005089 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 synchronized(this) {
5091 final ProcessRecord r = getRecordForAppLocked(caller);
5092 if (r == null) {
5093 throw new SecurityException("Unable to find app for caller "
5094 + caller
5095 + " when revoking permission to uri " + uri);
5096 }
5097 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005098 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 return;
5100 }
5101
5102 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5103 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5104 if (modeFlags == 0) {
5105 return;
5106 }
5107
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005108 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109
5110 final String authority = uri.getAuthority();
5111 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005112 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 if (cpr != null) {
5114 pi = cpr.info;
5115 } else {
5116 try {
5117 pi = pm.resolveContentProvider(authority,
5118 PackageManager.GET_URI_PERMISSION_PATTERNS);
5119 } catch (RemoteException ex) {
5120 }
5121 }
5122 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005123 Slog.w(TAG, "No content provider found for permission revoke: "
5124 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 return;
5126 }
5127
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005128 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 }
5130 }
5131
Dianne Hackborn7e269642010-08-25 19:50:20 -07005132 @Override
5133 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005134 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005135 synchronized(this) {
5136 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5137 return owner.getExternalTokenLocked();
5138 }
5139 }
5140
5141 @Override
5142 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5143 Uri uri, int modeFlags) {
5144 synchronized(this) {
5145 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5146 if (owner == null) {
5147 throw new IllegalArgumentException("Unknown owner: " + token);
5148 }
5149 if (fromUid != Binder.getCallingUid()) {
5150 if (Binder.getCallingUid() != Process.myUid()) {
5151 // Only system code can grant URI permissions on behalf
5152 // of other users.
5153 throw new SecurityException("nice try");
5154 }
5155 }
5156 if (targetPkg == null) {
5157 throw new IllegalArgumentException("null target");
5158 }
5159 if (uri == null) {
5160 throw new IllegalArgumentException("null uri");
5161 }
5162
5163 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5164 }
5165 }
5166
5167 @Override
5168 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5169 synchronized(this) {
5170 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5171 if (owner == null) {
5172 throw new IllegalArgumentException("Unknown owner: " + token);
5173 }
5174
5175 if (uri == null) {
5176 owner.removeUriPermissionsLocked(mode);
5177 } else {
5178 owner.removeUriPermissionLocked(uri, mode);
5179 }
5180 }
5181 }
5182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5184 synchronized (this) {
5185 ProcessRecord app =
5186 who != null ? getRecordForAppLocked(who) : null;
5187 if (app == null) return;
5188
5189 Message msg = Message.obtain();
5190 msg.what = WAIT_FOR_DEBUGGER_MSG;
5191 msg.obj = app;
5192 msg.arg1 = waiting ? 1 : 0;
5193 mHandler.sendMessage(msg);
5194 }
5195 }
5196
5197 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005198 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5199 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005201 outInfo.threshold = homeAppMem;
5202 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5203 outInfo.hiddenAppThreshold = hiddenAppMem;
5204 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005205 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005206 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5207 ProcessList.VISIBLE_APP_ADJ);
5208 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5209 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 }
5211
5212 // =========================================================
5213 // TASK MANAGEMENT
5214 // =========================================================
5215
5216 public List getTasks(int maxNum, int flags,
5217 IThumbnailReceiver receiver) {
5218 ArrayList list = new ArrayList();
5219
5220 PendingThumbnailsRecord pending = null;
5221 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005222 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223
5224 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005225 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5227 + ", receiver=" + receiver);
5228
5229 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5230 != PackageManager.PERMISSION_GRANTED) {
5231 if (receiver != null) {
5232 // If the caller wants to wait for pending thumbnails,
5233 // it ain't gonna get them.
5234 try {
5235 receiver.finished();
5236 } catch (RemoteException ex) {
5237 }
5238 }
5239 String msg = "Permission Denial: getTasks() from pid="
5240 + Binder.getCallingPid()
5241 + ", uid=" + Binder.getCallingUid()
5242 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005243 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 throw new SecurityException(msg);
5245 }
5246
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005247 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005248 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005249 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005250 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 TaskRecord curTask = null;
5252 int numActivities = 0;
5253 int numRunning = 0;
5254 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005255 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005257 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258
5259 // Initialize state for next task if needed.
5260 if (top == null ||
5261 (top.state == ActivityState.INITIALIZING
5262 && top.task == r.task)) {
5263 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 curTask = r.task;
5265 numActivities = numRunning = 0;
5266 }
5267
5268 // Add 'r' into the current task.
5269 numActivities++;
5270 if (r.app != null && r.app.thread != null) {
5271 numRunning++;
5272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273
Joe Onorato8a9b2202010-02-26 18:56:32 -08005274 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275 TAG, r.intent.getComponent().flattenToShortString()
5276 + ": task=" + r.task);
5277
5278 // If the next one is a different task, generate a new
5279 // TaskInfo entry for what we have.
5280 if (next == null || next.task != curTask) {
5281 ActivityManager.RunningTaskInfo ci
5282 = new ActivityManager.RunningTaskInfo();
5283 ci.id = curTask.taskId;
5284 ci.baseActivity = r.intent.getComponent();
5285 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005286 if (top.thumbHolder != null) {
5287 ci.description = top.thumbHolder.lastDescription;
5288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 ci.numActivities = numActivities;
5290 ci.numRunning = numRunning;
5291 //System.out.println(
5292 // "#" + maxNum + ": " + " descr=" + ci.description);
5293 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005294 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 TAG, "State=" + top.state + "Idle=" + top.idle
5296 + " app=" + top.app
5297 + " thr=" + (top.app != null ? top.app.thread : null));
5298 if (top.state == ActivityState.RESUMED
5299 || top.state == ActivityState.PAUSING) {
5300 if (top.idle && top.app != null
5301 && top.app.thread != null) {
5302 topRecord = top;
5303 topThumbnail = top.app.thread;
5304 } else {
5305 top.thumbnailNeeded = true;
5306 }
5307 }
5308 if (pending == null) {
5309 pending = new PendingThumbnailsRecord(receiver);
5310 }
5311 pending.pendingRecords.add(top);
5312 }
5313 list.add(ci);
5314 maxNum--;
5315 top = null;
5316 }
5317 }
5318
5319 if (pending != null) {
5320 mPendingThumbnails.add(pending);
5321 }
5322 }
5323
Joe Onorato8a9b2202010-02-26 18:56:32 -08005324 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325
5326 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005327 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005329 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005331 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005332 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 }
5334 }
5335
5336 if (pending == null && receiver != null) {
5337 // In this case all thumbnails were available and the client
5338 // is being asked to be told when the remaining ones come in...
5339 // which is unusually, since the top-most currently running
5340 // activity should never have a canned thumbnail! Oh well.
5341 try {
5342 receiver.finished();
5343 } catch (RemoteException ex) {
5344 }
5345 }
5346
5347 return list;
5348 }
5349
5350 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5351 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005352 final int callingUid = Binder.getCallingUid();
5353 // If it's the system uid asking, then use the current user id.
5354 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5355 // require the entire list.
5356 final int callingUserId = callingUid == Process.SYSTEM_UID
5357 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 synchronized (this) {
5359 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5360 "getRecentTasks()");
5361
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005362 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 final int N = mRecentTasks.size();
5365 ArrayList<ActivityManager.RecentTaskInfo> res
5366 = new ArrayList<ActivityManager.RecentTaskInfo>(
5367 maxNum < N ? maxNum : N);
5368 for (int i=0; i<N && maxNum > 0; i++) {
5369 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005370 // Only add calling user's recent tasks
5371 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005372 // Return the entry if desired by the caller. We always return
5373 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005374 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005375 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5376 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005377
Dianne Hackborn905577f2011-09-07 18:31:28 -07005378 if (i == 0
5379 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 || (tr.intent == null)
5381 || ((tr.intent.getFlags()
5382 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5383 ActivityManager.RecentTaskInfo rti
5384 = new ActivityManager.RecentTaskInfo();
5385 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005386 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 rti.baseIntent = new Intent(
5388 tr.intent != null ? tr.intent : tr.affinityIntent);
5389 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005390 rti.description = tr.lastDescription;
5391
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005392 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5393 // Check whether this activity is currently available.
5394 try {
5395 if (rti.origActivity != null) {
5396 if (pm.getActivityInfo(rti.origActivity, 0) == null) {
5397 continue;
5398 }
5399 } else if (rti.baseIntent != null) {
5400 if (pm.queryIntentActivities(rti.baseIntent,
5401 null, 0) == null) {
5402 continue;
5403 }
5404 }
5405 } catch (RemoteException e) {
5406 // Will never happen.
5407 }
5408 }
5409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 res.add(rti);
5411 maxNum--;
5412 }
5413 }
5414 return res;
5415 }
5416 }
5417
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005418 private TaskRecord taskForIdLocked(int id) {
5419 final int N = mRecentTasks.size();
5420 for (int i=0; i<N; i++) {
5421 TaskRecord tr = mRecentTasks.get(i);
5422 if (tr.taskId == id) {
5423 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005424 }
5425 }
5426 return null;
5427 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005428
5429 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5430 synchronized (this) {
5431 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5432 "getTaskThumbnails()");
5433 TaskRecord tr = taskForIdLocked(id);
5434 if (tr != null) {
5435 return mMainStack.getTaskThumbnailsLocked(tr);
5436 }
5437 }
5438 return null;
5439 }
5440
5441 public boolean removeSubTask(int taskId, int subTaskIndex) {
5442 synchronized (this) {
5443 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5444 "removeSubTask()");
5445 long ident = Binder.clearCallingIdentity();
5446 try {
5447 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex) != null;
5448 } finally {
5449 Binder.restoreCallingIdentity(ident);
5450 }
5451 }
5452 }
5453
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005454 private void cleanUpRemovedTaskLocked(ActivityRecord root, boolean killProcesses) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005455 TaskRecord tr = root.task;
5456 Intent baseIntent = new Intent(
5457 tr.intent != null ? tr.intent : tr.affinityIntent);
5458 ComponentName component = baseIntent.getComponent();
5459 if (component == null) {
5460 Slog.w(TAG, "Now component for base intent of task: " + tr);
5461 return;
5462 }
5463
5464 // Find any running services associated with this app.
5465 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07005466 for (ServiceRecord sr : mServiceMap.getAllServices(root.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005467 if (sr.packageName.equals(component.getPackageName())) {
5468 services.add(sr);
5469 }
5470 }
5471
5472 // Take care of any running services associated with the app.
5473 for (int i=0; i<services.size(); i++) {
5474 ServiceRecord sr = services.get(i);
5475 if (sr.startRequested) {
5476 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005477 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005478 stopServiceLocked(sr);
5479 } else {
5480 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005481 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005482 if (sr.app != null && sr.app.thread != null) {
5483 sendServiceArgsLocked(sr, false);
5484 }
5485 }
5486 }
5487 }
5488
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005489 if (killProcesses) {
5490 // Find any running processes associated with this app.
5491 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5492 SparseArray<ProcessRecord> appProcs
5493 = mProcessNames.getMap().get(component.getPackageName());
5494 if (appProcs != null) {
5495 for (int i=0; i<appProcs.size(); i++) {
5496 procs.add(appProcs.valueAt(i));
5497 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005498 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005499
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005500 // Kill the running processes.
5501 for (int i=0; i<procs.size(); i++) {
5502 ProcessRecord pr = procs.get(i);
5503 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5504 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5505 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5506 pr.processName, pr.setAdj, "remove task");
5507 Process.killProcessQuiet(pr.pid);
5508 } else {
5509 pr.waitingToKill = "remove task";
5510 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005511 }
5512 }
5513 }
5514
5515 public boolean removeTask(int taskId, int flags) {
5516 synchronized (this) {
5517 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5518 "removeTask()");
5519 long ident = Binder.clearCallingIdentity();
5520 try {
5521 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1);
5522 if (r != null) {
5523 mRecentTasks.remove(r.task);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005524 cleanUpRemovedTaskLocked(r,
5525 (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005526 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005527 } else {
5528 TaskRecord tr = null;
5529 int i=0;
5530 while (i < mRecentTasks.size()) {
5531 TaskRecord t = mRecentTasks.get(i);
5532 if (t.taskId == taskId) {
5533 tr = t;
5534 break;
5535 }
5536 i++;
5537 }
5538 if (tr != null) {
5539 if (tr.numActivities <= 0) {
5540 // Caller is just removing a recent task that is
5541 // not actively running. That is easy!
5542 mRecentTasks.remove(i);
5543 } else {
5544 Slog.w(TAG, "removeTask: task " + taskId
5545 + " does not have activities to remove, "
5546 + " but numActivities=" + tr.numActivities
5547 + ": " + tr);
5548 }
5549 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005550 }
5551 } finally {
5552 Binder.restoreCallingIdentity(ident);
5553 }
5554 }
5555 return false;
5556 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5559 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005560 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 TaskRecord jt = startTask;
5562
5563 // First look backwards
5564 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005565 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 if (r.task != jt) {
5567 jt = r.task;
5568 if (affinity.equals(jt.affinity)) {
5569 return j;
5570 }
5571 }
5572 }
5573
5574 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005575 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 jt = startTask;
5577 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005578 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 if (r.task != jt) {
5580 if (affinity.equals(jt.affinity)) {
5581 return j;
5582 }
5583 jt = r.task;
5584 }
5585 }
5586
5587 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005588 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 return N-1;
5590 }
5591
5592 return -1;
5593 }
5594
5595 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005596 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 */
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005598 public void moveTaskToFront(int task, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5600 "moveTaskToFront()");
5601
5602 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005603 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5604 Binder.getCallingUid(), "Task to front")) {
5605 return;
5606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 final long origId = Binder.clearCallingIdentity();
5608 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609 TaskRecord tr = taskForIdLocked(task);
5610 if (tr != null) {
5611 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5612 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005614 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5615 // Caller wants the home activity moved with it. To accomplish this,
5616 // we'll just move the home task to the top first.
5617 mMainStack.moveHomeToFrontLocked();
5618 }
5619 mMainStack.moveTaskToFrontLocked(tr, null);
5620 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005622 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5623 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005625 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5626 mMainStack.mUserLeaving = true;
5627 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005628 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5629 // Caller wants the home activity moved with it. To accomplish this,
5630 // we'll just move the home task to the top first.
5631 mMainStack.moveHomeToFrontLocked();
5632 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005633 mMainStack.moveTaskToFrontLocked(hr.task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 return;
5635 }
5636 }
5637 } finally {
5638 Binder.restoreCallingIdentity(origId);
5639 }
5640 }
5641 }
5642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 public void moveTaskToBack(int task) {
5644 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5645 "moveTaskToBack()");
5646
5647 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005648 if (mMainStack.mResumedActivity != null
5649 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005650 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5651 Binder.getCallingUid(), "Task to back")) {
5652 return;
5653 }
5654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005656 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 Binder.restoreCallingIdentity(origId);
5658 }
5659 }
5660
5661 /**
5662 * Moves an activity, and all of the other activities within the same task, to the bottom
5663 * of the history stack. The activity's order within the task is unchanged.
5664 *
5665 * @param token A reference to the activity we wish to move
5666 * @param nonRoot If false then this only works if the activity is the root
5667 * of a task; if true it will work for any activity in a task.
5668 * @return Returns true if the move completed, false if not.
5669 */
5670 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005671 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 synchronized(this) {
5673 final long origId = Binder.clearCallingIdentity();
5674 int taskId = getTaskForActivityLocked(token, !nonRoot);
5675 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005676 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 }
5678 Binder.restoreCallingIdentity(origId);
5679 }
5680 return false;
5681 }
5682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 public void moveTaskBackwards(int task) {
5684 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5685 "moveTaskBackwards()");
5686
5687 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005688 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5689 Binder.getCallingUid(), "Task backwards")) {
5690 return;
5691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 final long origId = Binder.clearCallingIdentity();
5693 moveTaskBackwardsLocked(task);
5694 Binder.restoreCallingIdentity(origId);
5695 }
5696 }
5697
5698 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005699 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 }
5701
5702 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5703 synchronized(this) {
5704 return getTaskForActivityLocked(token, onlyRoot);
5705 }
5706 }
5707
5708 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005709 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 TaskRecord lastTask = null;
5711 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005712 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005713 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 if (!onlyRoot || lastTask != r.task) {
5715 return r.task.taskId;
5716 }
5717 return -1;
5718 }
5719 lastTask = r.task;
5720 }
5721
5722 return -1;
5723 }
5724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 // =========================================================
5726 // THUMBNAILS
5727 // =========================================================
5728
5729 public void reportThumbnail(IBinder token,
5730 Bitmap thumbnail, CharSequence description) {
5731 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5732 final long origId = Binder.clearCallingIdentity();
5733 sendPendingThumbnail(null, token, thumbnail, description, true);
5734 Binder.restoreCallingIdentity(origId);
5735 }
5736
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005737 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 Bitmap thumbnail, CharSequence description, boolean always) {
5739 TaskRecord task = null;
5740 ArrayList receivers = null;
5741
5742 //System.out.println("Send pending thumbnail: " + r);
5743
5744 synchronized(this) {
5745 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005746 r = mMainStack.isInStackLocked(token);
5747 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 return;
5749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005751 if (thumbnail == null && r.thumbHolder != null) {
5752 thumbnail = r.thumbHolder.lastThumbnail;
5753 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 if (thumbnail == null && !always) {
5756 // If there is no thumbnail, and this entry is not actually
5757 // going away, then abort for now and pick up the next
5758 // thumbnail we get.
5759 return;
5760 }
5761 task = r.task;
5762
5763 int N = mPendingThumbnails.size();
5764 int i=0;
5765 while (i<N) {
5766 PendingThumbnailsRecord pr =
5767 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5768 //System.out.println("Looking in " + pr.pendingRecords);
5769 if (pr.pendingRecords.remove(r)) {
5770 if (receivers == null) {
5771 receivers = new ArrayList();
5772 }
5773 receivers.add(pr);
5774 if (pr.pendingRecords.size() == 0) {
5775 pr.finished = true;
5776 mPendingThumbnails.remove(i);
5777 N--;
5778 continue;
5779 }
5780 }
5781 i++;
5782 }
5783 }
5784
5785 if (receivers != null) {
5786 final int N = receivers.size();
5787 for (int i=0; i<N; i++) {
5788 try {
5789 PendingThumbnailsRecord pr =
5790 (PendingThumbnailsRecord)receivers.get(i);
5791 pr.receiver.newThumbnail(
5792 task != null ? task.taskId : -1, thumbnail, description);
5793 if (pr.finished) {
5794 pr.receiver.finished();
5795 }
5796 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005797 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 }
5799 }
5800 }
5801 }
5802
5803 // =========================================================
5804 // CONTENT PROVIDERS
5805 // =========================================================
5806
Jeff Brown10e89712011-07-08 18:52:57 -07005807 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5808 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005810 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005811 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005812 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 } catch (RemoteException ex) {
5814 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005815 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005816 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5817 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 if (providers != null) {
5819 final int N = providers.size();
5820 for (int i=0; i<N; i++) {
5821 ProviderInfo cpi =
5822 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005823
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005824 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005825 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005827 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005828 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005830 if (DEBUG_MU)
5831 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 app.pubProviders.put(cpi.name, cpr);
5833 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005834 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
5836 }
5837 return providers;
5838 }
5839
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005840 /**
5841 * Check if {@link ProcessRecord} has a possible chance at accessing the
5842 * given {@link ProviderInfo}. Final permission checking is always done
5843 * in {@link ContentProvider}.
5844 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005846 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005848 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005850 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005851 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 return null;
5853 }
5854 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005855 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 == PackageManager.PERMISSION_GRANTED) {
5857 return null;
5858 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005859
5860 PathPermission[] pps = cpi.pathPermissions;
5861 if (pps != null) {
5862 int i = pps.length;
5863 while (i > 0) {
5864 i--;
5865 PathPermission pp = pps[i];
5866 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005867 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005868 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005869 return null;
5870 }
5871 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005872 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005873 == PackageManager.PERMISSION_GRANTED) {
5874 return null;
5875 }
5876 }
5877 }
5878
Dianne Hackbornb424b632010-08-18 15:59:05 -07005879 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5880 if (perms != null) {
5881 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5882 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5883 return null;
5884 }
5885 }
5886 }
5887
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005888 String msg;
5889 if (!cpi.exported) {
5890 msg = "Permission Denial: opening provider " + cpi.name
5891 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5892 + ", uid=" + callingUid + ") that is not exported from uid "
5893 + cpi.applicationInfo.uid;
5894 } else {
5895 msg = "Permission Denial: opening provider " + cpi.name
5896 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5897 + ", uid=" + callingUid + ") requires "
5898 + cpi.readPermission + " or " + cpi.writePermission;
5899 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005900 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 return msg;
5902 }
5903
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005904 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5905 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005906 if (r != null) {
5907 Integer cnt = r.conProviders.get(cpr);
5908 if (DEBUG_PROVIDER) Slog.v(TAG,
5909 "Adding provider requested by "
5910 + r.processName + " from process "
5911 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5912 + " cnt=" + (cnt == null ? 1 : cnt));
5913 if (cnt == null) {
5914 cpr.clients.add(r);
5915 r.conProviders.put(cpr, new Integer(1));
5916 return true;
5917 } else {
5918 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
5919 }
5920 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005921 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005922 }
5923 return false;
5924 }
5925
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005926 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
5927 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005928 if (r != null) {
5929 Integer cnt = r.conProviders.get(cpr);
5930 if (DEBUG_PROVIDER) Slog.v(TAG,
5931 "Removing provider requested by "
5932 + r.processName + " from process "
5933 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
5934 + " cnt=" + cnt);
5935 if (cnt == null || cnt.intValue() <= 1) {
5936 cpr.clients.remove(r);
5937 r.conProviders.remove(cpr);
5938 return true;
5939 } else {
5940 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
5941 }
5942 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005943 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005944 }
5945 return false;
5946 }
5947
Amith Yamasani742a6712011-05-04 14:49:28 -07005948 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005949 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 ContentProviderRecord cpr;
5951 ProviderInfo cpi = null;
5952
5953 synchronized(this) {
5954 ProcessRecord r = null;
5955 if (caller != null) {
5956 r = getRecordForAppLocked(caller);
5957 if (r == null) {
5958 throw new SecurityException(
5959 "Unable to find app for caller " + caller
5960 + " (pid=" + Binder.getCallingPid()
5961 + ") when getting content provider " + name);
5962 }
5963 }
5964
5965 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005966 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07005967 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005968 boolean providerRunning = cpr != null;
5969 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07005971 String msg;
5972 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
5973 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 }
5975
5976 if (r != null && cpr.canRunHere(r)) {
5977 // This provider has been published or is in the process
5978 // of being published... but it is also allowed to run
5979 // in the caller's process, so don't make a connection
5980 // and just let the caller instantiate its own instance.
5981 if (cpr.provider != null) {
5982 // don't give caller the provider object, it needs
5983 // to make its own.
5984 cpr = new ContentProviderRecord(cpr);
5985 }
5986 return cpr;
5987 }
5988
5989 final long origId = Binder.clearCallingIdentity();
5990
Dianne Hackborna1e989b2009-09-01 19:54:29 -07005991 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005992 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005993 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07005994 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07005995 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005996 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07005997 // make sure to count it as being accessed and thus
5998 // back up on the LRU list. This is good because
5999 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006000 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006001 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006002 }
6003
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006004 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006005 if (false) {
6006 if (cpr.name.flattenToShortString().equals(
6007 "com.android.providers.calendar/.CalendarProvider2")) {
6008 Slog.v(TAG, "****************** KILLING "
6009 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006010 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006011 }
6012 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006013 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006014 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6015 // NOTE: there is still a race here where a signal could be
6016 // pending on the process even though we managed to update its
6017 // adj level. Not sure what to do about this, but at least
6018 // the race is now smaller.
6019 if (!success) {
6020 // Uh oh... it looks like the provider's process
6021 // has been killed on us. We need to wait for a new
6022 // process to be started, and make sure its death
6023 // doesn't kill our process.
6024 Slog.i(TAG,
6025 "Existing provider " + cpr.name.flattenToShortString()
6026 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006027 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006028 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006029 if (!lastRef) {
6030 // This wasn't the last ref our process had on
6031 // the provider... we have now been killed, bail.
6032 return null;
6033 }
6034 providerRunning = false;
6035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 }
6037
6038 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006041 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006043 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006044 resolveContentProvider(name,
6045 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 } catch (RemoteException ex) {
6047 }
6048 if (cpi == null) {
6049 return null;
6050 }
6051
Amith Yamasani742a6712011-05-04 14:49:28 -07006052 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo,
6053 Binder.getOrigCallingUser());
6054
Dianne Hackbornb424b632010-08-18 15:59:05 -07006055 String msg;
6056 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6057 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 }
6059
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006060 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006061 && !cpi.processName.equals("system")) {
6062 // If this content provider does not run in the system
6063 // process, and the system is not yet ready to run other
6064 // processes, then fail fast instead of hanging.
6065 throw new IllegalArgumentException(
6066 "Attempt to launch content provider before system ready");
6067 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006068
6069 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006070 cpr = mProviderMap.getProviderByClass(comp, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 final boolean firstClass = cpr == null;
6072 if (firstClass) {
6073 try {
6074 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006075 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 getApplicationInfo(
6077 cpi.applicationInfo.packageName,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006078 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006080 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 + cpi.name);
6082 return null;
6083 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006084 ai = getAppInfoForUser(ai, Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006085 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 } catch (RemoteException ex) {
6087 // pm is in same process, this will never happen.
6088 }
6089 }
6090
6091 if (r != null && cpr.canRunHere(r)) {
6092 // If this is a multiprocess provider, then just return its
6093 // info and allow the caller to instantiate it. Only do
6094 // this if the provider is the same user as the caller's
6095 // process, or can run as root (so can be in any process).
6096 return cpr;
6097 }
6098
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006099 if (DEBUG_PROVIDER) {
6100 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006101 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006102 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 }
6104
6105 // This is single process, and our app is now connecting to it.
6106 // See if we are already in the process of launching this
6107 // provider.
6108 final int N = mLaunchingProviders.size();
6109 int i;
6110 for (i=0; i<N; i++) {
6111 if (mLaunchingProviders.get(i) == cpr) {
6112 break;
6113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 }
6115
6116 // If the provider is not already being launched, then get it
6117 // started.
6118 if (i >= N) {
6119 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006120
6121 try {
6122 // Content provider is now in use, its package can't be stopped.
6123 try {
6124 AppGlobals.getPackageManager().setPackageStoppedState(
6125 cpr.appInfo.packageName, false);
6126 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006127 } catch (IllegalArgumentException e) {
6128 Slog.w(TAG, "Failed trying to unstop package "
6129 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006130 }
6131
6132 ProcessRecord proc = startProcessLocked(cpi.processName,
6133 cpr.appInfo, false, 0, "content provider",
6134 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006135 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006136 if (proc == null) {
6137 Slog.w(TAG, "Unable to launch app "
6138 + cpi.applicationInfo.packageName + "/"
6139 + cpi.applicationInfo.uid + " for provider "
6140 + name + ": process is bad");
6141 return null;
6142 }
6143 cpr.launchingApp = proc;
6144 mLaunchingProviders.add(cpr);
6145 } finally {
6146 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
6150 // Make sure the provider is published (the same provider class
6151 // may be published under multiple names).
6152 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006153 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006155
Amith Yamasani742a6712011-05-04 14:49:28 -07006156 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006157 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 }
6159 }
6160
6161 // Wait for the provider to be published...
6162 synchronized (cpr) {
6163 while (cpr.provider == null) {
6164 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006165 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 + cpi.applicationInfo.packageName + "/"
6167 + cpi.applicationInfo.uid + " for provider "
6168 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006169 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 cpi.applicationInfo.packageName,
6171 cpi.applicationInfo.uid, name);
6172 return null;
6173 }
6174 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006175 if (DEBUG_MU) {
6176 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6177 + cpr.launchingApp);
6178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 cpr.wait();
6180 } catch (InterruptedException ex) {
6181 }
6182 }
6183 }
6184 return cpr;
6185 }
6186
6187 public final ContentProviderHolder getContentProvider(
6188 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006189 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 if (caller == null) {
6191 String msg = "null IApplicationThread when getting content provider "
6192 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006193 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 throw new SecurityException(msg);
6195 }
6196
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006197 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 }
6199
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006200 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6201 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6202 "Do not have permission in call getContentProviderExternal()");
6203 return getContentProviderExternalUnchecked(name, token);
6204 }
6205
6206 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6207 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
6209
6210 /**
6211 * Drop a content provider from a ProcessRecord's bookkeeping
6212 * @param cpr
6213 */
6214 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006215 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006217 int userId = UserId.getUserId(Binder.getCallingUid());
6218 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006220 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006221 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006222 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 return;
6224 }
6225 final ProcessRecord r = getRecordForAppLocked(caller);
6226 if (r == null) {
6227 throw new SecurityException(
6228 "Unable to find app for caller " + caller +
6229 " when removing content provider " + name);
6230 }
6231 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006232 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006233 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6234 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6235 + r.info.processName + " from process "
6236 + localCpr.appInfo.processName);
6237 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006239 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006240 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 return;
6242 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006243 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006244 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 }
6248 }
6249
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006250 public void removeContentProviderExternal(String name, IBinder token) {
6251 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6252 "Do not have permission in call removeContentProviderExternal()");
6253 removeContentProviderExternalUnchecked(name, token);
6254 }
6255
6256 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006258 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6259 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 if(cpr == null) {
6261 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006262 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 return;
6264 }
6265
6266 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006267 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006268 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6269 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006270 if (localCpr.hasExternalProcessHandles()) {
6271 if (localCpr.removeExternalProcessHandleLocked(token)) {
6272 updateOomAdjLocked();
6273 } else {
6274 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6275 + " with no external reference for token: "
6276 + token + ".");
6277 }
6278 } else {
6279 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6280 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
6283 }
6284
6285 public final void publishContentProviders(IApplicationThread caller,
6286 List<ContentProviderHolder> providers) {
6287 if (providers == null) {
6288 return;
6289 }
6290
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006291 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 synchronized(this) {
6293 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006294 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006295 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 if (r == null) {
6297 throw new SecurityException(
6298 "Unable to find app for caller " + caller
6299 + " (pid=" + Binder.getCallingPid()
6300 + ") when publishing content providers");
6301 }
6302
6303 final long origId = Binder.clearCallingIdentity();
6304
6305 final int N = providers.size();
6306 for (int i=0; i<N; i++) {
6307 ContentProviderHolder src = providers.get(i);
6308 if (src == null || src.info == null || src.provider == null) {
6309 continue;
6310 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006311 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006312 if (DEBUG_MU)
6313 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006315 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006316 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 String names[] = dst.info.authority.split(";");
6318 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006319 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 }
6321
6322 int NL = mLaunchingProviders.size();
6323 int j;
6324 for (j=0; j<NL; j++) {
6325 if (mLaunchingProviders.get(j) == dst) {
6326 mLaunchingProviders.remove(j);
6327 j--;
6328 NL--;
6329 }
6330 }
6331 synchronized (dst) {
6332 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006333 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 dst.notifyAll();
6335 }
6336 updateOomAdjLocked(r);
6337 }
6338 }
6339
6340 Binder.restoreCallingIdentity(origId);
6341 }
6342 }
6343
6344 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006345 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006346 synchronized (mSelf) {
6347 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6348 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006349 if (providers != null) {
6350 for (int i=providers.size()-1; i>=0; i--) {
6351 ProviderInfo pi = (ProviderInfo)providers.get(i);
6352 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6353 Slog.w(TAG, "Not installing system proc provider " + pi.name
6354 + ": not system .apk");
6355 providers.remove(i);
6356 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006357 }
6358 }
6359 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006360 if (providers != null) {
6361 mSystemThread.installSystemProviders(providers);
6362 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006363
6364 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006365
6366 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 }
6368
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006369 /**
6370 * Allows app to retrieve the MIME type of a URI without having permission
6371 * to access its content provider.
6372 *
6373 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6374 *
6375 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6376 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6377 */
6378 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006379 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006380 final String name = uri.getAuthority();
6381 final long ident = Binder.clearCallingIdentity();
6382 ContentProviderHolder holder = null;
6383
6384 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006385 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006386 if (holder != null) {
6387 return holder.provider.getType(uri);
6388 }
6389 } catch (RemoteException e) {
6390 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6391 return null;
6392 } finally {
6393 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006394 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006395 }
6396 Binder.restoreCallingIdentity(ident);
6397 }
6398
6399 return null;
6400 }
6401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 // =========================================================
6403 // GLOBAL MANAGEMENT
6404 // =========================================================
6405
6406 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006407 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 String proc = customProcess != null ? customProcess : info.processName;
6409 BatteryStatsImpl.Uid.Proc ps = null;
6410 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006411 int uid = info.uid;
6412 if (isolated) {
6413 int userId = UserId.getUserId(uid);
6414 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6415 uid = 0;
6416 while (true) {
6417 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6418 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6419 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6420 }
6421 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6422 mNextIsolatedProcessUid++;
6423 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6424 // No process for this uid, use it.
6425 break;
6426 }
6427 stepsLeft--;
6428 if (stepsLeft <= 0) {
6429 return null;
6430 }
6431 }
6432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 synchronized (stats) {
6434 ps = stats.getProcessStatsLocked(info.uid, proc);
6435 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006436 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 }
6438
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006439 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6440 ProcessRecord app;
6441 if (!isolated) {
6442 app = getProcessRecordLocked(info.processName, info.uid);
6443 } else {
6444 app = null;
6445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446
6447 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006448 app = newProcessRecordLocked(null, info, null, isolated);
6449 mProcessNames.put(info.processName, app.uid, app);
6450 if (isolated) {
6451 mIsolatedProcesses.put(app.uid, app);
6452 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006453 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455
Dianne Hackborne7f97212011-02-24 14:40:20 -08006456 // This package really, really can not be stopped.
6457 try {
6458 AppGlobals.getPackageManager().setPackageStoppedState(
6459 info.packageName, false);
6460 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006461 } catch (IllegalArgumentException e) {
6462 Slog.w(TAG, "Failed trying to unstop package "
6463 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006464 }
6465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6467 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6468 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006469 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 }
6471 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6472 mPersistentStartingProcesses.add(app);
6473 startProcessLocked(app, "added application", app.processName);
6474 }
6475
6476 return app;
6477 }
6478
6479 public void unhandledBack() {
6480 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6481 "unhandledBack()");
6482
6483 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006484 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006485 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 TAG, "Performing unhandledBack(): stack size = " + count);
6487 if (count > 1) {
6488 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006489 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6491 Binder.restoreCallingIdentity(origId);
6492 }
6493 }
6494 }
6495
6496 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006497 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006499 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 ParcelFileDescriptor pfd = null;
6501 if (cph != null) {
6502 // We record the binder invoker's uid in thread-local storage before
6503 // going to the content provider to open the file. Later, in the code
6504 // that handles all permissions checks, we look for this uid and use
6505 // that rather than the Activity Manager's own uid. The effect is that
6506 // we do the check against the caller's permissions even though it looks
6507 // to the content provider like the Activity Manager itself is making
6508 // the request.
6509 sCallerIdentity.set(new Identity(
6510 Binder.getCallingPid(), Binder.getCallingUid()));
6511 try {
6512 pfd = cph.provider.openFile(uri, "r");
6513 } catch (FileNotFoundException e) {
6514 // do nothing; pfd will be returned null
6515 } finally {
6516 // Ensure that whatever happens, we clean up the identity state
6517 sCallerIdentity.remove();
6518 }
6519
6520 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006521 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006523 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525 return pfd;
6526 }
6527
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006528 // Actually is sleeping or shutting down or whatever else in the future
6529 // is an inactive state.
6530 public boolean isSleeping() {
6531 return mSleeping || mShuttingDown;
6532 }
6533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 public void goingToSleep() {
6535 synchronized(this) {
6536 mSleeping = true;
6537 mWindowManager.setEventDispatching(false);
6538
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006539 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006540
6541 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006542 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006543 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6544 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006545 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 }
6547 }
6548
Dianne Hackborn55280a92009-05-07 15:53:46 -07006549 public boolean shutdown(int timeout) {
6550 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6551 != PackageManager.PERMISSION_GRANTED) {
6552 throw new SecurityException("Requires permission "
6553 + android.Manifest.permission.SHUTDOWN);
6554 }
6555
6556 boolean timedout = false;
6557
6558 synchronized(this) {
6559 mShuttingDown = true;
6560 mWindowManager.setEventDispatching(false);
6561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006562 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006563 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006564 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006565 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006566 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006567 long delay = endTime - System.currentTimeMillis();
6568 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006569 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006570 timedout = true;
6571 break;
6572 }
6573 try {
6574 this.wait();
6575 } catch (InterruptedException e) {
6576 }
6577 }
6578 }
6579 }
6580
6581 mUsageStatsService.shutdown();
6582 mBatteryStatsService.shutdown();
6583
6584 return timedout;
6585 }
6586
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006587 public final void activitySlept(IBinder token) {
6588 if (localLOGV) Slog.v(
6589 TAG, "Activity slept: token=" + token);
6590
6591 ActivityRecord r = null;
6592
6593 final long origId = Binder.clearCallingIdentity();
6594
6595 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006596 r = mMainStack.isInStackLocked(token);
6597 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006598 mMainStack.activitySleptLocked(r);
6599 }
6600 }
6601
6602 Binder.restoreCallingIdentity(origId);
6603 }
6604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 public void wakingUp() {
6606 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 mWindowManager.setEventDispatching(true);
6608 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006609 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006610 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 }
6612 }
6613
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006614 public void stopAppSwitches() {
6615 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6616 != PackageManager.PERMISSION_GRANTED) {
6617 throw new SecurityException("Requires permission "
6618 + android.Manifest.permission.STOP_APP_SWITCHES);
6619 }
6620
6621 synchronized(this) {
6622 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6623 + APP_SWITCH_DELAY_TIME;
6624 mDidAppSwitch = false;
6625 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6626 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6627 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6628 }
6629 }
6630
6631 public void resumeAppSwitches() {
6632 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6633 != PackageManager.PERMISSION_GRANTED) {
6634 throw new SecurityException("Requires permission "
6635 + android.Manifest.permission.STOP_APP_SWITCHES);
6636 }
6637
6638 synchronized(this) {
6639 // Note that we don't execute any pending app switches... we will
6640 // let those wait until either the timeout, or the next start
6641 // activity request.
6642 mAppSwitchesAllowedTime = 0;
6643 }
6644 }
6645
6646 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6647 String name) {
6648 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6649 return true;
6650 }
6651
6652 final int perm = checkComponentPermission(
6653 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006654 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006655 if (perm == PackageManager.PERMISSION_GRANTED) {
6656 return true;
6657 }
6658
Joe Onorato8a9b2202010-02-26 18:56:32 -08006659 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006660 return false;
6661 }
6662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 public void setDebugApp(String packageName, boolean waitForDebugger,
6664 boolean persistent) {
6665 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6666 "setDebugApp()");
6667
6668 // Note that this is not really thread safe if there are multiple
6669 // callers into it at the same time, but that's not a situation we
6670 // care about.
6671 if (persistent) {
6672 final ContentResolver resolver = mContext.getContentResolver();
6673 Settings.System.putString(
6674 resolver, Settings.System.DEBUG_APP,
6675 packageName);
6676 Settings.System.putInt(
6677 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6678 waitForDebugger ? 1 : 0);
6679 }
6680
6681 synchronized (this) {
6682 if (!persistent) {
6683 mOrigDebugApp = mDebugApp;
6684 mOrigWaitForDebugger = mWaitForDebugger;
6685 }
6686 mDebugApp = packageName;
6687 mWaitForDebugger = waitForDebugger;
6688 mDebugTransient = !persistent;
6689 if (packageName != null) {
6690 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -07006691 forceStopPackageLocked(packageName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 Binder.restoreCallingIdentity(origId);
6693 }
6694 }
6695 }
6696
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006697 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6698 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6699 synchronized (this) {
6700 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6701 if (!isDebuggable) {
6702 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6703 throw new SecurityException("Process not debuggable: " + app.packageName);
6704 }
6705 }
6706 mProfileApp = processName;
6707 mProfileFile = profileFile;
6708 if (mProfileFd != null) {
6709 try {
6710 mProfileFd.close();
6711 } catch (IOException e) {
6712 }
6713 mProfileFd = null;
6714 }
6715 mProfileFd = profileFd;
6716 mProfileType = 0;
6717 mAutoStopProfiler = autoStopProfiler;
6718 }
6719 }
6720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 public void setAlwaysFinish(boolean enabled) {
6722 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6723 "setAlwaysFinish()");
6724
6725 Settings.System.putInt(
6726 mContext.getContentResolver(),
6727 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6728
6729 synchronized (this) {
6730 mAlwaysFinishActivities = enabled;
6731 }
6732 }
6733
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006734 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006736 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006738 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 }
6740 }
6741
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006742 public boolean isUserAMonkey() {
6743 // For now the fact that there is a controller implies
6744 // we have a monkey.
6745 synchronized (this) {
6746 return mController != null;
6747 }
6748 }
6749
Jeff Sharkeya4620792011-05-20 15:29:23 -07006750 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006751 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6752 "registerProcessObserver()");
6753 synchronized (this) {
6754 mProcessObservers.register(observer);
6755 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006756 }
6757
6758 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006759 synchronized (this) {
6760 mProcessObservers.unregister(observer);
6761 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006762 }
6763
Daniel Sandler69a48172010-06-23 16:29:36 -04006764 public void setImmersive(IBinder token, boolean immersive) {
6765 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006766 ActivityRecord r = mMainStack.isInStackLocked(token);
6767 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006768 throw new IllegalArgumentException();
6769 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006770 r.immersive = immersive;
6771 }
6772 }
6773
6774 public boolean isImmersive(IBinder token) {
6775 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006776 ActivityRecord r = mMainStack.isInStackLocked(token);
6777 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006778 throw new IllegalArgumentException();
6779 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006780 return r.immersive;
6781 }
6782 }
6783
6784 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006785 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006786 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006787 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006788 return (r != null) ? r.immersive : false;
6789 }
6790 }
6791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 public final void enterSafeMode() {
6793 synchronized(this) {
6794 // It only makes sense to do this before the system is ready
6795 // and started launching other packages.
6796 if (!mSystemReady) {
6797 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006798 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 } catch (RemoteException e) {
6800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
6802 }
6803 }
6804
Jeff Brownb09abc12011-01-13 21:08:27 -08006805 public final void showSafeModeOverlay() {
6806 View v = LayoutInflater.from(mContext).inflate(
6807 com.android.internal.R.layout.safe_mode, null);
6808 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6809 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6810 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6811 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6812 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6813 lp.format = v.getBackground().getOpacity();
6814 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6815 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6816 ((WindowManager)mContext.getSystemService(
6817 Context.WINDOW_SERVICE)).addView(v, lp);
6818 }
6819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 public void noteWakeupAlarm(IIntentSender sender) {
6821 if (!(sender instanceof PendingIntentRecord)) {
6822 return;
6823 }
6824 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6825 synchronized (stats) {
6826 if (mBatteryStatsService.isOnBattery()) {
6827 mBatteryStatsService.enforceCallingPermission();
6828 PendingIntentRecord rec = (PendingIntentRecord)sender;
6829 int MY_UID = Binder.getCallingUid();
6830 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6831 BatteryStatsImpl.Uid.Pkg pkg =
6832 stats.getPackageStatsLocked(uid, rec.key.packageName);
6833 pkg.incWakeupsLocked();
6834 }
6835 }
6836 }
6837
Dianne Hackborn64825172011-03-02 21:32:58 -08006838 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006840 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006842 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 // XXX Note: don't acquire main activity lock here, because the window
6844 // manager calls in with its locks held.
6845
6846 boolean killed = false;
6847 synchronized (mPidsSelfLocked) {
6848 int[] types = new int[pids.length];
6849 int worstType = 0;
6850 for (int i=0; i<pids.length; i++) {
6851 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6852 if (proc != null) {
6853 int type = proc.setAdj;
6854 types[i] = type;
6855 if (type > worstType) {
6856 worstType = type;
6857 }
6858 }
6859 }
6860
Dianne Hackborn64825172011-03-02 21:32:58 -08006861 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006863 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6864 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006865 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006866 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006867
6868 // If this is not a secure call, don't let it kill processes that
6869 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006870 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6871 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006872 }
6873
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006874 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 for (int i=0; i<pids.length; i++) {
6876 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6877 if (proc == null) {
6878 continue;
6879 }
6880 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006881 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006882 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006883 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6884 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006886 proc.killedBackground = true;
6887 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 }
6889 }
6890 }
6891 return killed;
6892 }
6893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 public final void startRunning(String pkg, String cls, String action,
6895 String data) {
6896 synchronized(this) {
6897 if (mStartRunning) {
6898 return;
6899 }
6900 mStartRunning = true;
6901 mTopComponent = pkg != null && cls != null
6902 ? new ComponentName(pkg, cls) : null;
6903 mTopAction = action != null ? action : Intent.ACTION_MAIN;
6904 mTopData = data;
6905 if (!mSystemReady) {
6906 return;
6907 }
6908 }
6909
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07006910 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006911 }
6912
6913 private void retrieveSettings() {
6914 final ContentResolver resolver = mContext.getContentResolver();
6915 String debugApp = Settings.System.getString(
6916 resolver, Settings.System.DEBUG_APP);
6917 boolean waitForDebugger = Settings.System.getInt(
6918 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
6919 boolean alwaysFinishActivities = Settings.System.getInt(
6920 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
6921
6922 Configuration configuration = new Configuration();
6923 Settings.System.getConfiguration(resolver, configuration);
6924
6925 synchronized (this) {
6926 mDebugApp = mOrigDebugApp = debugApp;
6927 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
6928 mAlwaysFinishActivities = alwaysFinishActivities;
6929 // This happens before any activities are started, so we can
6930 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08006931 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08006932 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 }
6934 }
6935
6936 public boolean testIsSystemReady() {
6937 // no need to synchronize(this) just to read & return the value
6938 return mSystemReady;
6939 }
6940
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006941 private static File getCalledPreBootReceiversFile() {
6942 File dataDir = Environment.getDataDirectory();
6943 File systemDir = new File(dataDir, "system");
6944 File fname = new File(systemDir, "called_pre_boots.dat");
6945 return fname;
6946 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07006947
6948 static final int LAST_DONE_VERSION = 10000;
6949
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006950 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
6951 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
6952 File file = getCalledPreBootReceiversFile();
6953 FileInputStream fis = null;
6954 try {
6955 fis = new FileInputStream(file);
6956 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006957 int fvers = dis.readInt();
6958 if (fvers == LAST_DONE_VERSION) {
6959 String vers = dis.readUTF();
6960 String codename = dis.readUTF();
6961 String build = dis.readUTF();
6962 if (android.os.Build.VERSION.RELEASE.equals(vers)
6963 && android.os.Build.VERSION.CODENAME.equals(codename)
6964 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
6965 int num = dis.readInt();
6966 while (num > 0) {
6967 num--;
6968 String pkg = dis.readUTF();
6969 String cls = dis.readUTF();
6970 lastDoneReceivers.add(new ComponentName(pkg, cls));
6971 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006972 }
6973 }
6974 } catch (FileNotFoundException e) {
6975 } catch (IOException e) {
6976 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
6977 } finally {
6978 if (fis != null) {
6979 try {
6980 fis.close();
6981 } catch (IOException e) {
6982 }
6983 }
6984 }
6985 return lastDoneReceivers;
6986 }
6987
6988 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
6989 File file = getCalledPreBootReceiversFile();
6990 FileOutputStream fos = null;
6991 DataOutputStream dos = null;
6992 try {
6993 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
6994 fos = new FileOutputStream(file);
6995 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07006996 dos.writeInt(LAST_DONE_VERSION);
6997 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006998 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07006999 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007000 dos.writeInt(list.size());
7001 for (int i=0; i<list.size(); i++) {
7002 dos.writeUTF(list.get(i).getPackageName());
7003 dos.writeUTF(list.get(i).getClassName());
7004 }
7005 } catch (IOException e) {
7006 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7007 file.delete();
7008 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007009 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007010 if (dos != null) {
7011 try {
7012 dos.close();
7013 } catch (IOException e) {
7014 // TODO Auto-generated catch block
7015 e.printStackTrace();
7016 }
7017 }
7018 }
7019 }
7020
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007021 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 synchronized(this) {
7023 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007024 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 return;
7026 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007027
7028 // Check to see if there are any update receivers to run.
7029 if (!mDidUpdate) {
7030 if (mWaitingUpdate) {
7031 return;
7032 }
7033 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7034 List<ResolveInfo> ris = null;
7035 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007036 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007037 intent, null, 0);
7038 } catch (RemoteException e) {
7039 }
7040 if (ris != null) {
7041 for (int i=ris.size()-1; i>=0; i--) {
7042 if ((ris.get(i).activityInfo.applicationInfo.flags
7043 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7044 ris.remove(i);
7045 }
7046 }
7047 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007048
7049 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7050
7051 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007052 for (int i=0; i<ris.size(); i++) {
7053 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007054 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7055 if (lastDoneReceivers.contains(comp)) {
7056 ris.remove(i);
7057 i--;
7058 }
7059 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007060
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007061 for (int i=0; i<ris.size(); i++) {
7062 ActivityInfo ai = ris.get(i).activityInfo;
7063 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7064 doneReceivers.add(comp);
7065 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007066 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007067 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007068 finisher = new IIntentReceiver.Stub() {
7069 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007070 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007071 boolean sticky) {
7072 // The raw IIntentReceiver interface is called
7073 // with the AM lock held, so redispatch to
7074 // execute our code without the lock.
7075 mHandler.post(new Runnable() {
7076 public void run() {
7077 synchronized (ActivityManagerService.this) {
7078 mDidUpdate = true;
7079 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007080 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007081 showBootMessage(mContext.getText(
7082 R.string.android_upgrading_complete),
7083 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007084 systemReady(goingCallback);
7085 }
7086 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007087 }
7088 };
7089 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007090 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007091 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007092 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007093 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007094 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007095 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007096 mWaitingUpdate = true;
7097 }
7098 }
7099 }
7100 if (mWaitingUpdate) {
7101 return;
7102 }
7103 mDidUpdate = true;
7104 }
7105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 mSystemReady = true;
7107 if (!mStartRunning) {
7108 return;
7109 }
7110 }
7111
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007112 ArrayList<ProcessRecord> procsToKill = null;
7113 synchronized(mPidsSelfLocked) {
7114 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7115 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7116 if (!isAllowedWhileBooting(proc.info)){
7117 if (procsToKill == null) {
7118 procsToKill = new ArrayList<ProcessRecord>();
7119 }
7120 procsToKill.add(proc);
7121 }
7122 }
7123 }
7124
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007125 synchronized(this) {
7126 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007127 for (int i=procsToKill.size()-1; i>=0; i--) {
7128 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007129 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007130 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007131 }
7132 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007133
7134 // Now that we have cleaned up any update processes, we
7135 // are ready to start launching real processes and know that
7136 // we won't trample on them any more.
7137 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007138 }
7139
Joe Onorato8a9b2202010-02-26 18:56:32 -08007140 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007141 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 SystemClock.uptimeMillis());
7143
7144 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007145 // Make sure we have no pre-ready processes sitting around.
7146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7148 ResolveInfo ri = mContext.getPackageManager()
7149 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007150 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 CharSequence errorMsg = null;
7152 if (ri != null) {
7153 ActivityInfo ai = ri.activityInfo;
7154 ApplicationInfo app = ai.applicationInfo;
7155 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7156 mTopAction = Intent.ACTION_FACTORY_TEST;
7157 mTopData = null;
7158 mTopComponent = new ComponentName(app.packageName,
7159 ai.name);
7160 } else {
7161 errorMsg = mContext.getResources().getText(
7162 com.android.internal.R.string.factorytest_not_system);
7163 }
7164 } else {
7165 errorMsg = mContext.getResources().getText(
7166 com.android.internal.R.string.factorytest_no_action);
7167 }
7168 if (errorMsg != null) {
7169 mTopAction = null;
7170 mTopData = null;
7171 mTopComponent = null;
7172 Message msg = Message.obtain();
7173 msg.what = SHOW_FACTORY_ERROR_MSG;
7174 msg.getData().putCharSequence("msg", errorMsg);
7175 mHandler.sendMessage(msg);
7176 }
7177 }
7178 }
7179
7180 retrieveSettings();
7181
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007182 if (goingCallback != null) goingCallback.run();
7183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 synchronized (this) {
7185 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7186 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007187 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007188 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 if (apps != null) {
7190 int N = apps.size();
7191 int i;
7192 for (i=0; i<N; i++) {
7193 ApplicationInfo info
7194 = (ApplicationInfo)apps.get(i);
7195 if (info != null &&
7196 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007197 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 }
7199 }
7200 }
7201 } catch (RemoteException ex) {
7202 // pm is in same process, this will never happen.
7203 }
7204 }
7205
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007206 // Start up initial activity.
7207 mBooting = true;
7208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007209 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007210 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 Message msg = Message.obtain();
7212 msg.what = SHOW_UID_ERROR_MSG;
7213 mHandler.sendMessage(msg);
7214 }
7215 } catch (RemoteException e) {
7216 }
7217
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007218 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
7221
Dan Egnorb7f03672009-12-09 16:22:32 -08007222 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007223 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007225 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007226 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007227 startAppProblemLocked(app);
7228 app.stopFreezingAllLocked();
7229 return handleAppCrashLocked(app);
7230 }
7231
Dan Egnorb7f03672009-12-09 16:22:32 -08007232 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007233 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007235 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007236 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7237 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007238 startAppProblemLocked(app);
7239 app.stopFreezingAllLocked();
7240 }
7241
7242 /**
7243 * Generate a process error record, suitable for attachment to a ProcessRecord.
7244 *
7245 * @param app The ProcessRecord in which the error occurred.
7246 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7247 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007248 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 * @param shortMsg Short message describing the crash.
7250 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007251 * @param stackTrace Full crash stack trace, may be null.
7252 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 * @return Returns a fully-formed AppErrorStateInfo record.
7254 */
7255 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007256 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 report.condition = condition;
7260 report.processName = app.processName;
7261 report.pid = app.pid;
7262 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007263 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 report.shortMsg = shortMsg;
7265 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007266 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267
7268 return report;
7269 }
7270
Dan Egnor42471dd2010-01-07 17:25:22 -08007271 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 synchronized (this) {
7273 app.crashing = false;
7274 app.crashingReport = null;
7275 app.notResponding = false;
7276 app.notRespondingReport = null;
7277 if (app.anrDialog == fromDialog) {
7278 app.anrDialog = null;
7279 }
7280 if (app.waitDialog == fromDialog) {
7281 app.waitDialog = null;
7282 }
7283 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007284 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007285 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007286 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7287 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007288 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 }
7291 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007292
Dan Egnorb7f03672009-12-09 16:22:32 -08007293 private boolean handleAppCrashLocked(ProcessRecord app) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 long now = SystemClock.uptimeMillis();
7295
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007296 Long crashTime;
7297 if (!app.isolated) {
7298 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7299 } else {
7300 crashTime = null;
7301 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007302 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007304 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007306 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007307 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007308 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7309 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007311 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007313 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 }
7315 }
7316 if (!app.persistent) {
7317 // We don't want to start this process again until the user
7318 // explicitly does so... but for persistent process, we really
7319 // need to keep it running. If a persistent process is actually
7320 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007321 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007323 if (!app.isolated) {
7324 // XXX We don't have a way to mark isolated processes
7325 // as bad, since they don't have a peristent identity.
7326 mBadProcesses.put(app.info.processName, app.uid, now);
7327 mProcessCrashTimes.remove(app.info.processName, app.uid);
7328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007331 // Don't let services in this process be restarted and potentially
7332 // annoy the user repeatedly. Unless it is persistent, since those
7333 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007334 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007335 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 return false;
7337 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007338 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007339 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007340 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007341 if (r.app == app) {
7342 // If the top running activity is from this crashing
7343 // process, then terminate it to avoid getting in a loop.
7344 Slog.w(TAG, " Force finishing activity "
7345 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007346 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007347 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007348 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007349 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007350 // stopped, to avoid a situation where one will get
7351 // re-start our crashing activity once it gets resumed again.
7352 index--;
7353 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007354 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007355 if (r.state == ActivityState.RESUMED
7356 || r.state == ActivityState.PAUSING
7357 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007358 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007359 Slog.w(TAG, " Force finishing activity "
7360 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007361 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007362 Activity.RESULT_CANCELED, null, "crashed");
7363 }
7364 }
7365 }
7366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 }
7368
7369 // Bump up the crash count of any services currently running in the proc.
7370 if (app.services.size() != 0) {
7371 // Any services running in the application need to be placed
7372 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007373 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007374 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007375 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 sr.crashCount++;
7377 }
7378 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007379
7380 // If the crashing process is what we consider to be the "home process" and it has been
7381 // replaced by a third-party app, clear the package preferred activities from packages
7382 // with a home activity running in the process to prevent a repeatedly crashing app
7383 // from blocking the user to manually clear the list.
7384 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7385 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7386 Iterator it = mHomeProcess.activities.iterator();
7387 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007388 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007389 if (r.isHomeActivity) {
7390 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7391 try {
7392 ActivityThread.getPackageManager()
7393 .clearPackagePreferredActivities(r.packageName);
7394 } catch (RemoteException c) {
7395 // pm is in same process, this will never happen.
7396 }
7397 }
7398 }
7399 }
7400
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007401 if (!app.isolated) {
7402 // XXX Can't keep track of crash times for isolated processes,
7403 // because they don't have a perisistent identity.
7404 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7405 }
7406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 return true;
7408 }
7409
7410 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007411 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7412 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 skipCurrentReceiverLocked(app);
7414 }
7415
7416 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007417 for (BroadcastQueue queue : mBroadcastQueues) {
7418 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 }
7420 }
7421
Dan Egnor60d87622009-12-16 16:32:58 -08007422 /**
7423 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7424 * The application process will exit immediately after this call returns.
7425 * @param app object of the crashing app, null for the system server
7426 * @param crashInfo describing the exception
7427 */
7428 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007429 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007430 final String processName = app == null ? "system_server"
7431 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007432
7433 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007434 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007435 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007436 crashInfo.exceptionClassName,
7437 crashInfo.exceptionMessage,
7438 crashInfo.throwFileName,
7439 crashInfo.throwLineNumber);
7440
Jeff Sharkeya353d262011-10-28 11:12:06 -07007441 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007442
7443 crashApplication(r, crashInfo);
7444 }
7445
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007446 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007447 IBinder app,
7448 int violationMask,
7449 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007450 ProcessRecord r = findAppProcess(app, "StrictMode");
7451 if (r == null) {
7452 return;
7453 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007454
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007455 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007456 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007457 boolean logIt = true;
7458 synchronized (mAlreadyLoggedViolatedStacks) {
7459 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7460 logIt = false;
7461 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007462 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007463 // the relative pain numbers, without logging all
7464 // the stack traces repeatedly. We'd want to do
7465 // likewise in the client code, which also does
7466 // dup suppression, before the Binder call.
7467 } else {
7468 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7469 mAlreadyLoggedViolatedStacks.clear();
7470 }
7471 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7472 }
7473 }
7474 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007475 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007476 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007477 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007478
7479 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7480 AppErrorResult result = new AppErrorResult();
7481 synchronized (this) {
7482 final long origId = Binder.clearCallingIdentity();
7483
7484 Message msg = Message.obtain();
7485 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7486 HashMap<String, Object> data = new HashMap<String, Object>();
7487 data.put("result", result);
7488 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007489 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007490 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007491 msg.obj = data;
7492 mHandler.sendMessage(msg);
7493
7494 Binder.restoreCallingIdentity(origId);
7495 }
7496 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007497 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007498 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007499 }
7500
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007501 // Depending on the policy in effect, there could be a bunch of
7502 // these in quick succession so we try to batch these together to
7503 // minimize disk writes, number of dropbox entries, and maximize
7504 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007505 private void logStrictModeViolationToDropBox(
7506 ProcessRecord process,
7507 StrictMode.ViolationInfo info) {
7508 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007509 return;
7510 }
7511 final boolean isSystemApp = process == null ||
7512 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7513 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007514 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007515 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7516 final DropBoxManager dbox = (DropBoxManager)
7517 mContext.getSystemService(Context.DROPBOX_SERVICE);
7518
7519 // Exit early if the dropbox isn't configured to accept this report type.
7520 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7521
7522 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007523 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007524 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7525 synchronized (sb) {
7526 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007527 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007528 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7529 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007530 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7531 if (info.violationNumThisLoop != 0) {
7532 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7533 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007534 if (info.numAnimationsRunning != 0) {
7535 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7536 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007537 if (info.broadcastIntentAction != null) {
7538 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7539 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007540 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007541 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007542 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007543 if (info.numInstances != -1) {
7544 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7545 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007546 if (info.tags != null) {
7547 for (String tag : info.tags) {
7548 sb.append("Span-Tag: ").append(tag).append("\n");
7549 }
7550 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007551 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007552 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7553 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007554 }
7555 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007556
7557 // Only buffer up to ~64k. Various logging bits truncate
7558 // things at 128k.
7559 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007560 }
7561
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007562 // Flush immediately if the buffer's grown too large, or this
7563 // is a non-system app. Non-system apps are isolated with a
7564 // different tag & policy and not batched.
7565 //
7566 // Batching is useful during internal testing with
7567 // StrictMode settings turned up high. Without batching,
7568 // thousands of separate files could be created on boot.
7569 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007570 new Thread("Error dump: " + dropboxTag) {
7571 @Override
7572 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007573 String report;
7574 synchronized (sb) {
7575 report = sb.toString();
7576 sb.delete(0, sb.length());
7577 sb.trimToSize();
7578 }
7579 if (report.length() != 0) {
7580 dbox.addText(dropboxTag, report);
7581 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007582 }
7583 }.start();
7584 return;
7585 }
7586
7587 // System app batching:
7588 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007589 // An existing dropbox-writing thread is outstanding, so
7590 // we don't need to start it up. The existing thread will
7591 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007592 return;
7593 }
7594
7595 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7596 // (After this point, we shouldn't access AMS internal data structures.)
7597 new Thread("Error dump: " + dropboxTag) {
7598 @Override
7599 public void run() {
7600 // 5 second sleep to let stacks arrive and be batched together
7601 try {
7602 Thread.sleep(5000); // 5 seconds
7603 } catch (InterruptedException e) {}
7604
7605 String errorReport;
7606 synchronized (mStrictModeBuffer) {
7607 errorReport = mStrictModeBuffer.toString();
7608 if (errorReport.length() == 0) {
7609 return;
7610 }
7611 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7612 mStrictModeBuffer.trimToSize();
7613 }
7614 dbox.addText(dropboxTag, errorReport);
7615 }
7616 }.start();
7617 }
7618
Dan Egnor60d87622009-12-16 16:32:58 -08007619 /**
7620 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7621 * @param app object of the crashing app, null for the system server
7622 * @param tag reported by the caller
7623 * @param crashInfo describing the context of the error
7624 * @return true if the process should exit immediately (WTF is fatal)
7625 */
7626 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007627 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007628 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007629 final String processName = app == null ? "system_server"
7630 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007631
7632 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007633 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007634 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007635 tag, crashInfo.exceptionMessage);
7636
Jeff Sharkeya353d262011-10-28 11:12:06 -07007637 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007638
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007639 if (r != null && r.pid != Process.myPid() &&
7640 Settings.Secure.getInt(mContext.getContentResolver(),
7641 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007642 crashApplication(r, crashInfo);
7643 return true;
7644 } else {
7645 return false;
7646 }
7647 }
7648
7649 /**
7650 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7651 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7652 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007653 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007654 if (app == null) {
7655 return null;
7656 }
7657
7658 synchronized (this) {
7659 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7660 final int NA = apps.size();
7661 for (int ia=0; ia<NA; ia++) {
7662 ProcessRecord p = apps.valueAt(ia);
7663 if (p.thread != null && p.thread.asBinder() == app) {
7664 return p;
7665 }
7666 }
7667 }
7668
Dianne Hackborncb44d962011-03-10 17:02:27 -08007669 Slog.w(TAG, "Can't find mystery application for " + reason
7670 + " from pid=" + Binder.getCallingPid()
7671 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007672 return null;
7673 }
7674 }
7675
7676 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007677 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7678 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007679 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007680 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7681 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007682 // Watchdog thread ends up invoking this function (with
7683 // a null ProcessRecord) to add the stack file to dropbox.
7684 // Do not acquire a lock on this (am) in such cases, as it
7685 // could cause a potential deadlock, if and when watchdog
7686 // is invoked due to unavailability of lock on am and it
7687 // would prevent watchdog from killing system_server.
7688 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007689 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007690 return;
7691 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007692 // Note: ProcessRecord 'process' is guarded by the service
7693 // instance. (notably process.pkgList, which could otherwise change
7694 // concurrently during execution of this method)
7695 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007696 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007697 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007698 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007699 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7700 for (String pkg : process.pkgList) {
7701 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007702 try {
Dan Egnora455d192010-03-12 08:52:28 -08007703 PackageInfo pi = pm.getPackageInfo(pkg, 0);
7704 if (pi != null) {
7705 sb.append(" v").append(pi.versionCode);
7706 if (pi.versionName != null) {
7707 sb.append(" (").append(pi.versionName).append(")");
7708 }
7709 }
7710 } catch (RemoteException e) {
7711 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007712 }
Dan Egnora455d192010-03-12 08:52:28 -08007713 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007714 }
Dan Egnora455d192010-03-12 08:52:28 -08007715 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007716 }
7717
7718 private static String processClass(ProcessRecord process) {
7719 if (process == null || process.pid == MY_PID) {
7720 return "system_server";
7721 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7722 return "system_app";
7723 } else {
7724 return "data_app";
7725 }
7726 }
7727
7728 /**
7729 * Write a description of an error (crash, WTF, ANR) to the drop box.
7730 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7731 * @param process which caused the error, null means the system server
7732 * @param activity which triggered the error, null if unknown
7733 * @param parent activity related to the error, null if unknown
7734 * @param subject line related to the error, null if absent
7735 * @param report in long form describing the error, null if absent
7736 * @param logFile to include in the report, null if none
7737 * @param crashInfo giving an application stack trace, null if absent
7738 */
7739 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007740 ProcessRecord process, String processName, ActivityRecord activity,
7741 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007742 final String report, final File logFile,
7743 final ApplicationErrorReport.CrashInfo crashInfo) {
7744 // NOTE -- this must never acquire the ActivityManagerService lock,
7745 // otherwise the watchdog may be prevented from resetting the system.
7746
7747 final String dropboxTag = processClass(process) + "_" + eventType;
7748 final DropBoxManager dbox = (DropBoxManager)
7749 mContext.getSystemService(Context.DROPBOX_SERVICE);
7750
7751 // Exit early if the dropbox isn't configured to accept this report type.
7752 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7753
7754 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007755 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007756 if (activity != null) {
7757 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7758 }
7759 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7760 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7761 }
7762 if (parent != null && parent != activity) {
7763 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7764 }
7765 if (subject != null) {
7766 sb.append("Subject: ").append(subject).append("\n");
7767 }
7768 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007769 if (Debug.isDebuggerConnected()) {
7770 sb.append("Debugger: Connected\n");
7771 }
Dan Egnora455d192010-03-12 08:52:28 -08007772 sb.append("\n");
7773
7774 // Do the rest in a worker thread to avoid blocking the caller on I/O
7775 // (After this point, we shouldn't access AMS internal data structures.)
7776 Thread worker = new Thread("Error dump: " + dropboxTag) {
7777 @Override
7778 public void run() {
7779 if (report != null) {
7780 sb.append(report);
7781 }
7782 if (logFile != null) {
7783 try {
7784 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7785 } catch (IOException e) {
7786 Slog.e(TAG, "Error reading " + logFile, e);
7787 }
7788 }
7789 if (crashInfo != null && crashInfo.stackTrace != null) {
7790 sb.append(crashInfo.stackTrace);
7791 }
7792
7793 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7794 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7795 if (lines > 0) {
7796 sb.append("\n");
7797
7798 // Merge several logcat streams, and take the last N lines
7799 InputStreamReader input = null;
7800 try {
7801 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7802 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7803 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7804
7805 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7806 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7807 input = new InputStreamReader(logcat.getInputStream());
7808
7809 int num;
7810 char[] buf = new char[8192];
7811 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7812 } catch (IOException e) {
7813 Slog.e(TAG, "Error running logcat", e);
7814 } finally {
7815 if (input != null) try { input.close(); } catch (IOException e) {}
7816 }
7817 }
7818
7819 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007820 }
Dan Egnora455d192010-03-12 08:52:28 -08007821 };
7822
7823 if (process == null || process.pid == MY_PID) {
7824 worker.run(); // We may be about to die -- need to run this synchronously
7825 } else {
7826 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007827 }
7828 }
7829
7830 /**
7831 * Bring up the "unexpected error" dialog box for a crashing app.
7832 * Deal with edge cases (intercepts from instrumented applications,
7833 * ActivityController, error intent receivers, that sort of thing).
7834 * @param r the application crashing
7835 * @param crashInfo describing the failure
7836 */
7837 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007838 long timeMillis = System.currentTimeMillis();
7839 String shortMsg = crashInfo.exceptionClassName;
7840 String longMsg = crashInfo.exceptionMessage;
7841 String stackTrace = crashInfo.stackTrace;
7842 if (shortMsg != null && longMsg != null) {
7843 longMsg = shortMsg + ": " + longMsg;
7844 } else if (shortMsg != null) {
7845 longMsg = shortMsg;
7846 }
7847
Dan Egnor60d87622009-12-16 16:32:58 -08007848 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007850 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 try {
7852 String name = r != null ? r.processName : null;
7853 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007854 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007855 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007856 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 + " at watcher's request");
7858 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007859 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 }
7861 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007862 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 }
7864 }
7865
7866 final long origId = Binder.clearCallingIdentity();
7867
7868 // If this process is running instrumentation, finish it.
7869 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007870 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007872 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7873 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 Bundle info = new Bundle();
7875 info.putString("shortMsg", shortMsg);
7876 info.putString("longMsg", longMsg);
7877 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7878 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007879 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 }
7881
Dan Egnor60d87622009-12-16 16:32:58 -08007882 // If we can't identify the process or it's already exceeded its crash quota,
7883 // quit right away without showing a crash dialog.
7884 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007886 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 }
7888
7889 Message msg = Message.obtain();
7890 msg.what = SHOW_ERROR_MSG;
7891 HashMap data = new HashMap();
7892 data.put("result", result);
7893 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 msg.obj = data;
7895 mHandler.sendMessage(msg);
7896
7897 Binder.restoreCallingIdentity(origId);
7898 }
7899
7900 int res = result.get();
7901
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007902 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007904 if (r != null && !r.isolated) {
7905 // XXX Can't keep track of crash time for isolated processes,
7906 // since they don't have a persistent identity.
7907 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 SystemClock.uptimeMillis());
7909 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007910 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007911 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007912 }
7913 }
7914
7915 if (appErrorIntent != null) {
7916 try {
7917 mContext.startActivity(appErrorIntent);
7918 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007919 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 }
Dan Egnorb7f03672009-12-09 16:22:32 -08007923
7924 Intent createAppErrorIntentLocked(ProcessRecord r,
7925 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
7926 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007927 if (report == null) {
7928 return null;
7929 }
7930 Intent result = new Intent(Intent.ACTION_APP_ERROR);
7931 result.setComponent(r.errorReportReceiver);
7932 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
7933 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
7934 return result;
7935 }
7936
Dan Egnorb7f03672009-12-09 16:22:32 -08007937 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
7938 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007939 if (r.errorReportReceiver == null) {
7940 return null;
7941 }
7942
7943 if (!r.crashing && !r.notResponding) {
7944 return null;
7945 }
7946
Dan Egnorb7f03672009-12-09 16:22:32 -08007947 ApplicationErrorReport report = new ApplicationErrorReport();
7948 report.packageName = r.info.packageName;
7949 report.installerPackageName = r.errorReportReceiver.getPackageName();
7950 report.processName = r.processName;
7951 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01007952 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007953
Dan Egnorb7f03672009-12-09 16:22:32 -08007954 if (r.crashing) {
7955 report.type = ApplicationErrorReport.TYPE_CRASH;
7956 report.crashInfo = crashInfo;
7957 } else if (r.notResponding) {
7958 report.type = ApplicationErrorReport.TYPE_ANR;
7959 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007960
Dan Egnorb7f03672009-12-09 16:22:32 -08007961 report.anrInfo.activity = r.notRespondingReport.tag;
7962 report.anrInfo.cause = r.notRespondingReport.shortMsg;
7963 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007964 }
7965
Dan Egnorb7f03672009-12-09 16:22:32 -08007966 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02007967 }
7968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007970 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 // assume our apps are happy - lazy create the list
7972 List<ActivityManager.ProcessErrorStateInfo> errList = null;
7973
7974 synchronized (this) {
7975
7976 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08007977 for (int i=mLruProcesses.size()-1; i>=0; i--) {
7978 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 if ((app.thread != null) && (app.crashing || app.notResponding)) {
7980 // This one's in trouble, so we'll generate a report for it
7981 // crashes are higher priority (in case there's a crash *and* an anr)
7982 ActivityManager.ProcessErrorStateInfo report = null;
7983 if (app.crashing) {
7984 report = app.crashingReport;
7985 } else if (app.notResponding) {
7986 report = app.notRespondingReport;
7987 }
7988
7989 if (report != null) {
7990 if (errList == null) {
7991 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
7992 }
7993 errList.add(report);
7994 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007995 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 " crashing = " + app.crashing +
7997 " notResponding = " + app.notResponding);
7998 }
7999 }
8000 }
8001 }
8002
8003 return errList;
8004 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008005
8006 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008007 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008008 if (currApp != null) {
8009 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8010 }
8011 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008012 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8013 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008014 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8015 if (currApp != null) {
8016 currApp.lru = 0;
8017 }
8018 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008019 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008020 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8021 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8022 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8023 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8024 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8025 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8026 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8027 } else {
8028 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8029 }
8030 }
8031
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008032 private void fillInProcMemInfo(ProcessRecord app,
8033 ActivityManager.RunningAppProcessInfo outInfo) {
8034 outInfo.pid = app.pid;
8035 outInfo.uid = app.info.uid;
8036 if (mHeavyWeightProcess == app) {
8037 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8038 }
8039 if (app.persistent) {
8040 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8041 }
8042 outInfo.lastTrimLevel = app.trimMemoryLevel;
8043 int adj = app.curAdj;
8044 outInfo.importance = oomAdjToImportance(adj, outInfo);
8045 outInfo.importanceReasonCode = app.adjTypeCode;
8046 }
8047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008049 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 // Lazy instantiation of list
8051 List<ActivityManager.RunningAppProcessInfo> runList = null;
8052 synchronized (this) {
8053 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008054 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8055 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8057 // Generate process state info for running application
8058 ActivityManager.RunningAppProcessInfo currApp =
8059 new ActivityManager.RunningAppProcessInfo(app.processName,
8060 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008061 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008062 if (app.adjSource instanceof ProcessRecord) {
8063 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008064 currApp.importanceReasonImportance = oomAdjToImportance(
8065 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008066 } else if (app.adjSource instanceof ActivityRecord) {
8067 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008068 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8069 }
8070 if (app.adjTarget instanceof ComponentName) {
8071 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8072 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008073 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 // + " lru=" + currApp.lru);
8075 if (runList == null) {
8076 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8077 }
8078 runList.add(currApp);
8079 }
8080 }
8081 }
8082 return runList;
8083 }
8084
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008085 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008086 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008087 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8088 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8089 if (runningApps != null && runningApps.size() > 0) {
8090 Set<String> extList = new HashSet<String>();
8091 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8092 if (app.pkgList != null) {
8093 for (String pkg : app.pkgList) {
8094 extList.add(pkg);
8095 }
8096 }
8097 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008098 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008099 for (String pkg : extList) {
8100 try {
8101 ApplicationInfo info = pm.getApplicationInfo(pkg, 0);
8102 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8103 retList.add(info);
8104 }
8105 } catch (RemoteException e) {
8106 }
8107 }
8108 }
8109 return retList;
8110 }
8111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008113 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8114 enforceNotIsolatedCaller("getMyMemoryState");
8115 synchronized (this) {
8116 ProcessRecord proc;
8117 synchronized (mPidsSelfLocked) {
8118 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8119 }
8120 fillInProcMemInfo(proc, outInfo);
8121 }
8122 }
8123
8124 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008126 if (checkCallingPermission(android.Manifest.permission.DUMP)
8127 != PackageManager.PERMISSION_GRANTED) {
8128 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8129 + Binder.getCallingPid()
8130 + ", uid=" + Binder.getCallingUid()
8131 + " without permission "
8132 + android.Manifest.permission.DUMP);
8133 return;
8134 }
8135
8136 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008137 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008138 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008139
8140 int opti = 0;
8141 while (opti < args.length) {
8142 String opt = args[opti];
8143 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8144 break;
8145 }
8146 opti++;
8147 if ("-a".equals(opt)) {
8148 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008149 } else if ("-c".equals(opt)) {
8150 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008151 } else if ("-h".equals(opt)) {
8152 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008153 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008154 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008155 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008156 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8157 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8158 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008159 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008160 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008161 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008162 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008163 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008164 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008165 pw.println(" all: dump all activities");
8166 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008167 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008168 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8169 pw.println(" a partial substring in a component name, a");
8170 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008171 pw.println(" -a: include all available server state.");
8172 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008174 } else {
8175 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008177 }
8178
8179 // Is the caller requesting to dump a particular piece of data?
8180 if (opti < args.length) {
8181 String cmd = args[opti];
8182 opti++;
8183 if ("activities".equals(cmd) || "a".equals(cmd)) {
8184 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008185 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008187 return;
8188 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008189 String[] newArgs;
8190 String name;
8191 if (opti >= args.length) {
8192 name = null;
8193 newArgs = EMPTY_STRING_ARRAY;
8194 } else {
8195 name = args[opti];
8196 opti++;
8197 newArgs = new String[args.length - opti];
8198 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8199 args.length - opti);
8200 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008201 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008202 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008203 }
8204 return;
8205 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008206 String[] newArgs;
8207 String name;
8208 if (opti >= args.length) {
8209 name = null;
8210 newArgs = EMPTY_STRING_ARRAY;
8211 } else {
8212 name = args[opti];
8213 opti++;
8214 newArgs = new String[args.length - opti];
8215 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8216 args.length - opti);
8217 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008218 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008219 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008220 }
8221 return;
8222 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008223 String[] newArgs;
8224 String name;
8225 if (opti >= args.length) {
8226 name = null;
8227 newArgs = EMPTY_STRING_ARRAY;
8228 } else {
8229 name = args[opti];
8230 opti++;
8231 newArgs = new String[args.length - opti];
8232 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8233 args.length - opti);
8234 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008235 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008236 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008237 }
8238 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008239 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8240 synchronized (this) {
8241 dumpOomLocked(fd, pw, args, opti, true);
8242 }
8243 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008244 } else if ("provider".equals(cmd)) {
8245 String[] newArgs;
8246 String name;
8247 if (opti >= args.length) {
8248 name = null;
8249 newArgs = EMPTY_STRING_ARRAY;
8250 } else {
8251 name = args[opti];
8252 opti++;
8253 newArgs = new String[args.length - opti];
8254 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8255 }
8256 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8257 pw.println("No providers match: " + name);
8258 pw.println("Use -h for help.");
8259 }
8260 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008261 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8262 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008263 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008264 }
8265 return;
8266 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008267 String[] newArgs;
8268 String name;
8269 if (opti >= args.length) {
8270 name = null;
8271 newArgs = EMPTY_STRING_ARRAY;
8272 } else {
8273 name = args[opti];
8274 opti++;
8275 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008276 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8277 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008278 }
8279 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8280 pw.println("No services match: " + name);
8281 pw.println("Use -h for help.");
8282 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008283 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008284 } else if ("package".equals(cmd)) {
8285 String[] newArgs;
8286 if (opti >= args.length) {
8287 pw.println("package: no package name specified");
8288 pw.println("Use -h for help.");
8289 return;
8290 } else {
8291 dumpPackage = args[opti];
8292 opti++;
8293 newArgs = new String[args.length - opti];
8294 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8295 args.length - opti);
8296 args = newArgs;
8297 opti = 0;
8298 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008299 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8300 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008301 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008302 }
8303 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008304 } else {
8305 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008306 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8307 pw.println("Bad activity command, or no activities match: " + cmd);
8308 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008309 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008310 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008312 }
8313
8314 // No piece of data specified, dump everything.
8315 synchronized (this) {
8316 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008317 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008318 if (needSep) {
8319 pw.println(" ");
8320 }
8321 if (dumpAll) {
8322 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008323 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008324 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008325 if (needSep) {
8326 pw.println(" ");
8327 }
8328 if (dumpAll) {
8329 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008330 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008331 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008332 if (needSep) {
8333 pw.println(" ");
8334 }
8335 if (dumpAll) {
8336 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008337 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008338 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008339 if (needSep) {
8340 pw.println(" ");
8341 }
8342 if (dumpAll) {
8343 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008344 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008345 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008346 if (needSep) {
8347 pw.println(" ");
8348 }
8349 if (dumpAll) {
8350 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008351 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008352 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008353 }
8354 }
8355
8356 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008357 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008358 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8359 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008360 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8361 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008362 pw.println(" ");
8363 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008364 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8365 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008366 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008368 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008369 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008370 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008371 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008372 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008374 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008375 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008376 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008377 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008378 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8379 pw.println(" ");
8380 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008381 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008382 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008383 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008384 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008385 pw.println(" ");
8386 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008387 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008388 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008391 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008392 if (mMainStack.mPausingActivity != null) {
8393 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008394 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008395 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008396 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008397 if (dumpAll) {
8398 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8399 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008400 pw.println(" mDismissKeyguardOnNextActivity: "
8401 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008404 if (mRecentTasks.size() > 0) {
8405 pw.println();
8406 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008407
8408 final int N = mRecentTasks.size();
8409 for (int i=0; i<N; i++) {
8410 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008411 if (dumpPackage != null) {
8412 if (tr.realActivity == null ||
8413 !dumpPackage.equals(tr.realActivity)) {
8414 continue;
8415 }
8416 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008417 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8418 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008419 if (dumpAll) {
8420 mRecentTasks.get(i).dump(pw, " ");
8421 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008422 }
8423 }
8424
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008425 if (dumpAll) {
8426 pw.println(" ");
8427 pw.println(" mCurTask: " + mCurTask);
8428 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008429
8430 return true;
8431 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008432
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008433 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008434 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008435 boolean needSep = false;
8436 int numPers = 0;
8437
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008438 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8439
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008440 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8442 final int NA = procs.size();
8443 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008444 ProcessRecord r = procs.valueAt(ia);
8445 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8446 continue;
8447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 if (!needSep) {
8449 pw.println(" All known processes:");
8450 needSep = true;
8451 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008452 pw.print(r.persistent ? " *PERS*" : " *APP*");
8453 pw.print(" UID "); pw.print(procs.keyAt(ia));
8454 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 r.dump(pw, " ");
8456 if (r.persistent) {
8457 numPers++;
8458 }
8459 }
8460 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008461 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008462
8463 if (mIsolatedProcesses.size() > 0) {
8464 if (needSep) pw.println(" ");
8465 needSep = true;
8466 pw.println(" Isolated process list (sorted by uid):");
8467 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8468 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8469 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8470 continue;
8471 }
8472 pw.println(String.format("%sIsolated #%2d: %s",
8473 " ", i, r.toString()));
8474 }
8475 }
8476
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008477 if (mLruProcesses.size() > 0) {
8478 if (needSep) pw.println(" ");
8479 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008480 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008481 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008482 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008483 needSep = true;
8484 }
8485
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008486 if (dumpAll) {
8487 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008488 boolean printed = false;
8489 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8490 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8491 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8492 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008493 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008494 if (!printed) {
8495 if (needSep) pw.println(" ");
8496 needSep = true;
8497 pw.println(" PID mappings:");
8498 printed = true;
8499 }
8500 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8501 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 }
8503 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008504 }
8505
8506 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008507 synchronized (mPidsSelfLocked) {
8508 boolean printed = false;
8509 for (int i=0; i<mForegroundProcesses.size(); i++) {
8510 ProcessRecord r = mPidsSelfLocked.get(
8511 mForegroundProcesses.valueAt(i).pid);
8512 if (dumpPackage != null && (r == null
8513 || !dumpPackage.equals(r.info.packageName))) {
8514 continue;
8515 }
8516 if (!printed) {
8517 if (needSep) pw.println(" ");
8518 needSep = true;
8519 pw.println(" Foreground Processes:");
8520 printed = true;
8521 }
8522 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8523 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008526 }
8527
8528 if (mPersistentStartingProcesses.size() > 0) {
8529 if (needSep) pw.println(" ");
8530 needSep = true;
8531 pw.println(" Persisent processes that are starting:");
8532 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008533 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008536 if (mRemovedProcesses.size() > 0) {
8537 if (needSep) pw.println(" ");
8538 needSep = true;
8539 pw.println(" Processes that are being removed:");
8540 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008541 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008542 }
8543
8544 if (mProcessesOnHold.size() > 0) {
8545 if (needSep) pw.println(" ");
8546 needSep = true;
8547 pw.println(" Processes that are on old until the system is ready:");
8548 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008549 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008552 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008553
8554 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008556 long now = SystemClock.uptimeMillis();
8557 for (Map.Entry<String, SparseArray<Long>> procs
8558 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008559 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008560 SparseArray<Long> uids = procs.getValue();
8561 final int N = uids.size();
8562 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008563 int puid = uids.keyAt(i);
8564 ProcessRecord r = mProcessNames.get(pname, puid);
8565 if (dumpPackage != null && (r == null
8566 || !dumpPackage.equals(r.info.packageName))) {
8567 continue;
8568 }
8569 if (!printed) {
8570 if (needSep) pw.println(" ");
8571 needSep = true;
8572 pw.println(" Time since processes crashed:");
8573 printed = true;
8574 }
8575 pw.print(" Process "); pw.print(pname);
8576 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008577 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008578 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8579 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008580 }
8581 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008584 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008585 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 for (Map.Entry<String, SparseArray<Long>> procs
8587 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008588 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008589 SparseArray<Long> uids = procs.getValue();
8590 final int N = uids.size();
8591 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008592 int puid = uids.keyAt(i);
8593 ProcessRecord r = mProcessNames.get(pname, puid);
8594 if (dumpPackage != null && (r == null
8595 || !dumpPackage.equals(r.info.packageName))) {
8596 continue;
8597 }
8598 if (!printed) {
8599 if (needSep) pw.println(" ");
8600 needSep = true;
8601 pw.println(" Bad processes:");
8602 }
8603 pw.print(" Bad process "); pw.print(pname);
8604 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008605 pw.print(": crashed at time ");
8606 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 }
8608 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008611 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008612 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008613 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008614 if (dumpAll) {
8615 StringBuilder sb = new StringBuilder(128);
8616 sb.append(" mPreviousProcessVisibleTime: ");
8617 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8618 pw.println(sb);
8619 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008620 if (mHeavyWeightProcess != null) {
8621 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8622 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008623 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008624 if (dumpAll) {
8625 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008626 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008627 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008628 for (Map.Entry<String, Integer> entry
8629 : mCompatModePackages.getPackages().entrySet()) {
8630 String pkg = entry.getKey();
8631 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008632 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8633 continue;
8634 }
8635 if (!printed) {
8636 pw.println(" mScreenCompatPackages:");
8637 printed = true;
8638 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008639 pw.print(" "); pw.print(pkg); pw.print(": ");
8640 pw.print(mode); pw.println();
8641 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008642 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008643 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008644 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8645 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8646 || mOrigWaitForDebugger) {
8647 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8648 + " mDebugTransient=" + mDebugTransient
8649 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8650 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008651 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8652 || mProfileFd != null) {
8653 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8654 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8655 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8656 + mAutoStopProfiler);
8657 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008658 if (mAlwaysFinishActivities || mController != null) {
8659 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8660 + " mController=" + mController);
8661 }
8662 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008665 + " mProcessesReady=" + mProcessesReady
8666 + " mSystemReady=" + mSystemReady);
8667 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 + " mBooted=" + mBooted
8669 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008670 pw.print(" mLastPowerCheckRealtime=");
8671 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8672 pw.println("");
8673 pw.print(" mLastPowerCheckUptime=");
8674 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8675 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008676 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8677 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008678 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008679 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8680 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682
8683 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 }
8685
Dianne Hackborn287952c2010-09-22 22:34:31 -07008686 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008687 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008688 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008689 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008690 long now = SystemClock.uptimeMillis();
8691 for (int i=0; i<mProcessesToGc.size(); i++) {
8692 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008693 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8694 continue;
8695 }
8696 if (!printed) {
8697 if (needSep) pw.println(" ");
8698 needSep = true;
8699 pw.println(" Processes that are waiting to GC:");
8700 printed = true;
8701 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008702 pw.print(" Process "); pw.println(proc);
8703 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8704 pw.print(", last gced=");
8705 pw.print(now-proc.lastRequestedGc);
8706 pw.print(" ms ago, last lowMem=");
8707 pw.print(now-proc.lastLowMemory);
8708 pw.println(" ms ago");
8709
8710 }
8711 }
8712 return needSep;
8713 }
8714
8715 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8716 int opti, boolean dumpAll) {
8717 boolean needSep = false;
8718
8719 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008720 if (needSep) pw.println(" ");
8721 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008722 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008723 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008724 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008725 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8726 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8727 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8728 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8729 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008730 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008731 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008732 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008733 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008734 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008735 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008736
8737 if (needSep) pw.println(" ");
8738 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008739 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008740 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008741 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008742 needSep = true;
8743 }
8744
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008745 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008746
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008747 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008748 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008749 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008750 if (mHeavyWeightProcess != null) {
8751 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8752 }
8753
8754 return true;
8755 }
8756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 /**
8758 * There are three ways to call this:
8759 * - no service specified: dump all the services
8760 * - a flattened component name that matched an existing service was specified as the
8761 * first arg: dump that one service
8762 * - the first arg isn't the flattened component name of an existing service:
8763 * dump all services whose component contains the first arg as a substring
8764 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008765 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8766 int opti, boolean dumpAll) {
8767 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008769 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008770 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008771 try {
8772 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8773 for (UserInfo user : users) {
8774 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8775 services.add(r1);
8776 }
8777 }
8778 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008779 }
8780 }
8781 } else {
8782 ComponentName componentName = name != null
8783 ? ComponentName.unflattenFromString(name) : null;
8784 int objectId = 0;
8785 if (componentName == null) {
8786 // Not a '/' separated full component name; maybe an object ID?
8787 try {
8788 objectId = Integer.parseInt(name, 16);
8789 name = null;
8790 componentName = null;
8791 } catch (RuntimeException e) {
8792 }
8793 }
8794
8795 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008796 try {
8797 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8798 for (UserInfo user : users) {
8799 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8800 if (componentName != null) {
8801 if (r1.name.equals(componentName)) {
8802 services.add(r1);
8803 }
8804 } else if (name != null) {
8805 if (r1.name.flattenToString().contains(name)) {
8806 services.add(r1);
8807 }
8808 } else if (System.identityHashCode(r1) == objectId) {
8809 services.add(r1);
8810 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008811 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008812 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008813 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 }
8815 }
8816 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008817
8818 if (services.size() <= 0) {
8819 return false;
8820 }
8821
8822 boolean needSep = false;
8823 for (int i=0; i<services.size(); i++) {
8824 if (needSep) {
8825 pw.println();
8826 }
8827 needSep = true;
8828 dumpService("", fd, pw, services.get(i), args, dumpAll);
8829 }
8830 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 }
8832
8833 /**
8834 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8835 * there is a thread associated with the service.
8836 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008837 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8838 final ServiceRecord r, String[] args, boolean dumpAll) {
8839 String innerPrefix = prefix + " ";
8840 synchronized (this) {
8841 pw.print(prefix); pw.print("SERVICE ");
8842 pw.print(r.shortName); pw.print(" ");
8843 pw.print(Integer.toHexString(System.identityHashCode(r)));
8844 pw.print(" pid=");
8845 if (r.app != null) pw.println(r.app.pid);
8846 else pw.println("(not running)");
8847 if (dumpAll) {
8848 r.dump(pw, innerPrefix);
8849 }
8850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008852 pw.print(prefix); pw.println(" Client:");
8853 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008855 TransferPipe tp = new TransferPipe();
8856 try {
8857 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8858 tp.setBufferPrefix(prefix + " ");
8859 tp.go(fd);
8860 } finally {
8861 tp.kill();
8862 }
8863 } catch (IOException e) {
8864 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008866 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 }
8868 }
8869 }
8870
Marco Nelissen18cb2872011-11-15 11:19:53 -08008871 /**
8872 * There are three ways to call this:
8873 * - no provider specified: dump all the providers
8874 * - a flattened component name that matched an existing provider was specified as the
8875 * first arg: dump that one provider
8876 * - the first arg isn't the flattened component name of an existing provider:
8877 * dump all providers whose component contains the first arg as a substring
8878 */
8879 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8880 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008881 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008882 }
8883
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008884 static class ItemMatcher {
8885 ArrayList<ComponentName> components;
8886 ArrayList<String> strings;
8887 ArrayList<Integer> objects;
8888 boolean all;
8889
8890 ItemMatcher() {
8891 all = true;
8892 }
8893
8894 void build(String name) {
8895 ComponentName componentName = ComponentName.unflattenFromString(name);
8896 if (componentName != null) {
8897 if (components == null) {
8898 components = new ArrayList<ComponentName>();
8899 }
8900 components.add(componentName);
8901 all = false;
8902 } else {
8903 int objectId = 0;
8904 // Not a '/' separated full component name; maybe an object ID?
8905 try {
8906 objectId = Integer.parseInt(name, 16);
8907 if (objects == null) {
8908 objects = new ArrayList<Integer>();
8909 }
8910 objects.add(objectId);
8911 all = false;
8912 } catch (RuntimeException e) {
8913 // Not an integer; just do string match.
8914 if (strings == null) {
8915 strings = new ArrayList<String>();
8916 }
8917 strings.add(name);
8918 all = false;
8919 }
8920 }
8921 }
8922
8923 int build(String[] args, int opti) {
8924 for (; opti<args.length; opti++) {
8925 String name = args[opti];
8926 if ("--".equals(name)) {
8927 return opti+1;
8928 }
8929 build(name);
8930 }
8931 return opti;
8932 }
8933
8934 boolean match(Object object, ComponentName comp) {
8935 if (all) {
8936 return true;
8937 }
8938 if (components != null) {
8939 for (int i=0; i<components.size(); i++) {
8940 if (components.get(i).equals(comp)) {
8941 return true;
8942 }
8943 }
8944 }
8945 if (objects != null) {
8946 for (int i=0; i<objects.size(); i++) {
8947 if (System.identityHashCode(object) == objects.get(i)) {
8948 return true;
8949 }
8950 }
8951 }
8952 if (strings != null) {
8953 String flat = comp.flattenToString();
8954 for (int i=0; i<strings.size(); i++) {
8955 if (flat.contains(strings.get(i))) {
8956 return true;
8957 }
8958 }
8959 }
8960 return false;
8961 }
8962 }
8963
Dianne Hackborn625ac272010-09-17 18:29:22 -07008964 /**
8965 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008966 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07008967 * - the cmd arg isn't the flattened component name of an existing activity:
8968 * dump all activity whose component contains the cmd as a substring
8969 * - A hex number of the ActivityRecord object instance.
8970 */
8971 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8972 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008973 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008974
8975 if ("all".equals(name)) {
8976 synchronized (this) {
8977 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07008978 activities.add(r1);
8979 }
8980 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07008981 } else if ("top".equals(name)) {
8982 synchronized (this) {
8983 final int N = mMainStack.mHistory.size();
8984 if (N > 0) {
8985 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
8986 }
8987 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008988 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008989 ItemMatcher matcher = new ItemMatcher();
8990 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008991
8992 synchronized (this) {
8993 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008994 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008995 activities.add(r1);
8996 }
8997 }
8998 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008999 }
9000
9001 if (activities.size() <= 0) {
9002 return false;
9003 }
9004
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009005 String[] newArgs = new String[args.length - opti];
9006 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9007
Dianne Hackborn30d71892010-12-11 10:37:55 -08009008 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009009 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009010 for (int i=activities.size()-1; i>=0; i--) {
9011 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009012 if (needSep) {
9013 pw.println();
9014 }
9015 needSep = true;
9016 synchronized (this) {
9017 if (lastTask != r.task) {
9018 lastTask = r.task;
9019 pw.print("TASK "); pw.print(lastTask.affinity);
9020 pw.print(" id="); pw.println(lastTask.taskId);
9021 if (dumpAll) {
9022 lastTask.dump(pw, " ");
9023 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009024 }
9025 }
9026 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009027 }
9028 return true;
9029 }
9030
9031 /**
9032 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9033 * there is a thread associated with the activity.
9034 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009035 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 final ActivityRecord r, String[] args, boolean dumpAll) {
9037 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009038 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009039 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9040 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9041 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009042 if (r.app != null) pw.println(r.app.pid);
9043 else pw.println("(not running)");
9044 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009045 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009046 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009047 }
9048 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 // flush anything that is already in the PrintWriter since the thread is going
9050 // to write to the file descriptor directly
9051 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009052 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009053 TransferPipe tp = new TransferPipe();
9054 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009055 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9056 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 tp.go(fd);
9058 } finally {
9059 tp.kill();
9060 }
9061 } catch (IOException e) {
9062 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009063 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009064 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009065 }
9066 }
9067 }
9068
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009069 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 boolean needSep = false;
9072
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009073 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009074 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009076 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077 Iterator it = mRegisteredReceivers.values().iterator();
9078 while (it.hasNext()) {
9079 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 if (dumpPackage != null && (r.app == null ||
9081 !dumpPackage.equals(r.app.info.packageName))) {
9082 continue;
9083 }
9084 if (!printed) {
9085 pw.println(" Registered Receivers:");
9086 needSep = true;
9087 printed = true;
9088 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009089 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 r.dump(pw, " ");
9091 }
9092 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009093
9094 if (mReceiverResolver.dump(pw, needSep ?
9095 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9096 " ", dumpPackage, false)) {
9097 needSep = true;
9098 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009100
9101 for (BroadcastQueue q : mBroadcastQueues) {
9102 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009105 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009106
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009107 if (mStickyBroadcasts != null && dumpPackage == null) {
9108 if (needSep) {
9109 pw.println();
9110 }
9111 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009112 pw.println(" Sticky broadcasts:");
9113 StringBuilder sb = new StringBuilder(128);
9114 for (Map.Entry<String, ArrayList<Intent>> ent
9115 : mStickyBroadcasts.entrySet()) {
9116 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009117 if (dumpAll) {
9118 pw.println(":");
9119 ArrayList<Intent> intents = ent.getValue();
9120 final int N = intents.size();
9121 for (int i=0; i<N; i++) {
9122 sb.setLength(0);
9123 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009124 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009125 pw.println(sb.toString());
9126 Bundle bundle = intents.get(i).getExtras();
9127 if (bundle != null) {
9128 pw.print(" ");
9129 pw.println(bundle.toString());
9130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009132 } else {
9133 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 }
9135 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 needSep = true;
9137 }
9138
9139 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009140 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009141 for (BroadcastQueue queue : mBroadcastQueues) {
9142 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9143 + queue.mBroadcastsScheduled);
9144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 pw.println(" mHandler:");
9146 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009147 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009149
9150 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 }
9152
Marco Nelissen18cb2872011-11-15 11:19:53 -08009153 /**
9154 * Prints a list of ServiceRecords (dumpsys activity services)
9155 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009156 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009157 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009160 ItemMatcher matcher = new ItemMatcher();
9161 matcher.build(args, opti);
9162
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009163 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009164 try {
9165 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9166 for (UserInfo user : users) {
9167 if (mServiceMap.getAllServices(user.id).size() > 0) {
9168 boolean printed = false;
9169 long nowReal = SystemClock.elapsedRealtime();
9170 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9171 user.id).iterator();
9172 needSep = false;
9173 while (it.hasNext()) {
9174 ServiceRecord r = it.next();
9175 if (!matcher.match(r, r.name)) {
9176 continue;
9177 }
9178 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9179 continue;
9180 }
9181 if (!printed) {
9182 pw.println(" Active services:");
9183 printed = true;
9184 }
9185 if (needSep) {
9186 pw.println();
9187 }
9188 pw.print(" * ");
9189 pw.println(r);
9190 if (dumpAll) {
9191 r.dump(pw, " ");
9192 needSep = true;
9193 } else {
9194 pw.print(" app=");
9195 pw.println(r.app);
9196 pw.print(" created=");
9197 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9198 pw.print(" started=");
9199 pw.print(r.startRequested);
9200 pw.print(" connections=");
9201 pw.println(r.connections.size());
9202 if (r.connections.size() > 0) {
9203 pw.println(" Connections:");
9204 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9205 for (int i = 0; i < clist.size(); i++) {
9206 ConnectionRecord conn = clist.get(i);
9207 pw.print(" ");
9208 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009209 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009210 pw.print(" -> ");
9211 ProcessRecord proc = conn.binding.client;
9212 pw.println(proc != null ? proc.toShortString() : "null");
9213 }
9214 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009215 }
9216 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009217 if (dumpClient && r.app != null && r.app.thread != null) {
9218 pw.println(" Client:");
9219 pw.flush();
9220 try {
9221 TransferPipe tp = new TransferPipe();
9222 try {
9223 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9224 r, args);
9225 tp.setBufferPrefix(" ");
9226 // Short timeout, since blocking here can
9227 // deadlock with the application.
9228 tp.go(fd, 2000);
9229 } finally {
9230 tp.kill();
9231 }
9232 } catch (IOException e) {
9233 pw.println(" Failure while dumping the service: " + e);
9234 } catch (RemoteException e) {
9235 pw.println(" Got a RemoteException while dumping the service");
9236 }
9237 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009238 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009240 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009243 } catch (RemoteException re) {
9244
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009248 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009249 for (int i=0; i<mPendingServices.size(); i++) {
9250 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009251 if (!matcher.match(r, r.name)) {
9252 continue;
9253 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9255 continue;
9256 }
9257 if (!printed) {
9258 if (needSep) pw.println(" ");
9259 needSep = true;
9260 pw.println(" Pending services:");
9261 printed = true;
9262 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263 pw.print(" * Pending "); pw.println(r);
9264 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 needSep = true;
9267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009270 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 for (int i=0; i<mRestartingServices.size(); i++) {
9272 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009273 if (!matcher.match(r, r.name)) {
9274 continue;
9275 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009276 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9277 continue;
9278 }
9279 if (!printed) {
9280 if (needSep) pw.println(" ");
9281 needSep = true;
9282 pw.println(" Restarting services:");
9283 printed = true;
9284 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009285 pw.print(" * Restarting "); pw.println(r);
9286 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009288 needSep = true;
9289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009291 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009292 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009293 for (int i=0; i<mStoppingServices.size(); i++) {
9294 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009295 if (!matcher.match(r, r.name)) {
9296 continue;
9297 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009298 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9299 continue;
9300 }
9301 if (!printed) {
9302 if (needSep) pw.println(" ");
9303 needSep = true;
9304 pw.println(" Stopping services:");
9305 printed = true;
9306 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009307 pw.print(" * Stopping "); pw.println(r);
9308 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009310 needSep = true;
9311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009315 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009316 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 = mServiceConnections.values().iterator();
9318 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009319 ArrayList<ConnectionRecord> r = it.next();
9320 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009321 ConnectionRecord cr = r.get(i);
9322 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9323 continue;
9324 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009325 if (dumpPackage != null && (cr.binding.client == null
9326 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9327 continue;
9328 }
9329 if (!printed) {
9330 if (needSep) pw.println(" ");
9331 needSep = true;
9332 pw.println(" Connection bindings to services:");
9333 printed = true;
9334 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009335 pw.print(" * "); pw.println(cr);
9336 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009339 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 }
9341 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009342
9343 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 }
9345
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009346 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009347 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009348 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009350 ItemMatcher matcher = new ItemMatcher();
9351 matcher.build(args, opti);
9352
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009353 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009354
9355 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009356
9357 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009358 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009359 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009360 ContentProviderRecord r = mLaunchingProviders.get(i);
9361 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9362 continue;
9363 }
9364 if (!printed) {
9365 if (needSep) pw.println(" ");
9366 needSep = true;
9367 pw.println(" Launching content providers:");
9368 printed = true;
9369 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009370 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009371 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009372 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373 }
9374
9375 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 if (needSep) pw.println();
9377 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009378 pw.println("Granted Uri Permissions:");
9379 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9380 int uid = mGrantedUriPermissions.keyAt(i);
9381 HashMap<Uri, UriPermission> perms
9382 = mGrantedUriPermissions.valueAt(i);
9383 pw.print(" * UID "); pw.print(uid);
9384 pw.println(" holds:");
9385 for (UriPermission perm : perms.values()) {
9386 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009387 if (dumpAll) {
9388 perm.dump(pw, " ");
9389 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009390 }
9391 }
9392 needSep = true;
9393 }
9394
9395 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396 }
9397
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009398 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009399 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009400 boolean needSep = false;
9401
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009402 if (mIntentSenderRecords.size() > 0) {
9403 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009404 Iterator<WeakReference<PendingIntentRecord>> it
9405 = mIntentSenderRecords.values().iterator();
9406 while (it.hasNext()) {
9407 WeakReference<PendingIntentRecord> ref = it.next();
9408 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 if (dumpPackage != null && (rec == null
9410 || !dumpPackage.equals(rec.key.packageName))) {
9411 continue;
9412 }
9413 if (!printed) {
9414 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9415 printed = true;
9416 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009417 needSep = true;
9418 if (rec != null) {
9419 pw.print(" * "); pw.println(rec);
9420 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 } else {
9424 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425 }
9426 }
9427 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009428
9429 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430 }
9431
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009432 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009433 String prefix, String label, boolean complete, boolean brief, boolean client,
9434 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009436 boolean needNL = false;
9437 final String innerPrefix = prefix + " ";
9438 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009440 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009441 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9442 continue;
9443 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009444 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009445 if (needNL) {
9446 pw.println(" ");
9447 needNL = false;
9448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 if (lastTask != r.task) {
9450 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009451 pw.print(prefix);
9452 pw.print(full ? "* " : " ");
9453 pw.println(lastTask);
9454 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009455 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009456 } else if (complete) {
9457 // Complete + brief == give a summary. Isn't that obvious?!?
9458 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009459 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009460 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009461 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009464 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9465 pw.print(" #"); pw.print(i); pw.print(": ");
9466 pw.println(r);
9467 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009468 r.dump(pw, innerPrefix);
9469 } else if (complete) {
9470 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009471 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009472 if (r.app != null) {
9473 pw.print(innerPrefix); pw.println(r.app);
9474 }
9475 }
9476 if (client && r.app != null && r.app.thread != null) {
9477 // flush anything that is already in the PrintWriter since the thread is going
9478 // to write to the file descriptor directly
9479 pw.flush();
9480 try {
9481 TransferPipe tp = new TransferPipe();
9482 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009483 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9484 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009485 // Short timeout, since blocking here can
9486 // deadlock with the application.
9487 tp.go(fd, 2000);
9488 } finally {
9489 tp.kill();
9490 }
9491 } catch (IOException e) {
9492 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9493 } catch (RemoteException e) {
9494 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9495 }
9496 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498 }
9499 }
9500
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009501 private static String buildOomTag(String prefix, String space, int val, int base) {
9502 if (val == base) {
9503 if (space == null) return prefix;
9504 return prefix + " ";
9505 }
9506 return prefix + "+" + Integer.toString(val-base);
9507 }
9508
9509 private static final int dumpProcessList(PrintWriter pw,
9510 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009511 String prefix, String normalLabel, String persistentLabel,
9512 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009514 final int N = list.size()-1;
9515 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009517 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9518 continue;
9519 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009520 pw.println(String.format("%s%s #%2d: %s",
9521 prefix, (r.persistent ? persistentLabel : normalLabel),
9522 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523 if (r.persistent) {
9524 numPers++;
9525 }
9526 }
9527 return numPers;
9528 }
9529
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009530 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009531 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009532 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009533 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009534
Dianne Hackborn905577f2011-09-07 18:31:28 -07009535 ArrayList<Pair<ProcessRecord, Integer>> list
9536 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9537 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009538 ProcessRecord r = origList.get(i);
9539 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9540 continue;
9541 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009542 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9543 }
9544
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 if (list.size() <= 0) {
9546 return false;
9547 }
9548
Dianne Hackborn905577f2011-09-07 18:31:28 -07009549 Comparator<Pair<ProcessRecord, Integer>> comparator
9550 = new Comparator<Pair<ProcessRecord, Integer>>() {
9551 @Override
9552 public int compare(Pair<ProcessRecord, Integer> object1,
9553 Pair<ProcessRecord, Integer> object2) {
9554 if (object1.first.setAdj != object2.first.setAdj) {
9555 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9556 }
9557 if (object1.second.intValue() != object2.second.intValue()) {
9558 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9559 }
9560 return 0;
9561 }
9562 };
9563
9564 Collections.sort(list, comparator);
9565
Dianne Hackborn287952c2010-09-22 22:34:31 -07009566 final long curRealtime = SystemClock.elapsedRealtime();
9567 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9568 final long curUptime = SystemClock.uptimeMillis();
9569 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9570
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009571 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009572 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009573 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009574 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009575 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009576 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9577 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009578 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9579 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009580 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9581 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009582 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9583 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009584 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009585 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009586 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9587 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9588 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9589 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9590 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9591 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9592 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9593 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009594 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9595 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009596 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9597 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009598 } else {
9599 oomAdj = Integer.toString(r.setAdj);
9600 }
9601 String schedGroup;
9602 switch (r.setSchedGroup) {
9603 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9604 schedGroup = "B";
9605 break;
9606 case Process.THREAD_GROUP_DEFAULT:
9607 schedGroup = "F";
9608 break;
9609 default:
9610 schedGroup = Integer.toString(r.setSchedGroup);
9611 break;
9612 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009613 String foreground;
9614 if (r.foregroundActivities) {
9615 foreground = "A";
9616 } else if (r.foregroundServices) {
9617 foreground = "S";
9618 } else {
9619 foreground = " ";
9620 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009621 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009622 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9624 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009625 if (r.adjSource != null || r.adjTarget != null) {
9626 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009627 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009628 if (r.adjTarget instanceof ComponentName) {
9629 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9630 } else if (r.adjTarget != null) {
9631 pw.print(r.adjTarget.toString());
9632 } else {
9633 pw.print("{null}");
9634 }
9635 pw.print("<=");
9636 if (r.adjSource instanceof ProcessRecord) {
9637 pw.print("Proc{");
9638 pw.print(((ProcessRecord)r.adjSource).toShortString());
9639 pw.println("}");
9640 } else if (r.adjSource != null) {
9641 pw.println(r.adjSource.toString());
9642 } else {
9643 pw.println("{null}");
9644 }
9645 }
9646 if (inclDetails) {
9647 pw.print(prefix);
9648 pw.print(" ");
9649 pw.print("oom: max="); pw.print(r.maxAdj);
9650 pw.print(" hidden="); pw.print(r.hiddenAdj);
9651 pw.print(" curRaw="); pw.print(r.curRawAdj);
9652 pw.print(" setRaw="); pw.print(r.setRawAdj);
9653 pw.print(" cur="); pw.print(r.curAdj);
9654 pw.print(" set="); pw.println(r.setAdj);
9655 pw.print(prefix);
9656 pw.print(" ");
9657 pw.print("keeping="); pw.print(r.keeping);
9658 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009659 pw.print(" empty="); pw.print(r.empty);
9660 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009661
9662 if (!r.keeping) {
9663 if (r.lastWakeTime != 0) {
9664 long wtime;
9665 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9666 synchronized (stats) {
9667 wtime = stats.getProcessWakeTime(r.info.uid,
9668 r.pid, curRealtime);
9669 }
9670 long timeUsed = wtime - r.lastWakeTime;
9671 pw.print(prefix);
9672 pw.print(" ");
9673 pw.print("keep awake over ");
9674 TimeUtils.formatDuration(realtimeSince, pw);
9675 pw.print(" used ");
9676 TimeUtils.formatDuration(timeUsed, pw);
9677 pw.print(" (");
9678 pw.print((timeUsed*100)/realtimeSince);
9679 pw.println("%)");
9680 }
9681 if (r.lastCpuTime != 0) {
9682 long timeUsed = r.curCpuTime - r.lastCpuTime;
9683 pw.print(prefix);
9684 pw.print(" ");
9685 pw.print("run cpu over ");
9686 TimeUtils.formatDuration(uptimeSince, pw);
9687 pw.print(" used ");
9688 TimeUtils.formatDuration(timeUsed, pw);
9689 pw.print(" (");
9690 pw.print((timeUsed*100)/uptimeSince);
9691 pw.println("%)");
9692 }
9693 }
9694 }
9695 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009696 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009697 }
9698
Dianne Hackbornb437e092011-08-05 17:50:29 -07009699 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700 ArrayList<ProcessRecord> procs;
9701 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009702 if (args != null && args.length > start
9703 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009704 procs = new ArrayList<ProcessRecord>();
9705 int pid = -1;
9706 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009707 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009708 } catch (NumberFormatException e) {
9709
9710 }
9711 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9712 ProcessRecord proc = mLruProcesses.get(i);
9713 if (proc.pid == pid) {
9714 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009715 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009716 procs.add(proc);
9717 }
9718 }
9719 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009720 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009721 return null;
9722 }
9723 } else {
9724 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9725 }
9726 }
9727 return procs;
9728 }
9729
9730 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9731 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009732 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009733 if (procs == null) {
9734 return;
9735 }
9736
9737 long uptime = SystemClock.uptimeMillis();
9738 long realtime = SystemClock.elapsedRealtime();
9739 pw.println("Applications Graphics Acceleration Info:");
9740 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9741
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009742 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9743 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009744 if (r.thread != null) {
9745 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9746 pw.flush();
9747 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009748 TransferPipe tp = new TransferPipe();
9749 try {
9750 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9751 tp.go(fd);
9752 } finally {
9753 tp.kill();
9754 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009756 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009757 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009758 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009759 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009760 pw.flush();
9761 }
9762 }
9763 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009764 }
9765
Jeff Brown6754ba22011-12-14 20:20:01 -08009766 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9767 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9768 if (procs == null) {
9769 return;
9770 }
9771
9772 pw.println("Applications Database Info:");
9773
9774 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9775 ProcessRecord r = procs.get(i);
9776 if (r.thread != null) {
9777 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9778 pw.flush();
9779 try {
9780 TransferPipe tp = new TransferPipe();
9781 try {
9782 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9783 tp.go(fd);
9784 } finally {
9785 tp.kill();
9786 }
9787 } catch (IOException e) {
9788 pw.println("Failure while dumping the app: " + r);
9789 pw.flush();
9790 } catch (RemoteException e) {
9791 pw.println("Got a RemoteException while dumping the app " + r);
9792 pw.flush();
9793 }
9794 }
9795 }
9796 }
9797
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009798 final static class MemItem {
9799 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009800 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009801 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009802 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009803 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009804
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009805 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009806 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009807 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009808 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009809 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009810 }
9811 }
9812
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009813 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009814 boolean sort) {
9815 if (sort) {
9816 Collections.sort(items, new Comparator<MemItem>() {
9817 @Override
9818 public int compare(MemItem lhs, MemItem rhs) {
9819 if (lhs.pss < rhs.pss) {
9820 return 1;
9821 } else if (lhs.pss > rhs.pss) {
9822 return -1;
9823 }
9824 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009825 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009826 });
9827 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009828
9829 for (int i=0; i<items.size(); i++) {
9830 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009831 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009832 if (mi.subitems != null) {
9833 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9834 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009835 }
9836 }
9837
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009838 // These are in KB.
9839 static final long[] DUMP_MEM_BUCKETS = new long[] {
9840 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9841 120*1024, 160*1024, 200*1024,
9842 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9843 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9844 };
9845
Dianne Hackborn672342c2011-11-29 11:29:02 -08009846 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9847 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009848 int start = label.lastIndexOf('.');
9849 if (start >= 0) start++;
9850 else start = 0;
9851 int end = label.length();
9852 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9853 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9854 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9855 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009856 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009857 out.append(label, start, end);
9858 return;
9859 }
9860 }
9861 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009862 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009863 out.append(label, start, end);
9864 }
9865
9866 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9867 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9868 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9869 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9870 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9871 };
9872 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9873 "System", "Persistent", "Foreground",
9874 "Visible", "Perceptible", "Heavy Weight",
9875 "Backup", "A Services", "Home", "Previous",
9876 "B Services", "Background"
9877 };
9878
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009879 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009880 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009881 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009882 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009883 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009884
9885 int opti = 0;
9886 while (opti < args.length) {
9887 String opt = args[opti];
9888 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9889 break;
9890 }
9891 opti++;
9892 if ("-a".equals(opt)) {
9893 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009894 } else if ("--oom".equals(opt)) {
9895 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009896 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009897 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009898 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009899 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -07009900 pw.println("If [process] is specified it can be the name or ");
9901 pw.println("pid of a specific process to dump.");
9902 return;
9903 } else {
9904 pw.println("Unknown argument: " + opt + "; use -h for help");
9905 }
9906 }
9907
9908 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009909 if (procs == null) {
9910 return;
9911 }
9912
Dianne Hackborn6447ca32009-04-07 19:50:08 -07009913 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009914 long uptime = SystemClock.uptimeMillis();
9915 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -07009916
9917 if (procs.size() == 1 || isCheckinRequest) {
9918 dumpAll = true;
9919 }
9920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 if (isCheckinRequest) {
9922 // short checkin version
9923 pw.println(uptime + "," + realtime);
9924 pw.flush();
9925 } else {
9926 pw.println("Applications Memory Usage (kB):");
9927 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9928 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009929
Dianne Hackbornb437e092011-08-05 17:50:29 -07009930 String[] innerArgs = new String[args.length-opti];
9931 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
9932
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009933 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
9934 long nativePss=0, dalvikPss=0, otherPss=0;
9935 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
9936
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009937 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
9938 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
9939 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -07009940
9941 long totalPss = 0;
9942
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009943 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9944 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009945 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009946 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009947 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
9948 pw.flush();
9949 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009950 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009951 if (dumpAll) {
9952 try {
9953 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
9954 } catch (RemoteException e) {
9955 if (!isCheckinRequest) {
9956 pw.println("Got RemoteException!");
9957 pw.flush();
9958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009959 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009960 } else {
9961 mi = new Debug.MemoryInfo();
9962 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009963 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009964
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009965 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009966 long myTotalPss = mi.getTotalPss();
9967 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009968 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009970 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009971
9972 nativePss += mi.nativePss;
9973 dalvikPss += mi.dalvikPss;
9974 otherPss += mi.otherPss;
9975 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
9976 long mem = mi.getOtherPss(j);
9977 miscPss[j] += mem;
9978 otherPss -= mem;
9979 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009980
9981 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
9983 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009984 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009985 if (oomProcs[oomIndex] == null) {
9986 oomProcs[oomIndex] = new ArrayList<MemItem>();
9987 }
9988 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009989 break;
9990 }
9991 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993 }
9994 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009995
9996 if (!isCheckinRequest && procs.size() > 1) {
9997 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
9998
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009999 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10000 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10001 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010002 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010003 String label = Debug.MemoryInfo.getOtherLabel(j);
10004 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010005 }
10006
Dianne Hackbornb437e092011-08-05 17:50:29 -070010007 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10008 for (int j=0; j<oomPss.length; j++) {
10009 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010010 String label = DUMP_MEM_OOM_LABEL[j];
10011 MemItem item = new MemItem(label, label, oomPss[j],
10012 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010013 item.subitems = oomProcs[j];
10014 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010015 }
10016 }
10017
Dianne Hackborn672342c2011-11-29 11:29:02 -080010018 if (outTag != null || outStack != null) {
10019 if (outTag != null) {
10020 appendMemBucket(outTag, totalPss, "total", false);
10021 }
10022 if (outStack != null) {
10023 appendMemBucket(outStack, totalPss, "total", true);
10024 }
10025 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010026 for (int i=0; i<oomMems.size(); i++) {
10027 MemItem miCat = oomMems.get(i);
10028 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10029 continue;
10030 }
10031 if (miCat.id < ProcessList.SERVICE_ADJ
10032 || miCat.id == ProcessList.HOME_APP_ADJ
10033 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010034 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10035 outTag.append(" / ");
10036 }
10037 if (outStack != null) {
10038 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10039 if (firstLine) {
10040 outStack.append(":");
10041 firstLine = false;
10042 }
10043 outStack.append("\n\t at ");
10044 } else {
10045 outStack.append("$");
10046 }
10047 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010048 for (int j=0; j<miCat.subitems.size(); j++) {
10049 MemItem mi = miCat.subitems.get(j);
10050 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010051 if (outTag != null) {
10052 outTag.append(" ");
10053 }
10054 if (outStack != null) {
10055 outStack.append("$");
10056 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010057 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010058 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10059 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10060 }
10061 if (outStack != null) {
10062 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10063 }
10064 }
10065 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10066 outStack.append("(");
10067 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10068 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10069 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10070 outStack.append(":");
10071 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10072 }
10073 }
10074 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010075 }
10076 }
10077 }
10078 }
10079
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010080 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010081 pw.println();
10082 pw.println("Total PSS by process:");
10083 dumpMemItems(pw, " ", procMems, true);
10084 pw.println();
10085 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010086 pw.println("Total PSS by OOM adjustment:");
10087 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010088 if (!oomOnly) {
10089 PrintWriter out = categoryPw != null ? categoryPw : pw;
10090 out.println();
10091 out.println("Total PSS by category:");
10092 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010093 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010094 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010095 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010097 }
10098
10099 /**
10100 * Searches array of arguments for the specified string
10101 * @param args array of argument strings
10102 * @param value value to search for
10103 * @return true if the value is contained in the array
10104 */
10105 private static boolean scanArgs(String[] args, String value) {
10106 if (args != null) {
10107 for (String arg : args) {
10108 if (value.equals(arg)) {
10109 return true;
10110 }
10111 }
10112 }
10113 return false;
10114 }
10115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010116 private final void killServicesLocked(ProcessRecord app,
10117 boolean allowRestart) {
10118 // Report disconnected services.
10119 if (false) {
10120 // XXX we are letting the client link to the service for
10121 // death notifications.
10122 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010123 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010124 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010125 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010126 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010127 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 = r.connections.values().iterator();
10129 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010130 ArrayList<ConnectionRecord> cl = jt.next();
10131 for (int i=0; i<cl.size(); i++) {
10132 ConnectionRecord c = cl.get(i);
10133 if (c.binding.client != app) {
10134 try {
10135 //c.conn.connected(r.className, null);
10136 } catch (Exception e) {
10137 // todo: this should be asynchronous!
10138 Slog.w(TAG, "Exception thrown disconnected servce "
10139 + r.shortName
10140 + " from app " + app.processName, e);
10141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010142 }
10143 }
10144 }
10145 }
10146 }
10147 }
10148 }
10149
10150 // Clean up any connections this application has to other services.
10151 if (app.connections.size() > 0) {
10152 Iterator<ConnectionRecord> it = app.connections.iterator();
10153 while (it.hasNext()) {
10154 ConnectionRecord r = it.next();
10155 removeConnectionLocked(r, app, null);
10156 }
10157 }
10158 app.connections.clear();
10159
10160 if (app.services.size() != 0) {
10161 // Any services running in the application need to be placed
10162 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010163 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010164 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010165 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166 synchronized (sr.stats.getBatteryStats()) {
10167 sr.stats.stopLaunchedLocked();
10168 }
10169 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010170 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010171 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010172 if (mStoppingServices.remove(sr)) {
10173 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10174 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010175
10176 boolean hasClients = sr.bindings.size() > 0;
10177 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010178 Iterator<IntentBindRecord> bindings
10179 = sr.bindings.values().iterator();
10180 while (bindings.hasNext()) {
10181 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010182 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010183 + ": shouldUnbind=" + b.hasBound);
10184 b.binder = null;
10185 b.requested = b.received = b.hasBound = false;
10186 }
10187 }
10188
Dianne Hackborn070783f2010-12-29 16:46:28 -080010189 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10190 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010191 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010192 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010193 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010194 sr.crashCount, sr.shortName, app.pid);
10195 bringDownServiceLocked(sr, true);
10196 } else if (!allowRestart) {
10197 bringDownServiceLocked(sr, true);
10198 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010199 boolean canceled = scheduleServiceRestartLocked(sr, true);
10200
10201 // Should the service remain running? Note that in the
10202 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010203 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010204 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10205 if (sr.pendingStarts.size() == 0) {
10206 sr.startRequested = false;
10207 if (!hasClients) {
10208 // Whoops, no reason to restart!
10209 bringDownServiceLocked(sr, true);
10210 }
10211 }
10212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010213 }
10214 }
10215
10216 if (!allowRestart) {
10217 app.services.clear();
10218 }
10219 }
10220
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010221 // Make sure we have no more records on the stopping list.
10222 int i = mStoppingServices.size();
10223 while (i > 0) {
10224 i--;
10225 ServiceRecord sr = mStoppingServices.get(i);
10226 if (sr.app == app) {
10227 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010228 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010229 }
10230 }
10231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010232 app.executingServices.clear();
10233 }
10234
10235 private final void removeDyingProviderLocked(ProcessRecord proc,
10236 ContentProviderRecord cpr) {
10237 synchronized (cpr) {
10238 cpr.launchingApp = null;
10239 cpr.notifyAll();
10240 }
10241
Amith Yamasani742a6712011-05-04 14:49:28 -070010242 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010243 String names[] = cpr.info.authority.split(";");
10244 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010245 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010246 }
10247
10248 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10249 while (cit.hasNext()) {
10250 ProcessRecord capp = cit.next();
10251 if (!capp.persistent && capp.thread != null
10252 && capp.pid != 0
10253 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010254 Slog.i(TAG, "Kill " + capp.processName
10255 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010256 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010257 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010258 capp.processName, capp.setAdj, "dying provider "
10259 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010260 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010261 }
10262 }
10263
10264 mLaunchingProviders.remove(cpr);
10265 }
10266
10267 /**
10268 * Main code for cleaning up a process when it has gone away. This is
10269 * called both as a result of the process dying, or directly when stopping
10270 * a process when running in single process mode.
10271 */
10272 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010273 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010274 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010275 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010276 }
10277
Dianne Hackborn36124872009-10-08 16:22:03 -070010278 mProcessesToGc.remove(app);
10279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010280 // Dismiss any open dialogs.
10281 if (app.crashDialog != null) {
10282 app.crashDialog.dismiss();
10283 app.crashDialog = null;
10284 }
10285 if (app.anrDialog != null) {
10286 app.anrDialog.dismiss();
10287 app.anrDialog = null;
10288 }
10289 if (app.waitDialog != null) {
10290 app.waitDialog.dismiss();
10291 app.waitDialog = null;
10292 }
10293
10294 app.crashing = false;
10295 app.notResponding = false;
10296
10297 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010298 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010299 app.thread = null;
10300 app.forcingToForeground = null;
10301 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010302 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010303 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010304 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010305
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010306 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010307
10308 boolean restart = false;
10309
10310 int NL = mLaunchingProviders.size();
10311
10312 // Remove published content providers.
10313 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010314 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010315 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010316 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010317 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010318 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319
10320 // See if someone is waiting for this provider... in which
10321 // case we don't remove it, but just let it restart.
10322 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010323 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010324 for (; i<NL; i++) {
10325 if (mLaunchingProviders.get(i) == cpr) {
10326 restart = true;
10327 break;
10328 }
10329 }
10330 } else {
10331 i = NL;
10332 }
10333
10334 if (i >= NL) {
10335 removeDyingProviderLocked(app, cpr);
10336 NL = mLaunchingProviders.size();
10337 }
10338 }
10339 app.pubProviders.clear();
10340 }
10341
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010342 // Take care of any launching providers waiting for this process.
10343 if (checkAppInLaunchingProvidersLocked(app, false)) {
10344 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010345 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 // Unregister from connected content providers.
10348 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010349 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 while (it.hasNext()) {
10351 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10352 cpr.clients.remove(app);
10353 }
10354 app.conProviders.clear();
10355 }
10356
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010357 // At this point there may be remaining entries in mLaunchingProviders
10358 // where we were the only one waiting, so they are no longer of use.
10359 // Look for these and clean up if found.
10360 // XXX Commented out for now. Trying to figure out a way to reproduce
10361 // the actual situation to identify what is actually going on.
10362 if (false) {
10363 for (int i=0; i<NL; i++) {
10364 ContentProviderRecord cpr = (ContentProviderRecord)
10365 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010366 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010367 synchronized (cpr) {
10368 cpr.launchingApp = null;
10369 cpr.notifyAll();
10370 }
10371 }
10372 }
10373 }
10374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 skipCurrentReceiverLocked(app);
10376
10377 // Unregister any receivers.
10378 if (app.receivers.size() > 0) {
10379 Iterator<ReceiverList> it = app.receivers.iterator();
10380 while (it.hasNext()) {
10381 removeReceiverLocked(it.next());
10382 }
10383 app.receivers.clear();
10384 }
10385
Christopher Tate181fafa2009-05-14 11:12:14 -070010386 // If the app is undergoing backup, tell the backup manager about it
10387 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010388 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010389 try {
10390 IBackupManager bm = IBackupManager.Stub.asInterface(
10391 ServiceManager.getService(Context.BACKUP_SERVICE));
10392 bm.agentDisconnected(app.info.packageName);
10393 } catch (RemoteException e) {
10394 // can't happen; backup manager is local
10395 }
10396 }
10397
Jeff Sharkey287bd832011-05-28 19:36:26 -070010398 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010400 // If the caller is restarting this app, then leave it in its
10401 // current lists and let the caller take care of it.
10402 if (restarting) {
10403 return;
10404 }
10405
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010406 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010407 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010408 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010409 mProcessNames.remove(app.processName, app.uid);
10410 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010411 if (mHeavyWeightProcess == app) {
10412 mHeavyWeightProcess = null;
10413 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 } else if (!app.removed) {
10416 // This app is persistent, so we need to keep its record around.
10417 // If it is not already on the pending app list, add it there
10418 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010419 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10420 mPersistentStartingProcesses.add(app);
10421 restart = true;
10422 }
10423 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010424 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10425 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 mProcessesOnHold.remove(app);
10427
The Android Open Source Project4df24232009-03-05 14:34:35 -080010428 if (app == mHomeProcess) {
10429 mHomeProcess = null;
10430 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010431 if (app == mPreviousProcess) {
10432 mPreviousProcess = null;
10433 }
10434
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010435 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 // We have components that still need to be running in the
10437 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010438 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010439 startProcessLocked(app, "restart", app.processName);
10440 } else if (app.pid > 0 && app.pid != MY_PID) {
10441 // Goodbye!
10442 synchronized (mPidsSelfLocked) {
10443 mPidsSelfLocked.remove(app.pid);
10444 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10445 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010446 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010447 }
10448 }
10449
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010450 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10451 // Look through the content providers we are waiting to have launched,
10452 // and if any run in this process then either schedule a restart of
10453 // the process or kill the client waiting for it if this process has
10454 // gone bad.
10455 int NL = mLaunchingProviders.size();
10456 boolean restart = false;
10457 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010458 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010459 if (cpr.launchingApp == app) {
10460 if (!alwaysBad && !app.bad) {
10461 restart = true;
10462 } else {
10463 removeDyingProviderLocked(app, cpr);
10464 NL = mLaunchingProviders.size();
10465 }
10466 }
10467 }
10468 return restart;
10469 }
10470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010471 // =========================================================
10472 // SERVICES
10473 // =========================================================
10474
10475 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10476 ActivityManager.RunningServiceInfo info =
10477 new ActivityManager.RunningServiceInfo();
10478 info.service = r.name;
10479 if (r.app != null) {
10480 info.pid = r.app.pid;
10481 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010482 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 info.process = r.processName;
10484 info.foreground = r.isForeground;
10485 info.activeSince = r.createTime;
10486 info.started = r.startRequested;
10487 info.clientCount = r.connections.size();
10488 info.crashCount = r.crashCount;
10489 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010490 if (r.isForeground) {
10491 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10492 }
10493 if (r.startRequested) {
10494 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10495 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010496 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010497 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10498 }
10499 if (r.app != null && r.app.persistent) {
10500 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10501 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010502
10503 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10504 for (int i=0; i<connl.size(); i++) {
10505 ConnectionRecord conn = connl.get(i);
10506 if (conn.clientLabel != 0) {
10507 info.clientPackage = conn.binding.client.info.packageName;
10508 info.clientLabel = conn.clientLabel;
10509 return info;
10510 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010511 }
10512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 return info;
10514 }
10515
10516 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10517 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010518 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 synchronized (this) {
10520 ArrayList<ActivityManager.RunningServiceInfo> res
10521 = new ArrayList<ActivityManager.RunningServiceInfo>();
10522
Amith Yamasani742a6712011-05-04 14:49:28 -070010523 int userId = UserId.getUserId(Binder.getCallingUid());
10524 if (mServiceMap.getAllServices(userId).size() > 0) {
10525 Iterator<ServiceRecord> it
10526 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 while (it.hasNext() && res.size() < maxNum) {
10528 res.add(makeRunningServiceInfoLocked(it.next()));
10529 }
10530 }
10531
10532 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10533 ServiceRecord r = mRestartingServices.get(i);
10534 ActivityManager.RunningServiceInfo info =
10535 makeRunningServiceInfoLocked(r);
10536 info.restarting = r.nextRestartTime;
10537 res.add(info);
10538 }
10539
10540 return res;
10541 }
10542 }
10543
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010544 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010545 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010546 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010547 int userId = UserId.getUserId(Binder.getCallingUid());
10548 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010549 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010550 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10551 for (int i=0; i<conn.size(); i++) {
10552 if (conn.get(i).clientIntent != null) {
10553 return conn.get(i).clientIntent;
10554 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010555 }
10556 }
10557 }
10558 }
10559 return null;
10560 }
10561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 private final ServiceRecord findServiceLocked(ComponentName name,
10563 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010564 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 return r == token ? r : null;
10566 }
10567
10568 private final class ServiceLookupResult {
10569 final ServiceRecord record;
10570 final String permission;
10571
10572 ServiceLookupResult(ServiceRecord _record, String _permission) {
10573 record = _record;
10574 permission = _permission;
10575 }
10576 };
10577
10578 private ServiceLookupResult findServiceLocked(Intent service,
10579 String resolvedType) {
10580 ServiceRecord r = null;
10581 if (service.getComponent() != null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010582 r = mServiceMap.getServiceByName(service.getComponent(), Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010583 }
10584 if (r == null) {
10585 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani742a6712011-05-04 14:49:28 -070010586 r = mServiceMap.getServiceByIntent(filter, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010587 }
10588
10589 if (r == null) {
10590 try {
10591 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010592 AppGlobals.getPackageManager().resolveService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 service, resolvedType, 0);
10594 ServiceInfo sInfo =
10595 rInfo != null ? rInfo.serviceInfo : null;
10596 if (sInfo == null) {
10597 return null;
10598 }
10599
10600 ComponentName name = new ComponentName(
10601 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010602 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 } catch (RemoteException ex) {
10604 // pm is in same process, this will never happen.
10605 }
10606 }
10607 if (r != null) {
10608 int callingPid = Binder.getCallingPid();
10609 int callingUid = Binder.getCallingUid();
10610 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010611 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010612 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010613 if (!r.exported) {
10614 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10615 + " from pid=" + callingPid
10616 + ", uid=" + callingUid
10617 + " that is not exported from uid " + r.appInfo.uid);
10618 return new ServiceLookupResult(null, "not exported from uid "
10619 + r.appInfo.uid);
10620 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010621 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 + " from pid=" + callingPid
10623 + ", uid=" + callingUid
10624 + " requires " + r.permission);
10625 return new ServiceLookupResult(null, r.permission);
10626 }
10627 return new ServiceLookupResult(r, null);
10628 }
10629 return null;
10630 }
10631
10632 private class ServiceRestarter implements Runnable {
10633 private ServiceRecord mService;
10634
10635 void setService(ServiceRecord service) {
10636 mService = service;
10637 }
10638
10639 public void run() {
10640 synchronized(ActivityManagerService.this) {
10641 performServiceRestartLocked(mService);
10642 }
10643 }
10644 }
10645
10646 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010647 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010649 if (DEBUG_SERVICE)
10650 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010651 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010654 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010655 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010656 if (r == null) {
10657 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010658 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 if (r == null) {
10661 try {
10662 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010663 AppGlobals.getPackageManager().resolveService(
Dianne Hackborn1655be42009-05-08 14:29:01 -070010664 service, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 ServiceInfo sInfo =
10666 rInfo != null ? rInfo.serviceInfo : null;
10667 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010668 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010669 ": not found");
10670 return null;
10671 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010672 if (userId > 0) {
10673 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 ComponentName name = new ComponentName(
10676 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010677 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010678 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010679 Intent.FilterComparison filter = new Intent.FilterComparison(
10680 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 ServiceRestarter res = new ServiceRestarter();
10682 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10683 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10684 synchronized (stats) {
10685 ss = stats.getServiceStatsLocked(
10686 sInfo.applicationInfo.uid, sInfo.packageName,
10687 sInfo.name);
10688 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010689 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010691 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10692 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693
10694 // Make sure this component isn't in the pending list.
10695 int N = mPendingServices.size();
10696 for (int i=0; i<N; i++) {
10697 ServiceRecord pr = mPendingServices.get(i);
10698 if (pr.name.equals(name)) {
10699 mPendingServices.remove(i);
10700 i--;
10701 N--;
10702 }
10703 }
10704 }
10705 } catch (RemoteException ex) {
10706 // pm is in same process, this will never happen.
10707 }
10708 }
10709 if (r != null) {
10710 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010711 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010712 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010713 if (!r.exported) {
10714 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10715 + " from pid=" + callingPid
10716 + ", uid=" + callingUid
10717 + " that is not exported from uid " + r.appInfo.uid);
10718 return new ServiceLookupResult(null, "not exported from uid "
10719 + r.appInfo.uid);
10720 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010721 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010722 + " from pid=" + callingPid
10723 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 + " requires " + r.permission);
10725 return new ServiceLookupResult(null, r.permission);
10726 }
10727 return new ServiceLookupResult(r, null);
10728 }
10729 return null;
10730 }
10731
Dianne Hackborn287952c2010-09-22 22:34:31 -070010732 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10733 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10734 + why + " of " + r + " in app " + r.app);
10735 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10736 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737 long now = SystemClock.uptimeMillis();
10738 if (r.executeNesting == 0 && r.app != null) {
10739 if (r.app.executingServices.size() == 0) {
10740 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10741 msg.obj = r.app;
10742 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10743 }
10744 r.app.executingServices.add(r);
10745 }
10746 r.executeNesting++;
10747 r.executingStart = now;
10748 }
10749
10750 private final void sendServiceArgsLocked(ServiceRecord r,
10751 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010752 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 if (N == 0) {
10754 return;
10755 }
10756
Dianne Hackborn39792d22010-08-19 18:01:52 -070010757 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010759 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010760 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10761 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010762 if (si.intent == null && N > 1) {
10763 // If somehow we got a dummy null intent in the middle,
10764 // then skip it. DO NOT skip a null intent when it is
10765 // the only one in the list -- this is to support the
10766 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010767 continue;
10768 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010769 si.deliveredTime = SystemClock.uptimeMillis();
10770 r.deliveredStarts.add(si);
10771 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010772 if (si.neededGrants != null) {
10773 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10774 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010775 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010776 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 if (!oomAdjusted) {
10778 oomAdjusted = true;
10779 updateOomAdjLocked(r.app);
10780 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010781 int flags = 0;
10782 if (si.deliveryCount > 0) {
10783 flags |= Service.START_FLAG_RETRY;
10784 }
10785 if (si.doneExecutingCount > 0) {
10786 flags |= Service.START_FLAG_REDELIVERY;
10787 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010788 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010789 } catch (RemoteException e) {
10790 // Remote process gone... we'll let the normal cleanup take
10791 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010792 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010793 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010794 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010795 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 break;
10797 }
10798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 }
10800
10801 private final boolean requestServiceBindingLocked(ServiceRecord r,
10802 IntentBindRecord i, boolean rebind) {
10803 if (r.app == null || r.app.thread == null) {
10804 // If service is not currently running, can't yet bind.
10805 return false;
10806 }
10807 if ((!i.requested || rebind) && i.apps.size() > 0) {
10808 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010809 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10811 if (!rebind) {
10812 i.requested = true;
10813 }
10814 i.hasBound = true;
10815 i.doRebind = false;
10816 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010817 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 return false;
10819 }
10820 }
10821 return true;
10822 }
10823
10824 private final void requestServiceBindingsLocked(ServiceRecord r) {
10825 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10826 while (bindings.hasNext()) {
10827 IntentBindRecord i = bindings.next();
10828 if (!requestServiceBindingLocked(r, i, false)) {
10829 break;
10830 }
10831 }
10832 }
10833
10834 private final void realStartServiceLocked(ServiceRecord r,
10835 ProcessRecord app) throws RemoteException {
10836 if (app.thread == null) {
10837 throw new RemoteException();
10838 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010839 if (DEBUG_MU)
10840 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010841 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010843 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844
10845 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010846 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010847 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848
10849 boolean created = false;
10850 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010851 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010852 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010853 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010855 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 synchronized (r.stats.getBatteryStats()) {
10857 r.stats.startLaunchedLocked();
10858 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010859 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010860 app.thread.scheduleCreateService(r, r.serviceInfo,
10861 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010862 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 created = true;
10864 } finally {
10865 if (!created) {
10866 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010867 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 }
10869 }
10870
10871 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010872
10873 // If the service is in the started state, and there are no
10874 // pending arguments, then fake up one so its onStartCommand() will
10875 // be called.
10876 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010877 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010878 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010879 }
10880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 sendServiceArgsLocked(r, true);
10882 }
10883
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010884 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10885 boolean allowCancel) {
10886 boolean canceled = false;
10887
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010888 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010889 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070010890 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010891
Dianne Hackborn070783f2010-12-29 16:46:28 -080010892 if ((r.serviceInfo.applicationInfo.flags
10893 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10894 minDuration /= 4;
10895 }
10896
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010897 // Any delivered but not yet finished starts should be put back
10898 // on the pending list.
10899 final int N = r.deliveredStarts.size();
10900 if (N > 0) {
10901 for (int i=N-1; i>=0; i--) {
10902 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070010903 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010904 if (si.intent == null) {
10905 // We'll generate this again if needed.
10906 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
10907 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
10908 r.pendingStarts.add(0, si);
10909 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
10910 dur *= 2;
10911 if (minDuration < dur) minDuration = dur;
10912 if (resetTime < dur) resetTime = dur;
10913 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010914 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010915 + r.name);
10916 canceled = true;
10917 }
10918 }
10919 r.deliveredStarts.clear();
10920 }
10921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 r.totalRestartCount++;
10923 if (r.restartDelay == 0) {
10924 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010925 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010926 } else {
10927 // If it has been a "reasonably long time" since the service
10928 // was started, then reset our restart duration back to
10929 // the beginning, so we don't infinitely increase the duration
10930 // on a service that just occasionally gets killed (which is
10931 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010932 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010933 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010934 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080010936 if ((r.serviceInfo.applicationInfo.flags
10937 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
10938 // Services in peristent processes will restart much more
10939 // quickly, since they are pretty important. (Think SystemUI).
10940 r.restartDelay += minDuration/2;
10941 } else {
10942 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
10943 if (r.restartDelay < minDuration) {
10944 r.restartDelay = minDuration;
10945 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947 }
10948 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010949
10950 r.nextRestartTime = now + r.restartDelay;
10951
10952 // Make sure that we don't end up restarting a bunch of services
10953 // all at the same time.
10954 boolean repeat;
10955 do {
10956 repeat = false;
10957 for (int i=mRestartingServices.size()-1; i>=0; i--) {
10958 ServiceRecord r2 = mRestartingServices.get(i);
10959 if (r2 != r && r.nextRestartTime
10960 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
10961 && r.nextRestartTime
10962 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
10963 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
10964 r.restartDelay = r.nextRestartTime - now;
10965 repeat = true;
10966 break;
10967 }
10968 }
10969 } while (repeat);
10970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 if (!mRestartingServices.contains(r)) {
10972 mRestartingServices.add(r);
10973 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010974
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010975 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070010978 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080010980 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080010982 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983 r.shortName, r.restartDelay);
10984
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010985 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 }
10987
10988 final void performServiceRestartLocked(ServiceRecord r) {
10989 if (!mRestartingServices.contains(r)) {
10990 return;
10991 }
10992 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
10993 }
10994
10995 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
10996 if (r.restartDelay == 0) {
10997 return false;
10998 }
10999 r.resetRestartCounter();
11000 mRestartingServices.remove(r);
11001 mHandler.removeCallbacks(r.restarter);
11002 return true;
11003 }
11004
11005 private final boolean bringUpServiceLocked(ServiceRecord r,
11006 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011007 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011008 //r.dump(" ");
11009
Dianne Hackborn36124872009-10-08 16:22:03 -070011010 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 sendServiceArgsLocked(r, false);
11012 return true;
11013 }
11014
11015 if (!whileRestarting && r.restartDelay > 0) {
11016 // If waiting for a restart, then do nothing.
11017 return true;
11018 }
11019
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011020 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011022 // We are now bringing the service up, so no longer in the
11023 // restarting state.
11024 mRestartingServices.remove(r);
11025
Dianne Hackborne7f97212011-02-24 14:40:20 -080011026 // Service is now being launched, its package can't be stopped.
11027 try {
11028 AppGlobals.getPackageManager().setPackageStoppedState(
11029 r.packageName, false);
11030 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011031 } catch (IllegalArgumentException e) {
11032 Slog.w(TAG, "Failed trying to unstop package "
11033 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011034 }
11035
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011036 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011038 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011040 if (!isolated) {
11041 app = getProcessRecordLocked(appName, r.appInfo.uid);
11042 if (DEBUG_MU)
11043 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11044 if (app != null && app.thread != null) {
11045 try {
11046 app.addPackage(r.appInfo.packageName);
11047 realStartServiceLocked(r, app);
11048 return true;
11049 } catch (RemoteException e) {
11050 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11051 }
11052
11053 // If a dead object exception was thrown -- fall through to
11054 // restart the application.
11055 }
11056 } else {
11057 // If this service runs in an isolated process, then each time
11058 // we call startProcessLocked() we will get a new isolated
11059 // process, starting another process if we are currently waiting
11060 // for a previous process to come up. To deal with this, we store
11061 // in the service any current isolated process it is running in or
11062 // waiting to have come up.
11063 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011064 }
11065
Dianne Hackborn36124872009-10-08 16:22:03 -070011066 // Not running -- get it started, and enqueue this service record
11067 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011068 if (app == null) {
11069 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11070 "service", r.name, false, isolated)) == null) {
11071 Slog.w(TAG, "Unable to launch app "
11072 + r.appInfo.packageName + "/"
11073 + r.appInfo.uid + " for service "
11074 + r.intent.getIntent() + ": process is bad");
11075 bringDownServiceLocked(r, true);
11076 return false;
11077 }
11078 if (isolated) {
11079 r.isolatedProc = app;
11080 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011081 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 mPendingServices.add(r);
11085 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 return true;
11088 }
11089
11090 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 //r.dump(" ");
11093
11094 // Does it still need to run?
11095 if (!force && r.startRequested) {
11096 return;
11097 }
11098 if (r.connections.size() > 0) {
11099 if (!force) {
11100 // XXX should probably keep a count of the number of auto-create
11101 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011102 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011104 ArrayList<ConnectionRecord> cr = it.next();
11105 for (int i=0; i<cr.size(); i++) {
11106 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11107 return;
11108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 }
11110 }
11111 }
11112
11113 // Report to all of the connections that the service is no longer
11114 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011115 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011117 ArrayList<ConnectionRecord> c = it.next();
11118 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011119 ConnectionRecord cr = c.get(i);
11120 // There is still a connection to the service that is
11121 // being brought down. Mark it as dead.
11122 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011123 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011124 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011125 } catch (Exception e) {
11126 Slog.w(TAG, "Failure disconnecting service " + r.name +
11127 " to connection " + c.get(i).conn.asBinder() +
11128 " (in " + c.get(i).binding.client.processName + ")", e);
11129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 }
11131 }
11132 }
11133
11134 // Tell the service that it has been unbound.
11135 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11136 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11137 while (it.hasNext()) {
11138 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011139 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 + ": hasBound=" + ibr.hasBound);
11141 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11142 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011143 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011144 updateOomAdjLocked(r.app);
11145 ibr.hasBound = false;
11146 r.app.thread.scheduleUnbindService(r,
11147 ibr.intent.getIntent());
11148 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 + r.shortName, e);
11151 serviceDoneExecutingLocked(r, true);
11152 }
11153 }
11154 }
11155 }
11156
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011157 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011158 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011159 System.identityHashCode(r), r.shortName,
11160 (r.app != null) ? r.app.pid : -1);
11161
Amith Yamasani742a6712011-05-04 14:49:28 -070011162 mServiceMap.removeServiceByName(r.name, r.userId);
11163 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164 r.totalRestartCount = 0;
11165 unscheduleServiceRestartLocked(r);
11166
11167 // Also make sure it is not on the pending list.
11168 int N = mPendingServices.size();
11169 for (int i=0; i<N; i++) {
11170 if (mPendingServices.get(i) == r) {
11171 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011172 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 i--;
11174 N--;
11175 }
11176 }
11177
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011178 r.cancelNotification();
11179 r.isForeground = false;
11180 r.foregroundId = 0;
11181 r.foregroundNoti = null;
11182
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011183 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011184 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011185 r.pendingStarts.clear();
11186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 if (r.app != null) {
11188 synchronized (r.stats.getBatteryStats()) {
11189 r.stats.stopLaunchedLocked();
11190 }
11191 r.app.services.remove(r);
11192 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011194 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 mStoppingServices.add(r);
11196 updateOomAdjLocked(r.app);
11197 r.app.thread.scheduleStopService(r);
11198 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011199 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 + r.shortName, e);
11201 serviceDoneExecutingLocked(r, true);
11202 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011203 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011205 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011206 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011207 }
11208 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011209 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011210 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011212
11213 if (r.bindings.size() > 0) {
11214 r.bindings.clear();
11215 }
11216
11217 if (r.restarter instanceof ServiceRestarter) {
11218 ((ServiceRestarter)r.restarter).setService(null);
11219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011220 }
11221
11222 ComponentName startServiceLocked(IApplicationThread caller,
11223 Intent service, String resolvedType,
11224 int callingPid, int callingUid) {
11225 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011226 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 + " type=" + resolvedType + " args=" + service.getExtras());
11228
11229 if (caller != null) {
11230 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11231 if (callerApp == null) {
11232 throw new SecurityException(
11233 "Unable to find app for caller " + caller
11234 + " (pid=" + Binder.getCallingPid()
11235 + ") when starting service " + service);
11236 }
11237 }
11238
11239 ServiceLookupResult res =
11240 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011241 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011242 if (res == null) {
11243 return null;
11244 }
11245 if (res.record == null) {
11246 return new ComponentName("!", res.permission != null
11247 ? res.permission : "private to package");
11248 }
11249 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011250 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11251 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011253 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 }
11255 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011256 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011257 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011258 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 r.lastActivity = SystemClock.uptimeMillis();
11260 synchronized (r.stats.getBatteryStats()) {
11261 r.stats.startRunningLocked();
11262 }
11263 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11264 return new ComponentName("!", "Service process is bad");
11265 }
11266 return r.name;
11267 }
11268 }
11269
11270 public ComponentName startService(IApplicationThread caller, Intent service,
11271 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011272 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 // Refuse possible leaked file descriptors
11274 if (service != null && service.hasFileDescriptors() == true) {
11275 throw new IllegalArgumentException("File descriptors passed in Intent");
11276 }
11277
Amith Yamasani742a6712011-05-04 14:49:28 -070011278 if (DEBUG_SERVICE)
11279 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 synchronized(this) {
11281 final int callingPid = Binder.getCallingPid();
11282 final int callingUid = Binder.getCallingUid();
11283 final long origId = Binder.clearCallingIdentity();
11284 ComponentName res = startServiceLocked(caller, service,
11285 resolvedType, callingPid, callingUid);
11286 Binder.restoreCallingIdentity(origId);
11287 return res;
11288 }
11289 }
11290
11291 ComponentName startServiceInPackage(int uid,
11292 Intent service, String resolvedType) {
11293 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011294 if (DEBUG_SERVICE)
11295 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296 final long origId = Binder.clearCallingIdentity();
11297 ComponentName res = startServiceLocked(null, service,
11298 resolvedType, -1, uid);
11299 Binder.restoreCallingIdentity(origId);
11300 return res;
11301 }
11302 }
11303
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011304 private void stopServiceLocked(ServiceRecord service) {
11305 synchronized (service.stats.getBatteryStats()) {
11306 service.stats.stopRunningLocked();
11307 }
11308 service.startRequested = false;
11309 service.callStart = false;
11310 bringDownServiceLocked(service, false);
11311 }
11312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 public int stopService(IApplicationThread caller, Intent service,
11314 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011315 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 // Refuse possible leaked file descriptors
11317 if (service != null && service.hasFileDescriptors() == true) {
11318 throw new IllegalArgumentException("File descriptors passed in Intent");
11319 }
11320
11321 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011322 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 + " type=" + resolvedType);
11324
11325 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11326 if (caller != null && callerApp == null) {
11327 throw new SecurityException(
11328 "Unable to find app for caller " + caller
11329 + " (pid=" + Binder.getCallingPid()
11330 + ") when stopping service " + service);
11331 }
11332
11333 // If this service is active, make sure it is stopped.
11334 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11335 if (r != null) {
11336 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011337 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011338 try {
11339 stopServiceLocked(r.record);
11340 } finally {
11341 Binder.restoreCallingIdentity(origId);
11342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 return 1;
11344 }
11345 return -1;
11346 }
11347 }
11348
11349 return 0;
11350 }
11351
11352 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011353 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 // Refuse possible leaked file descriptors
11355 if (service != null && service.hasFileDescriptors() == true) {
11356 throw new IllegalArgumentException("File descriptors passed in Intent");
11357 }
11358
11359 IBinder ret = null;
11360
11361 synchronized(this) {
11362 ServiceLookupResult r = findServiceLocked(service, resolvedType);
11363
11364 if (r != null) {
11365 // r.record is null if findServiceLocked() failed the caller permission check
11366 if (r.record == null) {
11367 throw new SecurityException(
11368 "Permission Denial: Accessing service " + r.record.name
11369 + " from pid=" + Binder.getCallingPid()
11370 + ", uid=" + Binder.getCallingUid()
11371 + " requires " + r.permission);
11372 }
11373 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11374 if (ib != null) {
11375 ret = ib.binder;
11376 }
11377 }
11378 }
11379
11380 return ret;
11381 }
11382
11383 public boolean stopServiceToken(ComponentName className, IBinder token,
11384 int startId) {
11385 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011386 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 + " " + token + " startId=" + startId);
11388 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011389 if (r != null) {
11390 if (startId >= 0) {
11391 // Asked to only stop if done with all work. Note that
11392 // to avoid leaks, we will take this as dropping all
11393 // start items up to and including this one.
11394 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11395 if (si != null) {
11396 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011397 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11398 cur.removeUriPermissionsLocked();
11399 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011400 break;
11401 }
11402 }
11403 }
11404
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011405 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011406 return false;
11407 }
11408
11409 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011410 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011411 + " is last, but have " + r.deliveredStarts.size()
11412 + " remaining args");
11413 }
11414 }
11415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 synchronized (r.stats.getBatteryStats()) {
11417 r.stats.stopRunningLocked();
11418 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011419 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 }
11421 final long origId = Binder.clearCallingIdentity();
11422 bringDownServiceLocked(r, false);
11423 Binder.restoreCallingIdentity(origId);
11424 return true;
11425 }
11426 }
11427 return false;
11428 }
11429
11430 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011431 int id, Notification notification, boolean removeNotification) {
11432 final long origId = Binder.clearCallingIdentity();
11433 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 synchronized(this) {
11435 ServiceRecord r = findServiceLocked(className, token);
11436 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011437 if (id != 0) {
11438 if (notification == null) {
11439 throw new IllegalArgumentException("null notification");
11440 }
11441 if (r.foregroundId != id) {
11442 r.cancelNotification();
11443 r.foregroundId = id;
11444 }
11445 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11446 r.foregroundNoti = notification;
11447 r.isForeground = true;
11448 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 if (r.app != null) {
11450 updateServiceForegroundLocked(r.app, true);
11451 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011452 } else {
11453 if (r.isForeground) {
11454 r.isForeground = false;
11455 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011456 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011457 updateServiceForegroundLocked(r.app, true);
11458 }
11459 }
11460 if (removeNotification) {
11461 r.cancelNotification();
11462 r.foregroundId = 0;
11463 r.foregroundNoti = null;
11464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 }
11466 }
11467 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011468 } finally {
11469 Binder.restoreCallingIdentity(origId);
11470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 }
11472
11473 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11474 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011475 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 if (sr.isForeground) {
11477 anyForeground = true;
11478 break;
11479 }
11480 }
11481 if (anyForeground != proc.foregroundServices) {
11482 proc.foregroundServices = anyForeground;
11483 if (oomAdj) {
11484 updateOomAdjLocked();
11485 }
11486 }
11487 }
11488
11489 public int bindService(IApplicationThread caller, IBinder token,
11490 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011491 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011492 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011493 // Refuse possible leaked file descriptors
11494 if (service != null && service.hasFileDescriptors() == true) {
11495 throw new IllegalArgumentException("File descriptors passed in Intent");
11496 }
11497
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011498 checkValidCaller(Binder.getCallingUid(), userId);
11499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011500 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011501 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 + " type=" + resolvedType + " conn=" + connection.asBinder()
11503 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011504 if (DEBUG_MU)
11505 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11506 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11508 if (callerApp == null) {
11509 throw new SecurityException(
11510 "Unable to find app for caller " + caller
11511 + " (pid=" + Binder.getCallingPid()
11512 + ") when binding service " + service);
11513 }
11514
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011515 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011517 activity = mMainStack.isInStackLocked(token);
11518 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011519 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011520 return 0;
11521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 }
11523
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011524 int clientLabel = 0;
11525 PendingIntent clientIntent = null;
11526
11527 if (callerApp.info.uid == Process.SYSTEM_UID) {
11528 // Hacky kind of thing -- allow system stuff to tell us
11529 // what they are, so we can report this elsewhere for
11530 // others to know why certain services are running.
11531 try {
11532 clientIntent = (PendingIntent)service.getParcelableExtra(
11533 Intent.EXTRA_CLIENT_INTENT);
11534 } catch (RuntimeException e) {
11535 }
11536 if (clientIntent != null) {
11537 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11538 if (clientLabel != 0) {
11539 // There are no useful extras in the intent, trash them.
11540 // System code calling with this stuff just needs to know
11541 // this will happen.
11542 service = service.cloneFilter();
11543 }
11544 }
11545 }
11546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 ServiceLookupResult res =
11548 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011549 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 if (res == null) {
11551 return 0;
11552 }
11553 if (res.record == null) {
11554 return -1;
11555 }
11556 ServiceRecord s = res.record;
11557
11558 final long origId = Binder.clearCallingIdentity();
11559
11560 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011561 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011562 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 }
11564
11565 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11566 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011567 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011568
11569 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011570 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11571 if (clist == null) {
11572 clist = new ArrayList<ConnectionRecord>();
11573 s.connections.put(binder, clist);
11574 }
11575 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 b.connections.add(c);
11577 if (activity != null) {
11578 if (activity.connections == null) {
11579 activity.connections = new HashSet<ConnectionRecord>();
11580 }
11581 activity.connections.add(c);
11582 }
11583 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011584 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11585 b.client.hasAboveClient = true;
11586 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011587 clist = mServiceConnections.get(binder);
11588 if (clist == null) {
11589 clist = new ArrayList<ConnectionRecord>();
11590 mServiceConnections.put(binder, clist);
11591 }
11592 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011593
11594 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11595 s.lastActivity = SystemClock.uptimeMillis();
11596 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11597 return 0;
11598 }
11599 }
11600
11601 if (s.app != null) {
11602 // This could have made the service more important.
11603 updateOomAdjLocked(s.app);
11604 }
11605
Joe Onorato8a9b2202010-02-26 18:56:32 -080011606 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 + ": received=" + b.intent.received
11608 + " apps=" + b.intent.apps.size()
11609 + " doRebind=" + b.intent.doRebind);
11610
11611 if (s.app != null && b.intent.received) {
11612 // Service is already running, so we can immediately
11613 // publish the connection.
11614 try {
11615 c.conn.connected(s.name, b.intent.binder);
11616 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011617 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 + " to connection " + c.conn.asBinder()
11619 + " (in " + c.binding.client.processName + ")", e);
11620 }
11621
11622 // If this is the first app connected back to this binding,
11623 // and the service had previously asked to be told when
11624 // rebound, then do so.
11625 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11626 requestServiceBindingLocked(s, b.intent, true);
11627 }
11628 } else if (!b.intent.requested) {
11629 requestServiceBindingLocked(s, b.intent, false);
11630 }
11631
11632 Binder.restoreCallingIdentity(origId);
11633 }
11634
11635 return 1;
11636 }
11637
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011638 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011639 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011640 IBinder binder = c.conn.asBinder();
11641 AppBindRecord b = c.binding;
11642 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011643 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11644 if (clist != null) {
11645 clist.remove(c);
11646 if (clist.size() == 0) {
11647 s.connections.remove(binder);
11648 }
11649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 b.connections.remove(c);
11651 if (c.activity != null && c.activity != skipAct) {
11652 if (c.activity.connections != null) {
11653 c.activity.connections.remove(c);
11654 }
11655 }
11656 if (b.client != skipApp) {
11657 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011658 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11659 b.client.updateHasAboveClientLocked();
11660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011662 clist = mServiceConnections.get(binder);
11663 if (clist != null) {
11664 clist.remove(c);
11665 if (clist.size() == 0) {
11666 mServiceConnections.remove(binder);
11667 }
11668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669
11670 if (b.connections.size() == 0) {
11671 b.intent.apps.remove(b.client);
11672 }
11673
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011674 if (!c.serviceDead) {
11675 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11676 + ": shouldUnbind=" + b.intent.hasBound);
11677 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11678 && b.intent.hasBound) {
11679 try {
11680 bumpServiceExecutingLocked(s, "unbind");
11681 updateOomAdjLocked(s.app);
11682 b.intent.hasBound = false;
11683 // Assume the client doesn't want to know about a rebind;
11684 // we will deal with that later if it asks for one.
11685 b.intent.doRebind = false;
11686 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11687 } catch (Exception e) {
11688 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11689 serviceDoneExecutingLocked(s, true);
11690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011692
11693 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11694 bringDownServiceLocked(s, false);
11695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 }
11697 }
11698
11699 public boolean unbindService(IServiceConnection connection) {
11700 synchronized (this) {
11701 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011702 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011703 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11704 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011705 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 + connection.asBinder());
11707 return false;
11708 }
11709
11710 final long origId = Binder.clearCallingIdentity();
11711
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011712 while (clist.size() > 0) {
11713 ConnectionRecord r = clist.get(0);
11714 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011716 if (r.binding.service.app != null) {
11717 // This could have made the service less important.
11718 updateOomAdjLocked(r.binding.service.app);
11719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 }
11721
11722 Binder.restoreCallingIdentity(origId);
11723 }
11724
11725 return true;
11726 }
11727
11728 public void publishService(IBinder token, Intent intent, IBinder service) {
11729 // Refuse possible leaked file descriptors
11730 if (intent != null && intent.hasFileDescriptors() == true) {
11731 throw new IllegalArgumentException("File descriptors passed in Intent");
11732 }
11733
11734 synchronized(this) {
11735 if (!(token instanceof ServiceRecord)) {
11736 throw new IllegalArgumentException("Invalid service token");
11737 }
11738 ServiceRecord r = (ServiceRecord)token;
11739
11740 final long origId = Binder.clearCallingIdentity();
11741
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011742 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011743 + " " + intent + ": " + service);
11744 if (r != null) {
11745 Intent.FilterComparison filter
11746 = new Intent.FilterComparison(intent);
11747 IntentBindRecord b = r.bindings.get(filter);
11748 if (b != null && !b.received) {
11749 b.binder = service;
11750 b.requested = true;
11751 b.received = true;
11752 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011753 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 = r.connections.values().iterator();
11755 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011756 ArrayList<ConnectionRecord> clist = it.next();
11757 for (int i=0; i<clist.size(); i++) {
11758 ConnectionRecord c = clist.get(i);
11759 if (!filter.equals(c.binding.intent.intent)) {
11760 if (DEBUG_SERVICE) Slog.v(
11761 TAG, "Not publishing to: " + c);
11762 if (DEBUG_SERVICE) Slog.v(
11763 TAG, "Bound intent: " + c.binding.intent.intent);
11764 if (DEBUG_SERVICE) Slog.v(
11765 TAG, "Published intent: " + intent);
11766 continue;
11767 }
11768 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11769 try {
11770 c.conn.connected(r.name, service);
11771 } catch (Exception e) {
11772 Slog.w(TAG, "Failure sending service " + r.name +
11773 " to connection " + c.conn.asBinder() +
11774 " (in " + c.binding.client.processName + ")", e);
11775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 }
11777 }
11778 }
11779 }
11780
11781 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11782
11783 Binder.restoreCallingIdentity(origId);
11784 }
11785 }
11786 }
11787
11788 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11789 // Refuse possible leaked file descriptors
11790 if (intent != null && intent.hasFileDescriptors() == true) {
11791 throw new IllegalArgumentException("File descriptors passed in Intent");
11792 }
11793
11794 synchronized(this) {
11795 if (!(token instanceof ServiceRecord)) {
11796 throw new IllegalArgumentException("Invalid service token");
11797 }
11798 ServiceRecord r = (ServiceRecord)token;
11799
11800 final long origId = Binder.clearCallingIdentity();
11801
11802 if (r != null) {
11803 Intent.FilterComparison filter
11804 = new Intent.FilterComparison(intent);
11805 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011806 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 + " at " + b + ": apps="
11808 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011809
11810 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011812 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011813 // Applications have already bound since the last
11814 // unbind, so just rebind right here.
11815 requestServiceBindingLocked(r, b, true);
11816 } else {
11817 // Note to tell the service the next time there is
11818 // a new client.
11819 b.doRebind = true;
11820 }
11821 }
11822
Per Edelberg78f9fff2010-08-30 20:01:35 +020011823 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824
11825 Binder.restoreCallingIdentity(origId);
11826 }
11827 }
11828 }
11829
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011830 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 synchronized(this) {
11832 if (!(token instanceof ServiceRecord)) {
11833 throw new IllegalArgumentException("Invalid service token");
11834 }
11835 ServiceRecord r = (ServiceRecord)token;
11836 boolean inStopping = mStoppingServices.contains(token);
11837 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011839 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840 + " with incorrect token: given " + token
11841 + ", expected " + r);
11842 return;
11843 }
11844
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011845 if (type == 1) {
11846 // This is a call from a service start... take care of
11847 // book-keeping.
11848 r.callStart = true;
11849 switch (res) {
11850 case Service.START_STICKY_COMPATIBILITY:
11851 case Service.START_STICKY: {
11852 // We are done with the associated start arguments.
11853 r.findDeliveredStart(startId, true);
11854 // Don't stop if killed.
11855 r.stopIfKilled = false;
11856 break;
11857 }
11858 case Service.START_NOT_STICKY: {
11859 // We are done with the associated start arguments.
11860 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011861 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011862 // There is no more work, and this service
11863 // doesn't want to hang around if killed.
11864 r.stopIfKilled = true;
11865 }
11866 break;
11867 }
11868 case Service.START_REDELIVER_INTENT: {
11869 // We'll keep this item until they explicitly
11870 // call stop for it, but keep track of the fact
11871 // that it was delivered.
11872 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11873 if (si != null) {
11874 si.deliveryCount = 0;
11875 si.doneExecutingCount++;
11876 // Don't stop if killed.
11877 r.stopIfKilled = true;
11878 }
11879 break;
11880 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011881 case Service.START_TASK_REMOVED_COMPLETE: {
11882 // Special processing for onTaskRemoved(). Don't
11883 // impact normal onStartCommand() processing.
11884 r.findDeliveredStart(startId, true);
11885 break;
11886 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011887 default:
11888 throw new IllegalArgumentException(
11889 "Unknown service start result: " + res);
11890 }
11891 if (res == Service.START_STICKY_COMPATIBILITY) {
11892 r.callStart = false;
11893 }
11894 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011895 if (DEBUG_MU)
11896 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
11897 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898 final long origId = Binder.clearCallingIdentity();
11899 serviceDoneExecutingLocked(r, inStopping);
11900 Binder.restoreCallingIdentity(origId);
11901 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011902 Slog.w(TAG, "Done executing unknown service from pid "
11903 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 }
11905 }
11906 }
11907
11908 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011909 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
11910 + ": nesting=" + r.executeNesting
11911 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011912 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 r.executeNesting--;
11914 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011915 if (DEBUG_SERVICE) Slog.v(TAG,
11916 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 r.app.executingServices.remove(r);
11918 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011919 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
11920 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011921 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
11922 }
11923 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011924 if (DEBUG_SERVICE) Slog.v(TAG,
11925 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011926 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020011927 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 }
11929 updateOomAdjLocked(r.app);
11930 }
11931 }
11932
11933 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011934 String anrMessage = null;
11935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011936 synchronized(this) {
11937 if (proc.executingServices.size() == 0 || proc.thread == null) {
11938 return;
11939 }
11940 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
11941 Iterator<ServiceRecord> it = proc.executingServices.iterator();
11942 ServiceRecord timeout = null;
11943 long nextTime = 0;
11944 while (it.hasNext()) {
11945 ServiceRecord sr = it.next();
11946 if (sr.executingStart < maxTime) {
11947 timeout = sr;
11948 break;
11949 }
11950 if (sr.executingStart > nextTime) {
11951 nextTime = sr.executingStart;
11952 }
11953 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011954 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011955 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011956 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 } else {
11958 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11959 msg.obj = proc;
11960 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
11961 }
11962 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011963
11964 if (anrMessage != null) {
11965 appNotResponding(proc, null, null, anrMessage);
11966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 }
11968
11969 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011970 // BACKUP AND RESTORE
11971 // =========================================================
11972
11973 // Cause the target app to be launched if necessary and its backup agent
11974 // instantiated. The backup agent will invoke backupAgentCreated() on the
11975 // activity manager to announce its creation.
11976 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011977 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011978 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
11979
11980 synchronized(this) {
11981 // !!! TODO: currently no check here that we're already bound
11982 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11983 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11984 synchronized (stats) {
11985 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11986 }
11987
Dianne Hackborne7f97212011-02-24 14:40:20 -080011988 // Backup agent is now in use, its package can't be stopped.
11989 try {
11990 AppGlobals.getPackageManager().setPackageStoppedState(
11991 app.packageName, false);
11992 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011993 } catch (IllegalArgumentException e) {
11994 Slog.w(TAG, "Failed trying to unstop package "
11995 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011996 }
11997
Christopher Tate181fafa2009-05-14 11:12:14 -070011998 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011999 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12000 ? new ComponentName(app.packageName, app.backupAgentName)
12001 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012002 // startProcessLocked() returns existing proc's record if it's already running
12003 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012004 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012005 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012006 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012007 return false;
12008 }
12009
12010 r.app = proc;
12011 mBackupTarget = r;
12012 mBackupAppName = app.packageName;
12013
Christopher Tate6fa95972009-06-05 18:43:55 -070012014 // Try not to kill the process during backup
12015 updateOomAdjLocked(proc);
12016
Christopher Tate181fafa2009-05-14 11:12:14 -070012017 // If the process is already attached, schedule the creation of the backup agent now.
12018 // If it is not yet live, this will be done when it attaches to the framework.
12019 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012020 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012021 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012022 proc.thread.scheduleCreateBackupAgent(app,
12023 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012024 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012025 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012026 }
12027 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012028 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012029 }
12030 // Invariants: at this point, the target app process exists and the application
12031 // is either already running or in the process of coming up. mBackupTarget and
12032 // mBackupAppName describe the app, so that when it binds back to the AM we
12033 // know that it's scheduled for a backup-agent operation.
12034 }
12035
12036 return true;
12037 }
12038
12039 // A backup agent has just come up
12040 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012041 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012042 + " = " + agent);
12043
12044 synchronized(this) {
12045 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012046 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012047 return;
12048 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012049 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012050
Dianne Hackborn06740692010-09-22 22:46:21 -070012051 long oldIdent = Binder.clearCallingIdentity();
12052 try {
12053 IBackupManager bm = IBackupManager.Stub.asInterface(
12054 ServiceManager.getService(Context.BACKUP_SERVICE));
12055 bm.agentConnected(agentPackageName, agent);
12056 } catch (RemoteException e) {
12057 // can't happen; the backup manager service is local
12058 } catch (Exception e) {
12059 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12060 e.printStackTrace();
12061 } finally {
12062 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012063 }
12064 }
12065
12066 // done with this agent
12067 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012068 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012069 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012070 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012071 return;
12072 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012073
12074 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012075 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012076 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012077 return;
12078 }
12079
Christopher Tate181fafa2009-05-14 11:12:14 -070012080 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012081 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012082 return;
12083 }
12084
Christopher Tate6fa95972009-06-05 18:43:55 -070012085 ProcessRecord proc = mBackupTarget.app;
12086 mBackupTarget = null;
12087 mBackupAppName = null;
12088
12089 // Not backing this app up any more; reset its OOM adjustment
12090 updateOomAdjLocked(proc);
12091
Christopher Tatec7b31e32009-06-10 15:49:30 -070012092 // If the app crashed during backup, 'thread' will be null here
12093 if (proc.thread != null) {
12094 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012095 proc.thread.scheduleDestroyBackupAgent(appInfo,
12096 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012097 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012098 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012099 e.printStackTrace();
12100 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012101 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012102 }
12103 }
12104 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 // BROADCASTS
12106 // =========================================================
12107
Josh Bartel7f208742010-02-25 11:01:44 -060012108 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109 List cur) {
12110 final ContentResolver resolver = mContext.getContentResolver();
12111 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12112 if (list == null) {
12113 return cur;
12114 }
12115 int N = list.size();
12116 for (int i=0; i<N; i++) {
12117 Intent intent = list.get(i);
12118 if (filter.match(resolver, intent, true, TAG) >= 0) {
12119 if (cur == null) {
12120 cur = new ArrayList<Intent>();
12121 }
12122 cur.add(intent);
12123 }
12124 }
12125 return cur;
12126 }
12127
Christopher Tatef46723b2012-01-26 14:19:24 -080012128 boolean isPendingBroadcastProcessLocked(int pid) {
12129 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12130 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132
Christopher Tatef46723b2012-01-26 14:19:24 -080012133 void skipPendingBroadcastLocked(int pid) {
12134 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12135 for (BroadcastQueue queue : mBroadcastQueues) {
12136 queue.skipPendingBroadcastLocked(pid);
12137 }
12138 }
12139
12140 // The app just attached; send any pending broadcasts that it should receive
12141 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12142 boolean didSomething = false;
12143 for (BroadcastQueue queue : mBroadcastQueues) {
12144 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012145 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012146 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012147 }
12148
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012149 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012151 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012152 synchronized(this) {
12153 ProcessRecord callerApp = null;
12154 if (caller != null) {
12155 callerApp = getRecordForAppLocked(caller);
12156 if (callerApp == null) {
12157 throw new SecurityException(
12158 "Unable to find app for caller " + caller
12159 + " (pid=" + Binder.getCallingPid()
12160 + ") when registering receiver " + receiver);
12161 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012162 if (callerApp.info.uid != Process.SYSTEM_UID &&
12163 !callerApp.pkgList.contains(callerPackage)) {
12164 throw new SecurityException("Given caller package " + callerPackage
12165 + " is not running in process " + callerApp);
12166 }
12167 } else {
12168 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 }
12170
12171 List allSticky = null;
12172
12173 // Look for any matching sticky broadcasts...
12174 Iterator actions = filter.actionsIterator();
12175 if (actions != null) {
12176 while (actions.hasNext()) {
12177 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012178 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012179 }
12180 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012181 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012182 }
12183
12184 // The first sticky in the list is returned directly back to
12185 // the client.
12186 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12187
Joe Onorato8a9b2202010-02-26 18:56:32 -080012188 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189 + ": " + sticky);
12190
12191 if (receiver == null) {
12192 return sticky;
12193 }
12194
12195 ReceiverList rl
12196 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12197 if (rl == null) {
12198 rl = new ReceiverList(this, callerApp,
12199 Binder.getCallingPid(),
12200 Binder.getCallingUid(), receiver);
12201 if (rl.app != null) {
12202 rl.app.receivers.add(rl);
12203 } else {
12204 try {
12205 receiver.asBinder().linkToDeath(rl, 0);
12206 } catch (RemoteException e) {
12207 return sticky;
12208 }
12209 rl.linkedToDeath = true;
12210 }
12211 mRegisteredReceivers.put(receiver.asBinder(), rl);
12212 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012213 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012214 rl.add(bf);
12215 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012216 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 }
12218 mReceiverResolver.addFilter(bf);
12219
12220 // Enqueue broadcasts for all existing stickies that match
12221 // this filter.
12222 if (allSticky != null) {
12223 ArrayList receivers = new ArrayList();
12224 receivers.add(bf);
12225
12226 int N = allSticky.size();
12227 for (int i=0; i<N; i++) {
12228 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012229 BroadcastQueue queue = broadcastQueueForIntent(intent);
12230 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012231 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012232 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012233 queue.enqueueParallelBroadcastLocked(r);
12234 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 }
12236 }
12237
12238 return sticky;
12239 }
12240 }
12241
12242 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012243 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244
Christopher Tatef46723b2012-01-26 14:19:24 -080012245 final long origId = Binder.clearCallingIdentity();
12246 try {
12247 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248
Christopher Tatef46723b2012-01-26 14:19:24 -080012249 synchronized(this) {
12250 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012252 if (rl != null) {
12253 if (rl.curBroadcast != null) {
12254 BroadcastRecord r = rl.curBroadcast;
12255 final boolean doNext = finishReceiverLocked(
12256 receiver.asBinder(), r.resultCode, r.resultData,
12257 r.resultExtras, r.resultAbort, true);
12258 if (doNext) {
12259 doTrim = true;
12260 r.queue.processNextBroadcast(false);
12261 }
12262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012263
Christopher Tatef46723b2012-01-26 14:19:24 -080012264 if (rl.app != null) {
12265 rl.app.receivers.remove(rl);
12266 }
12267 removeReceiverLocked(rl);
12268 if (rl.linkedToDeath) {
12269 rl.linkedToDeath = false;
12270 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012272 }
12273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012274
Christopher Tatef46723b2012-01-26 14:19:24 -080012275 // If we actually concluded any broadcasts, we might now be able
12276 // to trim the recipients' apps from our working set
12277 if (doTrim) {
12278 trimApplications();
12279 return;
12280 }
12281
12282 } finally {
12283 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 }
12286
12287 void removeReceiverLocked(ReceiverList rl) {
12288 mRegisteredReceivers.remove(rl.receiver.asBinder());
12289 int N = rl.size();
12290 for (int i=0; i<N; i++) {
12291 mReceiverResolver.removeFilter(rl.get(i));
12292 }
12293 }
12294
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012295 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12296 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12297 ProcessRecord r = mLruProcesses.get(i);
12298 if (r.thread != null) {
12299 try {
12300 r.thread.dispatchPackageBroadcast(cmd, packages);
12301 } catch (RemoteException ex) {
12302 }
12303 }
12304 }
12305 }
12306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012307 private final int broadcastIntentLocked(ProcessRecord callerApp,
12308 String callerPackage, Intent intent, String resolvedType,
12309 IIntentReceiver resultTo, int resultCode, String resultData,
12310 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012311 boolean ordered, boolean sticky, int callingPid, int callingUid,
12312 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 intent = new Intent(intent);
12314
Dianne Hackborne7f97212011-02-24 14:40:20 -080012315 // By default broadcasts do not go to stopped apps.
12316 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12317
Joe Onorato8a9b2202010-02-26 18:56:32 -080012318 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012319 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12320 + " ordered=" + ordered);
12321 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012322 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 }
12324
12325 // Handle special intents: if this broadcast is from the package
12326 // manager about a package being removed, we need to remove all of
12327 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012328 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012329 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012330 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12331 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012332 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012333 || uidRemoved) {
12334 if (checkComponentPermission(
12335 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012336 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337 == PackageManager.PERMISSION_GRANTED) {
12338 if (uidRemoved) {
12339 final Bundle intentExtras = intent.getExtras();
12340 final int uid = intentExtras != null
12341 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12342 if (uid >= 0) {
12343 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12344 synchronized (bs) {
12345 bs.removeUidStatsLocked(uid);
12346 }
12347 }
12348 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012349 // If resources are unvailble just force stop all
12350 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012351 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012352 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12353 if (list != null && (list.length > 0)) {
12354 for (String pkg : list) {
Christopher Tate3dacd842011-08-19 14:56:15 -070012355 forceStopPackageLocked(pkg, -1, false, true, true, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012356 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012357 sendPackageBroadcastLocked(
12358 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012359 }
12360 } else {
12361 Uri data = intent.getData();
12362 String ssp;
12363 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12364 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12365 forceStopPackageLocked(ssp,
Christopher Tate3dacd842011-08-19 14:56:15 -070012366 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true, false);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012367 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012368 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012369 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12370 new String[] {ssp});
12371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012372 }
12373 }
12374 }
12375 } else {
12376 String msg = "Permission Denial: " + intent.getAction()
12377 + " broadcast from " + callerPackage + " (pid=" + callingPid
12378 + ", uid=" + callingUid + ")"
12379 + " requires "
12380 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012381 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 throw new SecurityException(msg);
12383 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012384
12385 // Special case for adding a package: by default turn on compatibility
12386 // mode.
12387 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012388 Uri data = intent.getData();
12389 String ssp;
12390 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12391 mCompatModePackages.handlePackageAddedLocked(ssp,
12392 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 }
12395
12396 /*
12397 * If this is the time zone changed action, queue up a message that will reset the timezone
12398 * of all currently running processes. This message will get queued up before the broadcast
12399 * happens.
12400 */
12401 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12402 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12403 }
12404
Robert Greenwalt03595d02010-11-02 14:08:23 -070012405 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12406 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12407 }
12408
Robert Greenwalt434203a2010-10-11 16:00:27 -070012409 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12410 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12411 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12412 }
12413
Dianne Hackborn854060af2009-07-09 18:14:31 -070012414 /*
12415 * Prevent non-system code (defined here to be non-persistent
12416 * processes) from sending protected broadcasts.
12417 */
12418 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12419 || callingUid == Process.SHELL_UID || callingUid == 0) {
12420 // Always okay.
12421 } else if (callerApp == null || !callerApp.persistent) {
12422 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012423 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012424 intent.getAction())) {
12425 String msg = "Permission Denial: not allowed to send broadcast "
12426 + intent.getAction() + " from pid="
12427 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012428 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012429 throw new SecurityException(msg);
12430 }
12431 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 Slog.w(TAG, "Remote exception", e);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012433 return BROADCAST_SUCCESS;
12434 }
12435 }
12436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 // Add to the sticky list if requested.
12438 if (sticky) {
12439 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12440 callingPid, callingUid)
12441 != PackageManager.PERMISSION_GRANTED) {
12442 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12443 + callingPid + ", uid=" + callingUid
12444 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012445 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 throw new SecurityException(msg);
12447 }
12448 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012449 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450 + " and enforce permission " + requiredPermission);
12451 return BROADCAST_STICKY_CANT_HAVE_PERMISSION;
12452 }
12453 if (intent.getComponent() != null) {
12454 throw new SecurityException(
12455 "Sticky broadcasts can't target a specific component");
12456 }
12457 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12458 if (list == null) {
12459 list = new ArrayList<Intent>();
12460 mStickyBroadcasts.put(intent.getAction(), list);
12461 }
12462 int N = list.size();
12463 int i;
12464 for (i=0; i<N; i++) {
12465 if (intent.filterEquals(list.get(i))) {
12466 // This sticky already exists, replace it.
12467 list.set(i, new Intent(intent));
12468 break;
12469 }
12470 }
12471 if (i >= N) {
12472 list.add(new Intent(intent));
12473 }
12474 }
12475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012476 // Figure out who all will receive this broadcast.
12477 List receivers = null;
12478 List<BroadcastFilter> registeredReceivers = null;
12479 try {
12480 if (intent.getComponent() != null) {
12481 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012482 ActivityInfo ai = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -070012483 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012484 if (ai != null) {
12485 receivers = new ArrayList();
12486 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012487 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 receivers.add(ri);
12489 }
12490 } else {
Amith Yamasani742a6712011-05-04 14:49:28 -070012491 // TODO: Apply userId
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 // Need to resolve the intent to interested receivers...
12493 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12494 == 0) {
12495 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012496 AppGlobals.getPackageManager().queryIntentReceivers(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012497 intent, resolvedType, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012498 }
Mihai Preda074edef2009-05-18 17:13:31 +020012499 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501 } catch (RemoteException ex) {
12502 // pm is in same process, this will never happen.
12503 }
12504
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012505 final boolean replacePending =
12506 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12507
Joe Onorato8a9b2202010-02-26 18:56:32 -080012508 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012509 + " replacePending=" + replacePending);
12510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012511 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12512 if (!ordered && NR > 0) {
12513 // If we are not serializing this broadcast, then send the
12514 // registered receivers separately so they don't wait for the
12515 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012516 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12517 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 callerPackage, callingPid, callingUid, requiredPermission,
12519 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012520 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012521 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012522 TAG, "Enqueueing parallel broadcast " + r);
12523 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012524 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012525 queue.enqueueParallelBroadcastLocked(r);
12526 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012528 registeredReceivers = null;
12529 NR = 0;
12530 }
12531
12532 // Merge into one list.
12533 int ir = 0;
12534 if (receivers != null) {
12535 // A special case for PACKAGE_ADDED: do not allow the package
12536 // being added to see this broadcast. This prevents them from
12537 // using this as a back door to get run as soon as they are
12538 // installed. Maybe in the future we want to have a special install
12539 // broadcast or such for apps, but we'd like to deliberately make
12540 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012541 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012542 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12543 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12544 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012545 Uri data = intent.getData();
12546 if (data != null) {
12547 String pkgName = data.getSchemeSpecificPart();
12548 if (pkgName != null) {
12549 skipPackages = new String[] { pkgName };
12550 }
12551 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012552 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012553 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012554 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012555 if (skipPackages != null && (skipPackages.length > 0)) {
12556 for (String skipPackage : skipPackages) {
12557 if (skipPackage != null) {
12558 int NT = receivers.size();
12559 for (int it=0; it<NT; it++) {
12560 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12561 if (curt.activityInfo.packageName.equals(skipPackage)) {
12562 receivers.remove(it);
12563 it--;
12564 NT--;
12565 }
12566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 }
12568 }
12569 }
12570
12571 int NT = receivers != null ? receivers.size() : 0;
12572 int it = 0;
12573 ResolveInfo curt = null;
12574 BroadcastFilter curr = null;
12575 while (it < NT && ir < NR) {
12576 if (curt == null) {
12577 curt = (ResolveInfo)receivers.get(it);
12578 }
12579 if (curr == null) {
12580 curr = registeredReceivers.get(ir);
12581 }
12582 if (curr.getPriority() >= curt.priority) {
12583 // Insert this broadcast record into the final list.
12584 receivers.add(it, curr);
12585 ir++;
12586 curr = null;
12587 it++;
12588 NT++;
12589 } else {
12590 // Skip to the next ResolveInfo in the final list.
12591 it++;
12592 curt = null;
12593 }
12594 }
12595 }
12596 while (ir < NR) {
12597 if (receivers == null) {
12598 receivers = new ArrayList();
12599 }
12600 receivers.add(registeredReceivers.get(ir));
12601 ir++;
12602 }
12603
12604 if ((receivers != null && receivers.size() > 0)
12605 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012606 BroadcastQueue queue = broadcastQueueForIntent(intent);
12607 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012609 receivers, resultTo, resultCode, resultData, map, ordered,
12610 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012611 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012612 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012613 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012614 if (DEBUG_BROADCAST) {
12615 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012616 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012618 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012619 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012620 queue.enqueueOrderedBroadcastLocked(r);
12621 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012623 }
12624
12625 return BROADCAST_SUCCESS;
12626 }
12627
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012628 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 // Refuse possible leaked file descriptors
12630 if (intent != null && intent.hasFileDescriptors() == true) {
12631 throw new IllegalArgumentException("File descriptors passed in Intent");
12632 }
12633
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012634 int flags = intent.getFlags();
12635
12636 if (!mProcessesReady) {
12637 // if the caller really truly claims to know what they're doing, go
12638 // ahead and allow the broadcast without launching any receivers
12639 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12640 intent = new Intent(intent);
12641 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12642 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12643 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12644 + " before boot completion");
12645 throw new IllegalStateException("Cannot broadcast before boot completed");
12646 }
12647 }
12648
12649 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12650 throw new IllegalArgumentException(
12651 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12652 }
12653
12654 return intent;
12655 }
12656
12657 public final int broadcastIntent(IApplicationThread caller,
12658 Intent intent, String resolvedType, IIntentReceiver resultTo,
12659 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012660 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012661 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012662 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012663 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12666 final int callingPid = Binder.getCallingPid();
12667 final int callingUid = Binder.getCallingUid();
12668 final long origId = Binder.clearCallingIdentity();
12669 int res = broadcastIntentLocked(callerApp,
12670 callerApp != null ? callerApp.info.packageName : null,
12671 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012672 resultCode, resultData, map, requiredPermission, serialized, sticky,
12673 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012674 Binder.restoreCallingIdentity(origId);
12675 return res;
12676 }
12677 }
12678
12679 int broadcastIntentInPackage(String packageName, int uid,
12680 Intent intent, String resolvedType, IIntentReceiver resultTo,
12681 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012682 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012684 intent = verifyBroadcastLocked(intent);
12685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012686 final long origId = Binder.clearCallingIdentity();
12687 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12688 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012689 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012690 Binder.restoreCallingIdentity(origId);
12691 return res;
12692 }
12693 }
12694
Amith Yamasani742a6712011-05-04 14:49:28 -070012695 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12696 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012697 // Refuse possible leaked file descriptors
12698 if (intent != null && intent.hasFileDescriptors() == true) {
12699 throw new IllegalArgumentException("File descriptors passed in Intent");
12700 }
12701
12702 synchronized(this) {
12703 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12704 != PackageManager.PERMISSION_GRANTED) {
12705 String msg = "Permission Denial: unbroadcastIntent() from pid="
12706 + Binder.getCallingPid()
12707 + ", uid=" + Binder.getCallingUid()
12708 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012709 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012710 throw new SecurityException(msg);
12711 }
12712 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12713 if (list != null) {
12714 int N = list.size();
12715 int i;
12716 for (i=0; i<N; i++) {
12717 if (intent.filterEquals(list.get(i))) {
12718 list.remove(i);
12719 break;
12720 }
12721 }
12722 }
12723 }
12724 }
12725
12726 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12727 String resultData, Bundle resultExtras, boolean resultAbort,
12728 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012729 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12730 if (r == null) {
12731 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 return false;
12733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734
Christopher Tatef46723b2012-01-26 14:19:24 -080012735 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12736 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012737 }
12738
12739 public void finishReceiver(IBinder who, int resultCode, String resultData,
12740 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012741 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012742
12743 // Refuse possible leaked file descriptors
12744 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12745 throw new IllegalArgumentException("File descriptors passed in Bundle");
12746 }
12747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012748 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012749 try {
12750 boolean doNext = false;
12751 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752
Christopher Tatef46723b2012-01-26 14:19:24 -080012753 synchronized(this) {
12754 r = broadcastRecordForReceiverLocked(who);
12755 if (r != null) {
12756 doNext = r.queue.finishReceiverLocked(r, resultCode,
12757 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012759 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012760
Christopher Tatef46723b2012-01-26 14:19:24 -080012761 if (doNext) {
12762 r.queue.processNextBroadcast(false);
12763 }
12764 trimApplications();
12765 } finally {
12766 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012770 // =========================================================
12771 // INSTRUMENTATION
12772 // =========================================================
12773
12774 public boolean startInstrumentation(ComponentName className,
12775 String profileFile, int flags, Bundle arguments,
12776 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012777 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 // Refuse possible leaked file descriptors
12779 if (arguments != null && arguments.hasFileDescriptors()) {
12780 throw new IllegalArgumentException("File descriptors passed in Bundle");
12781 }
12782
12783 synchronized(this) {
12784 InstrumentationInfo ii = null;
12785 ApplicationInfo ai = null;
12786 try {
12787 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012788 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 ai = mContext.getPackageManager().getApplicationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012790 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012791 } catch (PackageManager.NameNotFoundException e) {
12792 }
12793 if (ii == null) {
12794 reportStartInstrumentationFailure(watcher, className,
12795 "Unable to find instrumentation info for: " + className);
12796 return false;
12797 }
12798 if (ai == null) {
12799 reportStartInstrumentationFailure(watcher, className,
12800 "Unable to find instrumentation target package: " + ii.targetPackage);
12801 return false;
12802 }
12803
12804 int match = mContext.getPackageManager().checkSignatures(
12805 ii.targetPackage, ii.packageName);
12806 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12807 String msg = "Permission Denial: starting instrumentation "
12808 + className + " from pid="
12809 + Binder.getCallingPid()
12810 + ", uid=" + Binder.getCallingPid()
12811 + " not allowed because package " + ii.packageName
12812 + " does not have a signature matching the target "
12813 + ii.targetPackage;
12814 reportStartInstrumentationFailure(watcher, className, msg);
12815 throw new SecurityException(msg);
12816 }
12817
12818 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012819 // Instrumentation can kill and relaunch even persistent processes
12820 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012821 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012822 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012823 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 app.instrumentationProfileFile = profileFile;
12825 app.instrumentationArguments = arguments;
12826 app.instrumentationWatcher = watcher;
12827 app.instrumentationResultClass = className;
12828 Binder.restoreCallingIdentity(origId);
12829 }
12830
12831 return true;
12832 }
12833
12834 /**
12835 * Report errors that occur while attempting to start Instrumentation. Always writes the
12836 * error to the logs, but if somebody is watching, send the report there too. This enables
12837 * the "am" command to report errors with more information.
12838 *
12839 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12840 * @param cn The component name of the instrumentation.
12841 * @param report The error report.
12842 */
12843 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12844 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012845 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 try {
12847 if (watcher != null) {
12848 Bundle results = new Bundle();
12849 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12850 results.putString("Error", report);
12851 watcher.instrumentationStatus(cn, -1, results);
12852 }
12853 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012854 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 }
12856 }
12857
12858 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12859 if (app.instrumentationWatcher != null) {
12860 try {
12861 // NOTE: IInstrumentationWatcher *must* be oneway here
12862 app.instrumentationWatcher.instrumentationFinished(
12863 app.instrumentationClass,
12864 resultCode,
12865 results);
12866 } catch (RemoteException e) {
12867 }
12868 }
12869 app.instrumentationWatcher = null;
12870 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012871 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 app.instrumentationProfileFile = null;
12873 app.instrumentationArguments = null;
12874
Christopher Tate3dacd842011-08-19 14:56:15 -070012875 forceStopPackageLocked(app.processName, -1, false, false, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 }
12877
12878 public void finishInstrumentation(IApplicationThread target,
12879 int resultCode, Bundle results) {
12880 // Refuse possible leaked file descriptors
12881 if (results != null && results.hasFileDescriptors()) {
12882 throw new IllegalArgumentException("File descriptors passed in Intent");
12883 }
12884
12885 synchronized(this) {
12886 ProcessRecord app = getRecordForAppLocked(target);
12887 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012888 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012889 return;
12890 }
12891 final long origId = Binder.clearCallingIdentity();
12892 finishInstrumentationLocked(app, resultCode, results);
12893 Binder.restoreCallingIdentity(origId);
12894 }
12895 }
12896
12897 // =========================================================
12898 // CONFIGURATION
12899 // =========================================================
12900
12901 public ConfigurationInfo getDeviceConfigurationInfo() {
12902 ConfigurationInfo config = new ConfigurationInfo();
12903 synchronized (this) {
12904 config.reqTouchScreen = mConfiguration.touchscreen;
12905 config.reqKeyboardType = mConfiguration.keyboard;
12906 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012907 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12908 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12910 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012911 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12912 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12914 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012915 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012916 }
12917 return config;
12918 }
12919
12920 public Configuration getConfiguration() {
12921 Configuration ci;
12922 synchronized(this) {
12923 ci = new Configuration(mConfiguration);
12924 }
12925 return ci;
12926 }
12927
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012928 public void updatePersistentConfiguration(Configuration values) {
12929 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12930 "updateConfiguration()");
12931 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12932 "updateConfiguration()");
12933 if (values == null) {
12934 throw new NullPointerException("Configuration must not be null");
12935 }
12936
12937 synchronized(this) {
12938 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012939 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012940 Binder.restoreCallingIdentity(origId);
12941 }
12942 }
12943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944 public void updateConfiguration(Configuration values) {
12945 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12946 "updateConfiguration()");
12947
12948 synchronized(this) {
12949 if (values == null && mWindowManager != null) {
12950 // sentinel: fetch the current configuration from the window manager
12951 values = mWindowManager.computeNewConfiguration();
12952 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012953
12954 if (mWindowManager != null) {
12955 mProcessList.applyDisplaySize(mWindowManager);
12956 }
12957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012958 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012959 if (values != null) {
12960 Settings.System.clearConfiguration(values);
12961 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012962 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012963 Binder.restoreCallingIdentity(origId);
12964 }
12965 }
12966
12967 /**
12968 * Do either or both things: (1) change the current configuration, and (2)
12969 * make sure the given activity is running with the (now) current
12970 * configuration. Returns true if the activity has been left running, or
12971 * false if <var>starting</var> is being destroyed to match the new
12972 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012973 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012975 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012976 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012977 // do nothing if we are headless
12978 if (mHeadless) return true;
12979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 int changes = 0;
12981
12982 boolean kept = true;
12983
12984 if (values != null) {
12985 Configuration newConfig = new Configuration(mConfiguration);
12986 changes = newConfig.updateFrom(values);
12987 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012988 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012989 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990 }
12991
Doug Zongker2bec3d42009-12-04 12:52:44 -080012992 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993
Dianne Hackborn813075a62011-11-14 17:45:19 -080012994 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 saveLocaleLocked(values.locale,
12996 !values.locale.equals(mConfiguration.locale),
12997 values.userSetLocale);
12998 }
12999
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013000 mConfigurationSeq++;
13001 if (mConfigurationSeq <= 0) {
13002 mConfigurationSeq = 1;
13003 }
13004 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013006 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013007
13008 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013009
13010 // TODO: If our config changes, should we auto dismiss any currently
13011 // showing dialogs?
13012 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013013
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013014 AttributeCache ac = AttributeCache.instance();
13015 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013016 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013018
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013019 // Make sure all resources in our process are updated
13020 // right now, so that anyone who is going to retrieve
13021 // resource values after we return will be sure to get
13022 // the new ones. This is especially important during
13023 // boot, where the first config change needs to guarantee
13024 // all resources have that config before following boot
13025 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013026 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013027
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013028 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013029 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013030 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013031 mHandler.sendMessage(msg);
13032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013034 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13035 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013036 try {
13037 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013038 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013039 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013040 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041 }
13042 } catch (Exception e) {
13043 }
13044 }
13045 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013046 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13047 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013049 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013050 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13051 broadcastIntentLocked(null, null,
13052 new Intent(Intent.ACTION_LOCALE_CHANGED),
13053 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013054 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013056 }
13057 }
13058
13059 if (changes != 0 && starting == null) {
13060 // If the configuration changed, and the caller is not already
13061 // in the process of starting an activity, then find the top
13062 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013063 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013064 }
13065
13066 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013067 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013068 // And we need to make sure at this point that all other activities
13069 // are made visible with the correct configuration.
13070 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 }
13072
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013073 if (values != null && mWindowManager != null) {
13074 mWindowManager.setNewConfiguration(mConfiguration);
13075 }
13076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013077 return kept;
13078 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013079
13080 /**
13081 * Decide based on the configuration whether we should shouw the ANR,
13082 * crash, etc dialogs. The idea is that if there is no affordnace to
13083 * press the on-screen buttons, we shouldn't show the dialog.
13084 *
13085 * A thought: SystemUI might also want to get told about this, the Power
13086 * dialog / global actions also might want different behaviors.
13087 */
13088 private static final boolean shouldShowDialogs(Configuration config) {
13089 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13090 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013092
13093 /**
13094 * Save the locale. You must be inside a synchronized (this) block.
13095 */
13096 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13097 if(isDiff) {
13098 SystemProperties.set("user.language", l.getLanguage());
13099 SystemProperties.set("user.region", l.getCountry());
13100 }
13101
13102 if(isPersist) {
13103 SystemProperties.set("persist.sys.language", l.getLanguage());
13104 SystemProperties.set("persist.sys.country", l.getCountry());
13105 SystemProperties.set("persist.sys.localevar", l.getVariant());
13106 }
13107 }
13108
13109 // =========================================================
13110 // LIFETIME MANAGEMENT
13111 // =========================================================
13112
Christopher Tatef46723b2012-01-26 14:19:24 -080013113 // Returns which broadcast queue the app is the current [or imminent] receiver
13114 // on, or 'null' if the app is not an active broadcast recipient.
13115 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13116 BroadcastRecord r = app.curReceiver;
13117 if (r != null) {
13118 return r.queue;
13119 }
13120
13121 // It's not the current receiver, but it might be starting up to become one
13122 synchronized (this) {
13123 for (BroadcastQueue queue : mBroadcastQueues) {
13124 r = queue.mPendingBroadcast;
13125 if (r != null && r.curApp == app) {
13126 // found it; report which queue it's in
13127 return queue;
13128 }
13129 }
13130 }
13131
13132 return null;
13133 }
13134
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013135 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013136 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013138 // This adjustment has already been computed. If we are calling
13139 // from the top, we may have already computed our adjustment with
13140 // an earlier hidden adjustment that isn't really for us... if
13141 // so, use the new hidden adjustment.
13142 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013143 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013144 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013145 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 }
13147
13148 if (app.thread == null) {
13149 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013150 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013151 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 }
13153
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013154 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13155 app.adjSource = null;
13156 app.adjTarget = null;
13157 app.empty = false;
13158 app.hidden = false;
13159
13160 final int activitiesSize = app.activities.size();
13161
Dianne Hackborn7d608422011-08-07 16:24:18 -070013162 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013163 // The max adjustment doesn't allow this app to be anything
13164 // below foreground, so it is not worth doing work for it.
13165 app.adjType = "fixed";
13166 app.adjSeq = mAdjSeq;
13167 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013168 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013169 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013170 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013171 // System process can do UI, and when they do we want to have
13172 // them trim their memory after the user leaves the UI. To
13173 // facilitate this, here we need to determine whether or not it
13174 // is currently showing UI.
13175 app.systemNoUi = true;
13176 if (app == TOP_APP) {
13177 app.systemNoUi = false;
13178 } else if (activitiesSize > 0) {
13179 for (int j = 0; j < activitiesSize; j++) {
13180 final ActivityRecord r = app.activities.get(j);
13181 if (r.visible) {
13182 app.systemNoUi = false;
13183 break;
13184 }
13185 }
13186 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013187 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013188 }
13189
13190 final boolean hadForegroundActivities = app.foregroundActivities;
13191
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013192 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013193 app.keeping = false;
13194 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013195
The Android Open Source Project4df24232009-03-05 14:34:35 -080013196 // Determine the importance of the process, starting with most
13197 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013199 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013200 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013201 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013203 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013204 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013205 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013206 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013207 } else if (app.instrumentationClass != null) {
13208 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013209 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013210 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013211 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013212 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013214 // counts as being in the foreground for OOM killer purposes.
13215 // It's placed in a sched group based on the nature of the
13216 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013217 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013218 schedGroup = (queue == mFgBroadcastQueue)
13219 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013220 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013221 } else if (app.executingServices.size() > 0) {
13222 // An app that is currently executing a service callback also
13223 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013224 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013225 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013226 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013227 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013229 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013231 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013232 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013233 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013234 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013235 // A very not-needed process. If this is lower in the lru list,
13236 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013237 adj = hiddenAdj;
13238 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013239 app.hidden = true;
13240 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013241 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013243
13244 // Examine all activities if not already foreground.
13245 if (!app.foregroundActivities && activitiesSize > 0) {
13246 for (int j = 0; j < activitiesSize; j++) {
13247 final ActivityRecord r = app.activities.get(j);
13248 if (r.visible) {
13249 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013250 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13251 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013252 app.adjType = "visible";
13253 }
13254 schedGroup = Process.THREAD_GROUP_DEFAULT;
13255 app.hidden = false;
13256 app.foregroundActivities = true;
13257 break;
13258 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13259 || r.state == ActivityState.STOPPING) {
13260 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013261 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13262 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013263 app.adjType = "stopping";
13264 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013265 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013266 app.foregroundActivities = true;
13267 }
13268 }
13269 }
13270
Dianne Hackborn7d608422011-08-07 16:24:18 -070013271 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013272 if (app.foregroundServices) {
13273 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013274 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013275 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013276 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013277 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013278 } else if (app.forcingToForeground != null) {
13279 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013280 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013281 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013282 app.adjType = "force-foreground";
13283 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013284 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013285 }
13286 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013287
Dianne Hackborn7d608422011-08-07 16:24:18 -070013288 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013289 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013290 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013291 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013292 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013293 app.adjType = "heavy";
13294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013295
Dianne Hackborn7d608422011-08-07 16:24:18 -070013296 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013297 // This process is hosting what we currently consider to be the
13298 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013299 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013300 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013301 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013302 app.adjType = "home";
13303 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013304
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013305 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13306 && app.activities.size() > 0) {
13307 // This was the previous process that showed UI to the user.
13308 // We want to try to keep it around more aggressively, to give
13309 // a good experience around switching between two apps.
13310 adj = ProcessList.PREVIOUS_APP_ADJ;
13311 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13312 app.hidden = false;
13313 app.adjType = "previous";
13314 }
13315
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013316 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13317 + " reason=" + app.adjType);
13318
The Android Open Source Project4df24232009-03-05 14:34:35 -080013319 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 // there are applications dependent on our services or providers, but
13321 // this gives us a baseline and makes sure we don't get into an
13322 // infinite recursion.
13323 app.adjSeq = mAdjSeq;
13324 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325
Christopher Tate6fa95972009-06-05 18:43:55 -070013326 if (mBackupTarget != null && app == mBackupTarget.app) {
13327 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013328 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013329 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013330 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013331 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013332 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013333 }
13334 }
13335
Dianne Hackborn7d608422011-08-07 16:24:18 -070013336 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013337 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 final long now = SystemClock.uptimeMillis();
13339 // This process is more important if the top activity is
13340 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013341 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013342 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013343 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013345 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013346 // If this process has shown some UI, let it immediately
13347 // go to the LRU list because it may be pretty heavy with
13348 // UI stuff. We'll tag it with a label just to help
13349 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013350 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013351 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013353 } else {
13354 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13355 // This service has seen some activity within
13356 // recent memory, so we will keep its process ahead
13357 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013358 if (adj > ProcessList.SERVICE_ADJ) {
13359 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013360 app.adjType = "started-services";
13361 app.hidden = false;
13362 }
13363 }
13364 // If we have let the service slide into the background
13365 // state, still have some text describing what it is doing
13366 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013367 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013368 app.adjType = "started-bg-services";
13369 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013370 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013371 // Don't kill this process because it is doing work; it
13372 // has said it is doing work.
13373 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013375 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013376 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013377 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013378 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013379 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013380 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013381 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013382 // XXX should compute this based on the max of
13383 // all connected clients.
13384 ConnectionRecord cr = clist.get(i);
13385 if (cr.binding.client == app) {
13386 // Binding to ourself is not interesting.
13387 continue;
13388 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013389 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013390 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013391 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013392 int myHiddenAdj = hiddenAdj;
13393 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013394 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013395 myHiddenAdj = client.hiddenAdj;
13396 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013397 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013398 }
13399 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013400 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013401 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013402 String adjType = null;
13403 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13404 // Not doing bind OOM management, so treat
13405 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013406 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013407 // If this process has shown some UI, let it immediately
13408 // go to the LRU list because it may be pretty heavy with
13409 // UI stuff. We'll tag it with a label just to help
13410 // debug and understand what is going on.
13411 if (adj > clientAdj) {
13412 adjType = "bound-bg-ui-services";
13413 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013414 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013415 clientAdj = adj;
13416 } else {
13417 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13418 // This service has not seen activity within
13419 // recent memory, so allow it to drop to the
13420 // LRU list if there is no other reason to keep
13421 // it around. We'll also tag it with a label just
13422 // to help debug and undertand what is going on.
13423 if (adj > clientAdj) {
13424 adjType = "bound-bg-services";
13425 }
13426 clientAdj = adj;
13427 }
13428 }
13429 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013430 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013431 // If this process has recently shown UI, and
13432 // the process that is binding to it is less
13433 // important than being visible, then we don't
13434 // care about the binding as much as we care
13435 // about letting this process get into the LRU
13436 // list to be killed and restarted if needed for
13437 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013438 if (app.hasShownUi && app != mHomeProcess
13439 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013440 adjType = "bound-bg-ui-services";
13441 } else {
13442 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13443 |Context.BIND_IMPORTANT)) != 0) {
13444 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013445 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13446 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13447 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13448 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13449 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013450 adj = clientAdj;
13451 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013452 app.pendingUiClean = true;
13453 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13454 adj = ProcessList.VISIBLE_APP_ADJ;
13455 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013456 }
13457 if (!client.hidden) {
13458 app.hidden = false;
13459 }
13460 if (client.keeping) {
13461 app.keeping = true;
13462 }
13463 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013464 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013465 }
13466 if (adjType != null) {
13467 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013468 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13469 .REASON_SERVICE_IN_USE;
13470 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013471 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013472 app.adjTarget = s.name;
13473 }
13474 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13475 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13476 schedGroup = Process.THREAD_GROUP_DEFAULT;
13477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013478 }
13479 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013480 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13481 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013482 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013483 (a.visible || a.state == ActivityState.RESUMED
13484 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013485 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013486 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13487 schedGroup = Process.THREAD_GROUP_DEFAULT;
13488 }
13489 app.hidden = false;
13490 app.adjType = "service";
13491 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13492 .REASON_SERVICE_IN_USE;
13493 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013494 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013495 app.adjTarget = s.name;
13496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 }
13499 }
13500 }
13501 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013502
Dianne Hackborn287952c2010-09-22 22:34:31 -070013503 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013504 // would like to avoid killing it unless it would prevent the current
13505 // application from running. By default we put the process in
13506 // with the rest of the background processes; as we scan through
13507 // its services we may bump it up from there.
13508 if (adj > hiddenAdj) {
13509 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013510 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013511 app.adjType = "bg-services";
13512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013513 }
13514
Dianne Hackborn7d608422011-08-07 16:24:18 -070013515 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013516 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013517 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013518 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013519 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013520 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 if (cpr.clients.size() != 0) {
13522 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013523 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013524 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013525 if (client == app) {
13526 // Being our own client is not interesting.
13527 continue;
13528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 int myHiddenAdj = hiddenAdj;
13530 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013531 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 myHiddenAdj = client.hiddenAdj;
13533 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013534 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013535 }
13536 }
13537 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013538 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013539 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013540 if (app.hasShownUi && app != mHomeProcess
13541 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013542 app.adjType = "bg-ui-provider";
13543 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013544 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13545 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013546 app.adjType = "provider";
13547 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013548 if (!client.hidden) {
13549 app.hidden = false;
13550 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013551 if (client.keeping) {
13552 app.keeping = true;
13553 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013554 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13555 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013556 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013557 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013558 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013559 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013560 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13561 schedGroup = Process.THREAD_GROUP_DEFAULT;
13562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013563 }
13564 }
13565 // If the provider has external (non-framework) process
13566 // dependencies, ensure that its adjustment is at least
13567 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013568 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013569 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13570 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013571 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013572 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013573 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013574 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013575 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013576 }
13577 }
13578 }
13579 }
13580
13581 app.curRawAdj = adj;
13582
Joe Onorato8a9b2202010-02-26 18:56:32 -080013583 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013584 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13585 if (adj > app.maxAdj) {
13586 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013587 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013588 schedGroup = Process.THREAD_GROUP_DEFAULT;
13589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013591 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013592 app.keeping = true;
13593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013594
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013595 if (app.hasAboveClient) {
13596 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13597 // then we need to drop its adjustment to be lower than the service's
13598 // in order to honor the request. We want to drop it by one adjustment
13599 // level... but there is special meaning applied to various levels so
13600 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013601 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013602 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013603 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13604 adj = ProcessList.VISIBLE_APP_ADJ;
13605 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13606 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13607 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13608 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013609 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013610 adj++;
13611 }
13612 }
13613
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013614 if (adj == ProcessList.SERVICE_ADJ) {
13615 if (doingAll) {
13616 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13617 mNewNumServiceProcs++;
13618 }
13619 if (app.serviceb) {
13620 adj = ProcessList.SERVICE_B_ADJ;
13621 }
13622 } else {
13623 app.serviceb = false;
13624 }
13625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013627 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013628
13629 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013630 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13631 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013632 }
13633
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013634 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013635 }
13636
13637 /**
13638 * Ask a given process to GC right now.
13639 */
13640 final void performAppGcLocked(ProcessRecord app) {
13641 try {
13642 app.lastRequestedGc = SystemClock.uptimeMillis();
13643 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013644 if (app.reportLowMemory) {
13645 app.reportLowMemory = false;
13646 app.thread.scheduleLowMemory();
13647 } else {
13648 app.thread.processInBackground();
13649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013650 }
13651 } catch (Exception e) {
13652 // whatever.
13653 }
13654 }
13655
13656 /**
13657 * Returns true if things are idle enough to perform GCs.
13658 */
Josh Bartel7f208742010-02-25 11:01:44 -060013659 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013660 boolean processingBroadcasts = false;
13661 for (BroadcastQueue q : mBroadcastQueues) {
13662 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13663 processingBroadcasts = true;
13664 }
13665 }
13666 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013667 && (mSleeping || (mMainStack.mResumedActivity != null &&
13668 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013669 }
13670
13671 /**
13672 * Perform GCs on all processes that are waiting for it, but only
13673 * if things are idle.
13674 */
13675 final void performAppGcsLocked() {
13676 final int N = mProcessesToGc.size();
13677 if (N <= 0) {
13678 return;
13679 }
Josh Bartel7f208742010-02-25 11:01:44 -060013680 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 while (mProcessesToGc.size() > 0) {
13682 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013683 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013684 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13685 <= SystemClock.uptimeMillis()) {
13686 // To avoid spamming the system, we will GC processes one
13687 // at a time, waiting a few seconds between each.
13688 performAppGcLocked(proc);
13689 scheduleAppGcsLocked();
13690 return;
13691 } else {
13692 // It hasn't been long enough since we last GCed this
13693 // process... put it in the list to wait for its time.
13694 addProcessToGcListLocked(proc);
13695 break;
13696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 }
13698 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013699
13700 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 }
13702 }
13703
13704 /**
13705 * If all looks good, perform GCs on all processes waiting for them.
13706 */
13707 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013708 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013709 performAppGcsLocked();
13710 return;
13711 }
13712 // Still not idle, wait some more.
13713 scheduleAppGcsLocked();
13714 }
13715
13716 /**
13717 * Schedule the execution of all pending app GCs.
13718 */
13719 final void scheduleAppGcsLocked() {
13720 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013721
13722 if (mProcessesToGc.size() > 0) {
13723 // Schedule a GC for the time to the next process.
13724 ProcessRecord proc = mProcessesToGc.get(0);
13725 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13726
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013727 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013728 long now = SystemClock.uptimeMillis();
13729 if (when < (now+GC_TIMEOUT)) {
13730 when = now + GC_TIMEOUT;
13731 }
13732 mHandler.sendMessageAtTime(msg, when);
13733 }
13734 }
13735
13736 /**
13737 * Add a process to the array of processes waiting to be GCed. Keeps the
13738 * list in sorted order by the last GC time. The process can't already be
13739 * on the list.
13740 */
13741 final void addProcessToGcListLocked(ProcessRecord proc) {
13742 boolean added = false;
13743 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13744 if (mProcessesToGc.get(i).lastRequestedGc <
13745 proc.lastRequestedGc) {
13746 added = true;
13747 mProcessesToGc.add(i+1, proc);
13748 break;
13749 }
13750 }
13751 if (!added) {
13752 mProcessesToGc.add(0, proc);
13753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013754 }
13755
13756 /**
13757 * Set up to ask a process to GC itself. This will either do it
13758 * immediately, or put it on the list of processes to gc the next
13759 * time things are idle.
13760 */
13761 final void scheduleAppGcLocked(ProcessRecord app) {
13762 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013763 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764 return;
13765 }
13766 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013767 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013768 scheduleAppGcsLocked();
13769 }
13770 }
13771
Dianne Hackborn287952c2010-09-22 22:34:31 -070013772 final void checkExcessivePowerUsageLocked(boolean doKills) {
13773 updateCpuStatsNow();
13774
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013775 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013776 boolean doWakeKills = doKills;
13777 boolean doCpuKills = doKills;
13778 if (mLastPowerCheckRealtime == 0) {
13779 doWakeKills = false;
13780 }
13781 if (mLastPowerCheckUptime == 0) {
13782 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013783 }
13784 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013785 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013786 }
13787 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013788 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13789 final long curUptime = SystemClock.uptimeMillis();
13790 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13791 mLastPowerCheckRealtime = curRealtime;
13792 mLastPowerCheckUptime = curUptime;
13793 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13794 doWakeKills = false;
13795 }
13796 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13797 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013798 }
13799 int i = mLruProcesses.size();
13800 while (i > 0) {
13801 i--;
13802 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013803 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013804 long wtime;
13805 synchronized (stats) {
13806 wtime = stats.getProcessWakeTime(app.info.uid,
13807 app.pid, curRealtime);
13808 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013809 long wtimeUsed = wtime - app.lastWakeTime;
13810 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13811 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013812 StringBuilder sb = new StringBuilder(128);
13813 sb.append("Wake for ");
13814 app.toShortString(sb);
13815 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013816 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013817 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013818 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013819 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013820 sb.append((wtimeUsed*100)/realtimeSince);
13821 sb.append("%)");
13822 Slog.i(TAG, sb.toString());
13823 sb.setLength(0);
13824 sb.append("CPU for ");
13825 app.toShortString(sb);
13826 sb.append(": over ");
13827 TimeUtils.formatDuration(uptimeSince, sb);
13828 sb.append(" used ");
13829 TimeUtils.formatDuration(cputimeUsed, sb);
13830 sb.append(" (");
13831 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013832 sb.append("%)");
13833 Slog.i(TAG, sb.toString());
13834 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013835 // If a process has held a wake lock for more
13836 // than 50% of the time during this period,
13837 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013838 if (doWakeKills && realtimeSince > 0
13839 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13840 synchronized (stats) {
13841 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13842 realtimeSince, wtimeUsed);
13843 }
13844 Slog.w(TAG, "Excessive wake lock in " + app.processName
13845 + " (pid " + app.pid + "): held " + wtimeUsed
13846 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013847 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13848 app.processName, app.setAdj, "excessive wake lock");
13849 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013850 } else if (doCpuKills && uptimeSince > 0
13851 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13852 synchronized (stats) {
13853 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13854 uptimeSince, cputimeUsed);
13855 }
13856 Slog.w(TAG, "Excessive CPU in " + app.processName
13857 + " (pid " + app.pid + "): used " + cputimeUsed
13858 + " during " + uptimeSince);
13859 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13860 app.processName, app.setAdj, "excessive cpu");
13861 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013862 } else {
13863 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013864 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013865 }
13866 }
13867 }
13868 }
13869
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013870 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013871 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872 app.hiddenAdj = hiddenAdj;
13873
13874 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013875 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013876 }
13877
Dianne Hackborn287952c2010-09-22 22:34:31 -070013878 final boolean wasKeeping = app.keeping;
13879
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013880 boolean success = true;
13881
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013882 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883
Jeff Brown10e89712011-07-08 18:52:57 -070013884 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070013885 if (false) {
13886 // Removing for now. Forcing GCs is not so useful anymore
13887 // with Dalvik, and the new memory level hint facility is
13888 // better for what we need to do these days.
13889 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
13890 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13891 // If this app is transitioning from foreground to
13892 // non-foreground, have it do a gc.
13893 scheduleAppGcLocked(app);
13894 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13895 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13896 // Likewise do a gc when an app is moving in to the
13897 // background (such as a service stopping).
13898 scheduleAppGcLocked(app);
13899 }
Jeff Brown10e89712011-07-08 18:52:57 -070013900 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013901
Jeff Brown10e89712011-07-08 18:52:57 -070013902 if (wasKeeping && !app.keeping) {
13903 // This app is no longer something we want to keep. Note
13904 // its current wake lock time to later know to kill it if
13905 // it is not behaving well.
13906 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13907 synchronized (stats) {
13908 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13909 app.pid, SystemClock.elapsedRealtime());
13910 }
13911 app.lastCpuTime = app.curCpuTime;
13912 }
13913
13914 app.setRawAdj = app.curRawAdj;
13915 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013916
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013917 if (app.curAdj != app.setAdj) {
13918 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013919 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013920 TAG, "Set " + app.pid + " " + app.processName +
13921 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013922 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013923 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013924 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013926 }
13927 }
13928 if (app.setSchedGroup != app.curSchedGroup) {
13929 app.setSchedGroup = app.curSchedGroup;
13930 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13931 "Setting process group of " + app.processName
13932 + " to " + app.curSchedGroup);
13933 if (app.waitingToKill != null &&
13934 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13935 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13936 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13937 app.processName, app.setAdj, app.waitingToKill);
13938 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013939 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013940 } else {
13941 if (true) {
13942 long oldId = Binder.clearCallingIdentity();
13943 try {
13944 Process.setProcessGroup(app.pid, app.curSchedGroup);
13945 } catch (Exception e) {
13946 Slog.w(TAG, "Failed setting process group of " + app.pid
13947 + " to " + app.curSchedGroup);
13948 e.printStackTrace();
13949 } finally {
13950 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013951 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013952 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013953 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013954 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013955 app.thread.setSchedulingGroup(app.curSchedGroup);
13956 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013957 }
13958 }
13959 }
13960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013962 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013963 }
13964
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013965 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013966 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013967 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013968 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013970 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013971 }
13972 }
13973 return resumedActivity;
13974 }
13975
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013976 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013977 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13979 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013980 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13981 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982
13983 mAdjSeq++;
13984
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013985 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013986 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13987 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013988 if (nowHidden != wasHidden) {
13989 // Changed to/from hidden state, so apps after it in the LRU
13990 // list may also be changed.
13991 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013992 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013993 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013994 }
13995
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013996 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013997 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013998 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13999
14000 if (false) {
14001 RuntimeException e = new RuntimeException();
14002 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014003 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014004 }
14005
14006 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014007 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014008
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014009 // Let's determine how many processes we have running vs.
14010 // how many slots we have for background processes; we may want
14011 // to put multiple processes in a slot of there are enough of
14012 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014013 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014014 int factor = (mLruProcesses.size()-4)/numSlots;
14015 if (factor < 1) factor = 1;
14016 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014017 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014018
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014019 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014020 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014021 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014022 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014023 while (i > 0) {
14024 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014025 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014026 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014027 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14028 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014029 && app.curAdj == curHiddenAdj) {
14030 step++;
14031 if (step >= factor) {
14032 step = 0;
14033 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014034 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014035 }
14036 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014037 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014038 numHidden++;
14039 if (numHidden > mProcessLimit) {
14040 Slog.i(TAG, "No longer want " + app.processName
14041 + " (pid " + app.pid + "): hidden #" + numHidden);
14042 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14043 app.processName, app.setAdj, "too many background");
14044 app.killedBackground = true;
14045 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014046 }
14047 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014048 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14049 // If this is an isolated process, and there are no
14050 // services running in it, then the process is no longer
14051 // needed. We agressively kill these because we can by
14052 // definition not re-use the same process again, and it is
14053 // good to avoid having whatever code was running in them
14054 // left sitting around after no longer needed.
14055 Slog.i(TAG, "Isolated process " + app.processName
14056 + " (pid " + app.pid + ") no longer needed");
14057 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14058 app.processName, app.setAdj, "isolated not needed");
14059 app.killedBackground = true;
14060 Process.killProcessQuiet(app.pid);
14061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014062 }
14063 }
14064
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014065 mNumServiceProcs = mNewNumServiceProcs;
14066
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014067 // Now determine the memory trimming level of background processes.
14068 // Unfortunately we need to start at the back of the list to do this
14069 // properly. We only do this if the number of background apps we
14070 // are managing to keep around is less than half the maximum we desire;
14071 // if we are keeping a good number around, we'll let them use whatever
14072 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014073 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014074 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014075 factor = numHidden/3;
14076 int minFactor = 2;
14077 if (mHomeProcess != null) minFactor++;
14078 if (mPreviousProcess != null) minFactor++;
14079 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014080 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014081 int fgTrimLevel;
14082 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14083 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14084 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14085 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14086 } else {
14087 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14088 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014089 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014090 for (i=0; i<N; i++) {
14091 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014092 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14093 && app.curAdj != ProcessList.SERVICE_B_ADJ
14094 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014095 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14096 try {
14097 app.thread.scheduleTrimMemory(curLevel);
14098 } catch (RemoteException e) {
14099 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014100 if (false) {
14101 // For now we won't do this; our memory trimming seems
14102 // to be good enough at this point that destroying
14103 // activities causes more harm than good.
14104 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14105 && app != mHomeProcess && app != mPreviousProcess) {
14106 // For these apps we will also finish their activities
14107 // to help them free memory.
14108 mMainStack.destroyActivitiesLocked(app, false, "trim");
14109 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014110 }
14111 }
14112 app.trimMemoryLevel = curLevel;
14113 step++;
14114 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014115 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014116 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014117 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14118 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014119 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014120 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14121 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014122 break;
14123 }
14124 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014125 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014126 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014127 && app.thread != null) {
14128 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014129 app.thread.scheduleTrimMemory(
14130 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014131 } catch (RemoteException e) {
14132 }
14133 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014134 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014135 } else {
14136 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14137 && app.pendingUiClean) {
14138 // If this application is now in the background and it
14139 // had done UI, then give it the special trim level to
14140 // have it free UI resources.
14141 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14142 if (app.trimMemoryLevel < level && app.thread != null) {
14143 try {
14144 app.thread.scheduleTrimMemory(level);
14145 } catch (RemoteException e) {
14146 }
14147 }
14148 app.pendingUiClean = false;
14149 }
14150 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014151 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014152 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014153 } catch (RemoteException e) {
14154 }
14155 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014156 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014157 }
14158 }
14159 } else {
14160 final int N = mLruProcesses.size();
14161 for (i=0; i<N; i++) {
14162 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014163 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014164 && app.pendingUiClean) {
14165 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14166 && app.thread != null) {
14167 try {
14168 app.thread.scheduleTrimMemory(
14169 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14170 } catch (RemoteException e) {
14171 }
14172 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014173 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014174 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014175 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014176 }
14177 }
14178
14179 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014180 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014182 }
14183
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014184 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014185 synchronized (this) {
14186 int i;
14187
14188 // First remove any unused application processes whose package
14189 // has been removed.
14190 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14191 final ProcessRecord app = mRemovedProcesses.get(i);
14192 if (app.activities.size() == 0
14193 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014194 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014195 TAG, "Exiting empty application process "
14196 + app.processName + " ("
14197 + (app.thread != null ? app.thread.asBinder() : null)
14198 + ")\n");
14199 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014200 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14201 app.processName, app.setAdj, "empty");
14202 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014203 } else {
14204 try {
14205 app.thread.scheduleExit();
14206 } catch (Exception e) {
14207 // Ignore exceptions.
14208 }
14209 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014210 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014211 mRemovedProcesses.remove(i);
14212
14213 if (app.persistent) {
14214 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014215 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014216 }
14217 }
14218 }
14219 }
14220
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014221 // Now update the oom adj for all processes.
14222 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014223 }
14224 }
14225
14226 /** This method sends the specified signal to each of the persistent apps */
14227 public void signalPersistentProcesses(int sig) throws RemoteException {
14228 if (sig != Process.SIGNAL_USR1) {
14229 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14230 }
14231
14232 synchronized (this) {
14233 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14234 != PackageManager.PERMISSION_GRANTED) {
14235 throw new SecurityException("Requires permission "
14236 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14237 }
14238
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014239 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14240 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014241 if (r.thread != null && r.persistent) {
14242 Process.sendSignal(r.pid, sig);
14243 }
14244 }
14245 }
14246 }
14247
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014248 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14249 if (proc == null || proc == mProfileProc) {
14250 proc = mProfileProc;
14251 path = mProfileFile;
14252 profileType = mProfileType;
14253 clearProfilerLocked();
14254 }
14255 if (proc == null) {
14256 return;
14257 }
14258 try {
14259 proc.thread.profilerControl(false, path, null, profileType);
14260 } catch (RemoteException e) {
14261 throw new IllegalStateException("Process disappeared");
14262 }
14263 }
14264
14265 private void clearProfilerLocked() {
14266 if (mProfileFd != null) {
14267 try {
14268 mProfileFd.close();
14269 } catch (IOException e) {
14270 }
14271 }
14272 mProfileApp = null;
14273 mProfileProc = null;
14274 mProfileFile = null;
14275 mProfileType = 0;
14276 mAutoStopProfiler = false;
14277 }
14278
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014279 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014280 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014281
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014282 try {
14283 synchronized (this) {
14284 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14285 // its own permission.
14286 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14287 != PackageManager.PERMISSION_GRANTED) {
14288 throw new SecurityException("Requires permission "
14289 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014290 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014291
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014292 if (start && fd == null) {
14293 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014294 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014295
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014296 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014297 if (process != null) {
14298 try {
14299 int pid = Integer.parseInt(process);
14300 synchronized (mPidsSelfLocked) {
14301 proc = mPidsSelfLocked.get(pid);
14302 }
14303 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014304 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014305
14306 if (proc == null) {
14307 HashMap<String, SparseArray<ProcessRecord>> all
14308 = mProcessNames.getMap();
14309 SparseArray<ProcessRecord> procs = all.get(process);
14310 if (procs != null && procs.size() > 0) {
14311 proc = procs.valueAt(0);
14312 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014313 }
14314 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014315
14316 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014317 throw new IllegalArgumentException("Unknown process: " + process);
14318 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014319
14320 if (start) {
14321 stopProfilerLocked(null, null, 0);
14322 setProfileApp(proc.info, proc.processName, path, fd, false);
14323 mProfileProc = proc;
14324 mProfileType = profileType;
14325 try {
14326 fd = fd.dup();
14327 } catch (IOException e) {
14328 fd = null;
14329 }
14330 proc.thread.profilerControl(start, path, fd, profileType);
14331 fd = null;
14332 mProfileFd = null;
14333 } else {
14334 stopProfilerLocked(proc, path, profileType);
14335 if (fd != null) {
14336 try {
14337 fd.close();
14338 } catch (IOException e) {
14339 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014340 }
14341 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014342
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014343 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014344 }
14345 } catch (RemoteException e) {
14346 throw new IllegalStateException("Process disappeared");
14347 } finally {
14348 if (fd != null) {
14349 try {
14350 fd.close();
14351 } catch (IOException e) {
14352 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014353 }
14354 }
14355 }
Andy McFadden824c5102010-07-09 16:26:57 -070014356
14357 public boolean dumpHeap(String process, boolean managed,
14358 String path, ParcelFileDescriptor fd) throws RemoteException {
14359
14360 try {
14361 synchronized (this) {
14362 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14363 // its own permission (same as profileControl).
14364 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14365 != PackageManager.PERMISSION_GRANTED) {
14366 throw new SecurityException("Requires permission "
14367 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14368 }
14369
14370 if (fd == null) {
14371 throw new IllegalArgumentException("null fd");
14372 }
14373
14374 ProcessRecord proc = null;
14375 try {
14376 int pid = Integer.parseInt(process);
14377 synchronized (mPidsSelfLocked) {
14378 proc = mPidsSelfLocked.get(pid);
14379 }
14380 } catch (NumberFormatException e) {
14381 }
14382
14383 if (proc == null) {
14384 HashMap<String, SparseArray<ProcessRecord>> all
14385 = mProcessNames.getMap();
14386 SparseArray<ProcessRecord> procs = all.get(process);
14387 if (procs != null && procs.size() > 0) {
14388 proc = procs.valueAt(0);
14389 }
14390 }
14391
14392 if (proc == null || proc.thread == null) {
14393 throw new IllegalArgumentException("Unknown process: " + process);
14394 }
14395
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014396 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14397 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014398 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14399 throw new SecurityException("Process not debuggable: " + proc);
14400 }
14401 }
14402
14403 proc.thread.dumpHeap(managed, path, fd);
14404 fd = null;
14405 return true;
14406 }
14407 } catch (RemoteException e) {
14408 throw new IllegalStateException("Process disappeared");
14409 } finally {
14410 if (fd != null) {
14411 try {
14412 fd.close();
14413 } catch (IOException e) {
14414 }
14415 }
14416 }
14417 }
14418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014419 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14420 public void monitor() {
14421 synchronized (this) { }
14422 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014423
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014424 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014425 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14426 ProcessRecord processRecord = mLruProcesses.get(i);
14427 try {
14428 if (processRecord.thread != null) {
14429 processRecord.thread.setCoreSettings(settings);
14430 }
14431 } catch (RemoteException re) {
14432 /* ignore */
14433 }
14434 }
14435 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014436
14437 // Multi-user methods
14438
Amith Yamasani742a6712011-05-04 14:49:28 -070014439 private int mCurrentUserId;
14440 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014441 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14442
14443 public interface UserListener {
14444 public void onUserChanged(int userId);
14445
14446 public void onUserAdded(int userId);
14447
14448 public void onUserRemoved(int userId);
14449
14450 public void onUserLoggedOut(int userId);
14451 }
14452
14453 public void addUserListener(UserListener listener) {
14454 synchronized (this) {
14455 if (!mUserListeners.contains(listener)) {
14456 mUserListeners.add(listener);
14457 }
14458 }
14459 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014460
14461 public boolean switchUser(int userId) {
14462 final int callingUid = Binder.getCallingUid();
14463 if (callingUid != 0 && callingUid != Process.myUid()) {
14464 Slog.e(TAG, "Trying to switch user from unauthorized app");
14465 return false;
14466 }
14467 if (mCurrentUserId == userId)
14468 return true;
14469
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014470 ArrayList<UserListener> listeners;
14471
Amith Yamasani742a6712011-05-04 14:49:28 -070014472 synchronized (this) {
14473 // Check if user is already logged in, otherwise check if user exists first before
14474 // adding to the list of logged in users.
14475 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14476 if (!userExists(userId)) {
14477 return false;
14478 }
14479 mLoggedInUsers.append(userId, userId);
14480 }
14481
14482 mCurrentUserId = userId;
14483 boolean haveActivities = mMainStack.switchUser(userId);
14484 if (!haveActivities) {
14485 startHomeActivityLocked(userId);
14486 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014487
14488 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14489 }
14490 // Inform the listeners
14491 for (UserListener listener : listeners) {
14492 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014493 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014494 return true;
14495 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014496
14497 private boolean userExists(int userId) {
14498 try {
14499 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14500 for (UserInfo user : users) {
14501 if (user.id == userId) {
14502 return true;
14503 }
14504 }
14505 } catch (RemoteException re) {
14506 // Won't happen, in same process
14507 }
14508
14509 return false;
14510 }
14511
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014512 private void checkValidCaller(int uid, int userId) {
14513 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14514
14515 throw new SecurityException("Caller uid=" + uid
14516 + " is not privileged to communicate with user=" + userId);
14517 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014518
14519 private int applyUserId(int uid, int userId) {
14520 return UserId.getUid(userId, uid);
14521 }
14522
14523 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014524 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014525 ApplicationInfo newInfo = new ApplicationInfo(info);
14526 newInfo.uid = applyUserId(info.uid, userId);
14527 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14528 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14529 + info.packageName;
14530 }
14531 return newInfo;
14532 }
14533
14534 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014535 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014536 || userId < 1) {
14537 return aInfo;
14538 }
14539
14540 ActivityInfo info = new ActivityInfo(aInfo);
14541 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14542 return info;
14543 }
14544
14545 static class ServiceMap {
14546
14547 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14548 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14549 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14550 mServicesByIntentPerUser = new SparseArray<
14551 HashMap<Intent.FilterComparison, ServiceRecord>>();
14552
14553 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14554 // TODO: Deal with global services
14555 if (DEBUG_MU)
14556 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14557 return getServices(callingUser).get(name);
14558 }
14559
14560 ServiceRecord getServiceByName(ComponentName name) {
14561 return getServiceByName(name, -1);
14562 }
14563
14564 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14565 // TODO: Deal with global services
14566 if (DEBUG_MU)
14567 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14568 return getServicesByIntent(callingUser).get(filter);
14569 }
14570
14571 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14572 return getServiceByIntent(filter, -1);
14573 }
14574
14575 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14576 // TODO: Deal with global services
14577 getServices(callingUser).put(name, value);
14578 }
14579
14580 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14581 ServiceRecord value) {
14582 // TODO: Deal with global services
14583 getServicesByIntent(callingUser).put(filter, value);
14584 }
14585
14586 void removeServiceByName(ComponentName name, int callingUser) {
14587 // TODO: Deal with global services
14588 ServiceRecord removed = getServices(callingUser).remove(name);
14589 if (DEBUG_MU)
14590 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14591 + " removed=" + removed);
14592 }
14593
14594 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14595 // TODO: Deal with global services
14596 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14597 if (DEBUG_MU)
14598 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14599 + " removed=" + removed);
14600 }
14601
14602 Collection<ServiceRecord> getAllServices(int callingUser) {
14603 // TODO: Deal with global services
14604 return getServices(callingUser).values();
14605 }
14606
14607 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14608 HashMap map = mServicesByNamePerUser.get(callingUser);
14609 if (map == null) {
14610 map = new HashMap<ComponentName, ServiceRecord>();
14611 mServicesByNamePerUser.put(callingUser, map);
14612 }
14613 return map;
14614 }
14615
14616 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14617 int callingUser) {
14618 HashMap map = mServicesByIntentPerUser.get(callingUser);
14619 if (map == null) {
14620 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14621 mServicesByIntentPerUser.put(callingUser, map);
14622 }
14623 return map;
14624 }
14625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014626}