blob: e5b786a2c9a9a0ca3e67ecd635b3bb0d69bc0500 [file] [log] [blame]
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001/*
2 * Copyright (C) 2012 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
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
Christopher Tatef278f122015-04-22 13:12:01 -070021import java.text.SimpleDateFormat;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080022import java.util.ArrayList;
Christopher Tatef278f122015-04-22 13:12:01 -070023import java.util.Date;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -070024import java.util.Set;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080025
Dianne Hackborn7d19e022012-08-07 19:12:33 -070026import android.app.ActivityManager;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080027import android.app.AppGlobals;
Dianne Hackbornf51f6122013-02-04 18:23:34 -080028import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070029import android.app.BroadcastOptions;
Svet Ganov9c165d72015-12-01 19:52:26 -080030import android.app.PendingIntent;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080031import android.content.ComponentName;
32import android.content.IIntentReceiver;
Svet Ganov9c165d72015-12-01 19:52:26 -080033import android.content.IIntentSender;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080034import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080035import android.content.IntentSender;
Dianne Hackborn7d19e022012-08-07 19:12:33 -070036import android.content.pm.ActivityInfo;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
39import android.os.Bundle;
40import android.os.Handler;
41import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080042import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080043import android.os.Message;
44import android.os.Process;
45import android.os.RemoteException;
46import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080048import android.util.EventLog;
49import android.util.Slog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070050import android.util.TimeUtils;
Dianne Hackborna750a632015-06-16 17:18:23 -070051import com.android.server.DeviceIdleController;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080052
Wale Ogunwaled57969f2014-11-15 19:37:29 -080053import static com.android.server.am.ActivityManagerDebugConfig.*;
54
Dianne Hackborn40c8db52012-02-10 18:59:48 -080055/**
56 * BROADCASTS
57 *
58 * We keep two broadcast queues and associated bookkeeping, one for those at
59 * foreground priority, and one for normal (background-priority) broadcasts.
60 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070061public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070062 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080063 private static final String TAG_MU = TAG + POSTFIX_MU;
64 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080065
Dianne Hackborn4c51de42013-10-16 23:34:35 -070066 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070067 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070068 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080069
70 final ActivityManagerService mService;
71
72 /**
73 * Recognizable moniker for this queue
74 */
75 final String mQueueName;
76
77 /**
78 * Timeout period for this queue's broadcasts
79 */
80 final long mTimeoutPeriod;
81
82 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070083 * If true, we can delay broadcasts while waiting services to finish in the previous
84 * receiver's process.
85 */
86 final boolean mDelayBehindServices;
87
88 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080089 * Lists of all active broadcasts that are to be executed immediately
90 * (without waiting for another broadcast to finish). Currently this only
91 * contains broadcasts to registered receivers, to avoid spinning up
92 * a bunch of processes to execute IntentReceiver components. Background-
93 * and foreground-priority broadcasts are queued separately.
94 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070095 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070096
Dianne Hackborn40c8db52012-02-10 18:59:48 -080097 /**
98 * List of all active broadcasts that are to be executed one at a time.
99 * The object at the top of the list is the currently activity broadcasts;
100 * those after it are waiting for the top to finish. As with parallel
101 * broadcasts, separate background- and foreground-priority queues are
102 * maintained.
103 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700104 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800105
106 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700107 * Historical data of past broadcasts, for debugging. This is a ring buffer
108 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800109 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700110 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700111 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800112
113 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700114 * Summary of historical data of past broadcasts, for debugging. This is a
115 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700116 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700117 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700118 int mSummaryHistoryNext = 0;
119
120 /**
121 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
122 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
123 * clock time, not elapsed.
124 */
125 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
126 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
127 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700128
129 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800130 * Set when we current have a BROADCAST_INTENT_MSG in flight.
131 */
132 boolean mBroadcastsScheduled = false;
133
134 /**
135 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
136 */
137 boolean mPendingBroadcastTimeoutMessage;
138
139 /**
140 * Intent broadcasts that we have tried to start, but are
141 * waiting for the application's process to be created. We only
142 * need one per scheduling class (instead of a list) because we always
143 * process broadcasts one at a time, so no others can be started while
144 * waiting for this one.
145 */
146 BroadcastRecord mPendingBroadcast = null;
147
148 /**
149 * The receiver index that is pending, to restart the broadcast if needed.
150 */
151 int mPendingBroadcastRecvIndex;
152
153 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
154 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700155 static final int SCHEDULE_TEMP_WHITELIST_MSG
156 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800157
Jeff Brown6f357d32014-01-15 20:40:55 -0800158 final BroadcastHandler mHandler;
159
160 private final class BroadcastHandler extends Handler {
161 public BroadcastHandler(Looper looper) {
162 super(looper, null, true);
163 }
164
165 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800166 public void handleMessage(Message msg) {
167 switch (msg.what) {
168 case BROADCAST_INTENT_MSG: {
169 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800170 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800171 processNextBroadcast(true);
172 } break;
173 case BROADCAST_TIMEOUT_MSG: {
174 synchronized (mService) {
175 broadcastTimeoutLocked(true);
176 }
177 } break;
Dianne Hackborna750a632015-06-16 17:18:23 -0700178 case SCHEDULE_TEMP_WHITELIST_MSG: {
179 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
180 if (dic != null) {
181 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700182 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700183 }
184 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800185 }
186 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800187 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800188
189 private final class AppNotResponding implements Runnable {
190 private final ProcessRecord mApp;
191 private final String mAnnotation;
192
193 public AppNotResponding(ProcessRecord app, String annotation) {
194 mApp = app;
195 mAnnotation = annotation;
196 }
197
198 @Override
199 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100200 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800201 }
202 }
203
Jeff Brown6f357d32014-01-15 20:40:55 -0800204 BroadcastQueue(ActivityManagerService service, Handler handler,
205 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800206 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800207 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800208 mQueueName = name;
209 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700210 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800211 }
212
213 public boolean isPendingBroadcastProcessLocked(int pid) {
214 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
215 }
216
217 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
218 mParallelBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700219 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800220 }
221
222 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
223 mOrderedBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700224 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800225 }
226
227 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700228 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700229 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn448489a2016-09-29 10:55:10 -0700230 final Intent curIntent = mParallelBroadcasts.get(i).intent;
Nimrod Gileadif2122f52016-10-06 19:25:11 +0100231 if (intent.filterEquals(curIntent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800232 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800233 "***** DROPPING PARALLEL ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700234 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800235 mParallelBroadcasts.set(i, r);
236 return true;
237 }
238 }
239 return false;
240 }
241
242 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700243 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700244 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700245 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800246 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800247 "***** DROPPING ORDERED ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700248 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800249 mOrderedBroadcasts.set(i, r);
250 return true;
251 }
252 }
253 return false;
254 }
255
256 private final void processCurBroadcastLocked(BroadcastRecord r,
257 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800258 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800259 "Process cur broadcast " + r + " for app " + app);
260 if (app.thread == null) {
261 throw new RemoteException();
262 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700263 if (app.inFullBackup) {
264 skipReceiverLocked(r);
265 return;
266 }
267
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800268 r.receiver = app.thread.asBinder();
269 r.curApp = app;
yangzhenyud509bc92016-08-31 18:26:46 +0800270 app.curReceivers.add(r);
Dianne Hackborna413dc02013-07-12 12:02:55 -0700271 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700272 mService.updateLruProcessLocked(app, false, null);
273 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800274
275 // Tell the application to launch this receiver.
276 r.intent.setComponent(r.curComponent);
277
278 boolean started = false;
279 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800280 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 "Delivering to component " + r.curComponent
282 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700283 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
284 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800285 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
286 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700287 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
288 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800289 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800290 "Process cur broadcast " + r + " DELIVERED for app " + app);
291 started = true;
292 } finally {
293 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800294 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 "Process cur broadcast " + r + ": NOT STARTED!");
296 r.receiver = null;
297 r.curApp = null;
yangzhenyud509bc92016-08-31 18:26:46 +0800298 app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800299 }
300 }
301 }
302
303 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
304 boolean didSomething = false;
305 final BroadcastRecord br = mPendingBroadcast;
306 if (br != null && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700307 if (br.curApp != app) {
308 Slog.e(TAG, "App mismatch when sending pending broadcast to "
309 + app.processName + ", intended target is " + br.curApp.processName);
310 return false;
311 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800312 try {
313 mPendingBroadcast = null;
314 processCurBroadcastLocked(br, app);
315 didSomething = true;
316 } catch (Exception e) {
317 Slog.w(TAG, "Exception in new application when starting receiver "
318 + br.curComponent.flattenToShortString(), e);
319 logBroadcastReceiverDiscardLocked(br);
320 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700321 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800322 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700323 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800324 br.state = BroadcastRecord.IDLE;
325 throw new RuntimeException(e.getMessage());
326 }
327 }
328 return didSomething;
329 }
330
331 public void skipPendingBroadcastLocked(int pid) {
332 final BroadcastRecord br = mPendingBroadcast;
333 if (br != null && br.curApp.pid == pid) {
334 br.state = BroadcastRecord.IDLE;
335 br.nextReceiver = mPendingBroadcastRecvIndex;
336 mPendingBroadcast = null;
337 scheduleBroadcastsLocked();
338 }
339 }
340
341 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700342 BroadcastRecord r = null;
343 if (mOrderedBroadcasts.size() > 0) {
344 BroadcastRecord br = mOrderedBroadcasts.get(0);
345 if (br.curApp == app) {
346 r = br;
347 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800348 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800349 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800350 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800351 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800352 r = mPendingBroadcast;
353 }
354
355 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700356 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800357 }
358 }
359
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700360 private void skipReceiverLocked(BroadcastRecord r) {
361 logBroadcastReceiverDiscardLocked(r);
362 finishReceiverLocked(r, r.resultCode, r.resultData,
363 r.resultExtras, r.resultAbort, false);
364 scheduleBroadcastsLocked();
365 }
366
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800367 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800368 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800369 + mQueueName + "]: current="
370 + mBroadcastsScheduled);
371
372 if (mBroadcastsScheduled) {
373 return;
374 }
375 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
376 mBroadcastsScheduled = true;
377 }
378
379 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
380 if (mOrderedBroadcasts.size() > 0) {
381 final BroadcastRecord r = mOrderedBroadcasts.get(0);
382 if (r != null && r.receiver == receiver) {
383 return r;
384 }
385 }
386 return null;
387 }
388
389 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700390 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
391 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700392 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800393 r.state = BroadcastRecord.IDLE;
394 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700395 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800396 }
397 r.receiver = null;
398 r.intent.setComponent(null);
yangzhenyud509bc92016-08-31 18:26:46 +0800399 if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
400 r.curApp.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800401 }
402 if (r.curFilter != null) {
403 r.curFilter.receiverList.curBroadcast = null;
404 }
405 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800406 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700407 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800408 mPendingBroadcast = null;
409
410 r.resultCode = resultCode;
411 r.resultData = resultData;
412 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700413 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
414 r.resultAbort = resultAbort;
415 } else {
416 r.resultAbort = false;
417 }
418
419 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
420 && r.queue.mOrderedBroadcasts.size() > 0
421 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700422 ActivityInfo nextReceiver;
423 if (r.nextReceiver < r.receivers.size()) {
424 Object obj = r.receivers.get(r.nextReceiver);
425 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
426 } else {
427 nextReceiver = null;
428 }
429 // Don't do this if the next receive is in the same process as the current one.
430 if (receiver == null || nextReceiver == null
431 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
432 || !receiver.processName.equals(nextReceiver.processName)) {
433 // In this case, we are ready to process the next receiver for the current broadcast,
434 // but are on a queue that would like to wait for services to finish before moving
435 // on. If there are background services currently starting, then we will go into a
436 // special state where we hold off on continuing this broadcast until they are done.
Dianne Hackbornad51be92016-08-16 16:27:36 -0700437 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800438 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700439 r.state = BroadcastRecord.WAITING_SERVICES;
440 return false;
441 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700442 }
443 }
444
445 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800446
447 // We will process the next receiver right now if this is finishing
448 // an app receiver (which is always asynchronous) or after we have
449 // come back from calling a receiver.
450 return state == BroadcastRecord.APP_RECEIVE
451 || state == BroadcastRecord.CALL_DONE_RECEIVE;
452 }
453
Dianne Hackborn6285a322013-09-18 12:09:47 -0700454 public void backgroundServicesFinishedLocked(int userId) {
455 if (mOrderedBroadcasts.size() > 0) {
456 BroadcastRecord br = mOrderedBroadcasts.get(0);
457 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800458 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700459 br.curComponent = null;
460 br.state = BroadcastRecord.IDLE;
461 processNextBroadcast(false);
462 }
463 }
464 }
465
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700466 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800467 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700468 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800469 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000470 if (app != null) {
471 if (app.thread != null) {
472 // If we have an app thread, do the call through that so it is
473 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700474 try {
475 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
476 data, extras, ordered, sticky, sendingUser, app.repProcState);
477 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
478 // DeadObjectException when the process isn't actually dead.
479 //} catch (DeadObjectException ex) {
480 // Failed to call into the process. It's dying so just let it die and move on.
481 // throw ex;
482 } catch (RemoteException ex) {
483 // Failed to call into the process. It's either dying or wedged. Kill it gently.
484 synchronized (mService) {
485 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
486 + " (pid " + app.pid + "). Crashing it.");
487 app.scheduleCrash("can't deliver broadcast");
488 }
489 throw ex;
490 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000491 } else {
492 // Application has died. Receiver doesn't exist.
493 throw new RemoteException("app.thread must not be null");
494 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800495 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700496 receiver.performReceive(intent, resultCode, data, extras, ordered,
497 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800498 }
499 }
500
Svet Ganov99b60432015-06-27 13:15:22 -0700501 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800502 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800503 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700504 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800505 int perm = mService.checkComponentPermission(filter.requiredPermission,
506 r.callingPid, r.callingUid, -1, true);
507 if (perm != PackageManager.PERMISSION_GRANTED) {
508 Slog.w(TAG, "Permission Denial: broadcasting "
509 + r.intent.toString()
510 + " from " + r.callerPackage + " (pid="
511 + r.callingPid + ", uid=" + r.callingUid + ")"
512 + " requires " + filter.requiredPermission
513 + " due to registered receiver " + filter);
514 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700515 } else {
516 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
517 if (opCode != AppOpsManager.OP_NONE
518 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
519 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
520 Slog.w(TAG, "Appop Denial: broadcasting "
521 + r.intent.toString()
522 + " from " + r.callerPackage + " (pid="
523 + r.callingPid + ", uid=" + r.callingUid + ")"
524 + " requires appop " + AppOpsManager.permissionToOp(
525 filter.requiredPermission)
526 + " due to registered receiver " + filter);
527 skip = true;
528 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800529 }
530 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700531 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
532 for (int i = 0; i < r.requiredPermissions.length; i++) {
533 String requiredPermission = r.requiredPermissions[i];
534 int perm = mService.checkComponentPermission(requiredPermission,
535 filter.receiverList.pid, filter.receiverList.uid, -1, true);
536 if (perm != PackageManager.PERMISSION_GRANTED) {
537 Slog.w(TAG, "Permission Denial: receiving "
538 + r.intent.toString()
539 + " to " + filter.receiverList.app
540 + " (pid=" + filter.receiverList.pid
541 + ", uid=" + filter.receiverList.uid + ")"
542 + " requires " + requiredPermission
543 + " due to sender " + r.callerPackage
544 + " (uid " + r.callingUid + ")");
545 skip = true;
546 break;
547 }
548 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700549 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700550 && mService.mAppOpsService.noteOperation(appOp,
551 filter.receiverList.uid, filter.packageName)
552 != AppOpsManager.MODE_ALLOWED) {
553 Slog.w(TAG, "Appop Denial: receiving "
554 + r.intent.toString()
555 + " to " + filter.receiverList.app
556 + " (pid=" + filter.receiverList.pid
557 + ", uid=" + filter.receiverList.uid + ")"
558 + " requires appop " + AppOpsManager.permissionToOp(
559 requiredPermission)
560 + " due to sender " + r.callerPackage
561 + " (uid " + r.callingUid + ")");
562 skip = true;
563 break;
564 }
565 }
566 }
567 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
568 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000569 filter.receiverList.pid, filter.receiverList.uid, -1, true);
570 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700571 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000572 + r.intent.toString()
573 + " to " + filter.receiverList.app
574 + " (pid=" + filter.receiverList.pid
575 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000576 + " due to sender " + r.callerPackage
577 + " (uid " + r.callingUid + ")");
578 skip = true;
579 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700580 }
581 if (!skip && r.appOp != AppOpsManager.OP_NONE
582 && mService.mAppOpsService.noteOperation(r.appOp,
583 filter.receiverList.uid, filter.packageName)
584 != AppOpsManager.MODE_ALLOWED) {
585 Slog.w(TAG, "Appop Denial: receiving "
586 + r.intent.toString()
587 + " to " + filter.receiverList.app
588 + " (pid=" + filter.receiverList.pid
589 + ", uid=" + filter.receiverList.uid + ")"
590 + " requires appop " + AppOpsManager.opToName(r.appOp)
591 + " due to sender " + r.callerPackage
592 + " (uid " + r.callingUid + ")");
593 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700594 }
Svet Ganov99b60432015-06-27 13:15:22 -0700595
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700596 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
597 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800598 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700599 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800600
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800601 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700602 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
603 + " to " + filter.receiverList + ": process crashing");
604 skip = true;
605 }
606
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800607 if (skip) {
608 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
609 return;
610 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800611
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800612 // If permissions need a review before any of the app components can run, we drop
613 // the broadcast and if the calling app is in the foreground and the broadcast is
614 // explicit we launch the review UI passing it a pending intent to send the skipped
615 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -0700616 if (mService.mPermissionReviewRequired) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800617 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
618 filter.owningUserId)) {
619 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
620 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800621 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800622 }
623
624 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
625
626 // If this is not being sent as an ordered broadcast, then we
627 // don't want to touch the fields that keep track of the current
628 // state of ordered broadcasts.
629 if (ordered) {
630 r.receiver = filter.receiverList.receiver.asBinder();
631 r.curFilter = filter;
632 filter.receiverList.curBroadcast = r;
633 r.state = BroadcastRecord.CALL_IN_RECEIVE;
634 if (filter.receiverList.app != null) {
635 // Bump hosting application to no longer be in background
636 // scheduling class. Note that we can't do that if there
637 // isn't an app... but we can only be in that case for
638 // things that directly call the IActivityManager API, which
639 // are already core system stuff so don't matter for this.
640 r.curApp = filter.receiverList.app;
yangzhenyud509bc92016-08-31 18:26:46 +0800641 filter.receiverList.app.curReceivers.add(r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800642 mService.updateOomAdjLocked(r.curApp);
643 }
644 }
645 try {
646 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
647 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700648 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
649 // Skip delivery if full backup in progress
650 // If it's an ordered broadcast, we need to continue to the next receiver.
651 if (ordered) {
652 skipReceiverLocked(r);
653 }
654 } else {
655 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
656 new Intent(r.intent), r.resultCode, r.resultData,
657 r.resultExtras, r.ordered, r.initialSticky, r.userId);
658 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800659 if (ordered) {
660 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
661 }
662 } catch (RemoteException e) {
663 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
664 if (ordered) {
665 r.receiver = null;
666 r.curFilter = null;
667 filter.receiverList.curBroadcast = null;
668 if (filter.receiverList.app != null) {
yangzhenyud509bc92016-08-31 18:26:46 +0800669 filter.receiverList.app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800670 }
671 }
672 }
673 }
674
Svet Ganov9c165d72015-12-01 19:52:26 -0800675 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
676 BroadcastRecord receiverRecord, String receivingPackageName,
677 final int receivingUserId) {
678 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
679 receivingPackageName, receivingUserId)) {
680 return true;
681 }
682
683 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800684 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800685 : true;
686
687 // Show a permission review UI only for explicit broadcast from a foreground app
688 if (callerForeground && receiverRecord.intent.getComponent() != null) {
689 IIntentSender target = mService.getIntentSenderLocked(
690 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
691 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
692 new Intent[]{receiverRecord.intent},
693 new String[]{receiverRecord.intent.resolveType(mService.mContext
694 .getContentResolver())},
695 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
696 | PendingIntent.FLAG_IMMUTABLE, null);
697
698 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
699 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
700 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
701 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
702 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
703
704 if (DEBUG_PERMISSIONS_REVIEW) {
705 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
706 + receivingPackageName);
707 }
708
709 mHandler.post(new Runnable() {
710 @Override
711 public void run() {
712 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
713 }
714 });
715 } else {
716 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
717 + receivingPackageName + " requires a permissions review");
718 }
719
720 return false;
721 }
722
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700723 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700724 if (duration > Integer.MAX_VALUE) {
725 duration = Integer.MAX_VALUE;
726 }
727 // XXX ideally we should pause the broadcast until everything behind this is done,
728 // or else we will likely start dispatching the broadcast before we have opened
729 // access to the app (there is a lot of asynchronicity behind this). It is probably
730 // not that big a deal, however, because the main purpose here is to allow apps
731 // to hold wake locks, and they will be able to acquire their wake lock immediately
732 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700733 StringBuilder b = new StringBuilder();
734 b.append("broadcast:");
735 UserHandle.formatUid(b, r.callingUid);
736 b.append(":");
737 if (r.intent.getAction() != null) {
738 b.append(r.intent.getAction());
739 } else if (r.intent.getComponent() != null) {
740 b.append(r.intent.getComponent().flattenToShortString());
741 } else if (r.intent.getData() != null) {
742 b.append(r.intent.getData());
743 }
744 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
745 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700746 }
747
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800748 final void processNextBroadcast(boolean fromMsg) {
749 synchronized(mService) {
750 BroadcastRecord r;
751
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800752 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800753 + mQueueName + "]: "
754 + mParallelBroadcasts.size() + " broadcasts, "
755 + mOrderedBroadcasts.size() + " ordered broadcasts");
756
757 mService.updateCpuStats();
758
759 if (fromMsg) {
760 mBroadcastsScheduled = false;
761 }
762
763 // First, deliver any non-serialized broadcasts right away.
764 while (mParallelBroadcasts.size() > 0) {
765 r = mParallelBroadcasts.remove(0);
766 r.dispatchTime = SystemClock.uptimeMillis();
767 r.dispatchClockTime = System.currentTimeMillis();
768 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800769 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800770 + mQueueName + "] " + r);
771 for (int i=0; i<N; i++) {
772 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800773 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800774 "Delivering non-ordered on [" + mQueueName + "] to registered "
775 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800776 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800777 }
778 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800779 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800780 + mQueueName + "] " + r);
781 }
782
783 // Now take care of the next serialized one...
784
785 // If we are waiting for a process to come up to handle the next
786 // broadcast, then do nothing at this point. Just in case, we
787 // check that the process we're waiting for still exists.
788 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700789 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
790 "processNextBroadcast [" + mQueueName + "]: waiting for "
791 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800792
793 boolean isDead;
794 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700795 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
796 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800797 }
798 if (!isDead) {
799 // It's still alive, so keep waiting
800 return;
801 } else {
802 Slog.w(TAG, "pending app ["
803 + mQueueName + "]" + mPendingBroadcast.curApp
804 + " died before responding to broadcast");
805 mPendingBroadcast.state = BroadcastRecord.IDLE;
806 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
807 mPendingBroadcast = null;
808 }
809 }
810
811 boolean looped = false;
812
813 do {
814 if (mOrderedBroadcasts.size() == 0) {
815 // No more broadcasts pending, so all done!
816 mService.scheduleAppGcsLocked();
817 if (looped) {
818 // If we had finished the last ordered broadcast, then
819 // make sure all processes have correct oom and sched
820 // adjustments.
821 mService.updateOomAdjLocked();
822 }
823 return;
824 }
825 r = mOrderedBroadcasts.get(0);
826 boolean forceReceive = false;
827
828 // Ensure that even if something goes awry with the timeout
829 // detection, we catch "hung" broadcasts here, discard them,
830 // and continue to make progress.
831 //
832 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
833 // receivers don't get executed with timeouts. They're intended for
834 // one time heavy lifting after system upgrades and can take
835 // significant amounts of time.
836 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
837 if (mService.mProcessesReady && r.dispatchTime > 0) {
838 long now = SystemClock.uptimeMillis();
839 if ((numReceivers > 0) &&
840 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
841 Slog.w(TAG, "Hung broadcast ["
842 + mQueueName + "] discarded after timeout failure:"
843 + " now=" + now
844 + " dispatchTime=" + r.dispatchTime
845 + " startTime=" + r.receiverTime
846 + " intent=" + r.intent
847 + " numReceivers=" + numReceivers
848 + " nextReceiver=" + r.nextReceiver
849 + " state=" + r.state);
850 broadcastTimeoutLocked(false); // forcibly finish this broadcast
851 forceReceive = true;
852 r.state = BroadcastRecord.IDLE;
853 }
854 }
855
856 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800857 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800858 "processNextBroadcast("
859 + mQueueName + ") called when not idle (state="
860 + r.state + ")");
861 return;
862 }
863
864 if (r.receivers == null || r.nextReceiver >= numReceivers
865 || r.resultAbort || forceReceive) {
866 // No more receivers for this broadcast! Send the final
867 // result if requested...
868 if (r.resultTo != null) {
869 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800870 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800871 "Finishing broadcast [" + mQueueName + "] "
872 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800873 performReceiveLocked(r.callerApp, r.resultTo,
874 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700875 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800876 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700877 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800878 r.resultTo = null;
879 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000880 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800881 Slog.w(TAG, "Failure ["
882 + mQueueName + "] sending broadcast result of "
883 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700884
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800885 }
886 }
887
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800888 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800889 cancelBroadcastTimeoutLocked();
890
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700891 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
892 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800893
894 // ... and on to the next...
895 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700896 if (r.intent.getComponent() == null && r.intent.getPackage() == null
897 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
898 // This was an implicit broadcast... let's record it for posterity.
899 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
900 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
901 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800902 mOrderedBroadcasts.remove(0);
903 r = null;
904 looped = true;
905 continue;
906 }
907 } while (r == null);
908
909 // Get the next receiver...
910 int recIdx = r.nextReceiver++;
911
912 // Keep track of when this receiver started, and make sure there
913 // is a timeout message pending to kill it if need be.
914 r.receiverTime = SystemClock.uptimeMillis();
915 if (recIdx == 0) {
916 r.dispatchTime = r.receiverTime;
917 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800918 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800919 + mQueueName + "] " + r);
920 }
921 if (! mPendingBroadcastTimeoutMessage) {
922 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800923 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800924 "Submitting BROADCAST_TIMEOUT_MSG ["
925 + mQueueName + "] for " + r + " at " + timeoutTime);
926 setBroadcastTimeoutLocked(timeoutTime);
927 }
928
Dianne Hackborna750a632015-06-16 17:18:23 -0700929 final BroadcastOptions brOptions = r.options;
930 final Object nextReceiver = r.receivers.get(recIdx);
931
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800932 if (nextReceiver instanceof BroadcastFilter) {
933 // Simple case: this is a registered receiver who gets
934 // a direct call.
935 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800936 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800937 "Delivering ordered ["
938 + mQueueName + "] to registered "
939 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800940 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800941 if (r.receiver == null || !r.ordered) {
942 // The receiver has already finished, so schedule to
943 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800944 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800945 + mQueueName + "]: ordered="
946 + r.ordered + " receiver=" + r.receiver);
947 r.state = BroadcastRecord.IDLE;
948 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700949 } else {
950 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
951 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700952 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700953 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800954 }
955 return;
956 }
957
958 // Hard case: need to instantiate the receiver, possibly
959 // starting its application process to host it.
960
961 ResolveInfo info =
962 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700963 ComponentName component = new ComponentName(
964 info.activityInfo.applicationInfo.packageName,
965 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800966
967 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800968 if (brOptions != null &&
969 (info.activityInfo.applicationInfo.targetSdkVersion
970 < brOptions.getMinManifestReceiverApiLevel() ||
971 info.activityInfo.applicationInfo.targetSdkVersion
972 > brOptions.getMaxManifestReceiverApiLevel())) {
973 skip = true;
974 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800975 int perm = mService.checkComponentPermission(info.activityInfo.permission,
976 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
977 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800978 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800979 if (!info.activityInfo.exported) {
980 Slog.w(TAG, "Permission Denial: broadcasting "
981 + r.intent.toString()
982 + " from " + r.callerPackage + " (pid=" + r.callingPid
983 + ", uid=" + r.callingUid + ")"
984 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700985 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800986 } else {
987 Slog.w(TAG, "Permission Denial: broadcasting "
988 + r.intent.toString()
989 + " from " + r.callerPackage + " (pid=" + r.callingPid
990 + ", uid=" + r.callingUid + ")"
991 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700992 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800993 }
994 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800995 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -0700996 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
997 if (opCode != AppOpsManager.OP_NONE
998 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
999 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1000 Slog.w(TAG, "Appop Denial: broadcasting "
1001 + r.intent.toString()
1002 + " from " + r.callerPackage + " (pid="
1003 + r.callingPid + ", uid=" + r.callingUid + ")"
1004 + " requires appop " + AppOpsManager.permissionToOp(
1005 info.activityInfo.permission)
1006 + " due to registered receiver "
1007 + component.flattenToShortString());
1008 skip = true;
1009 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001010 }
Svet Ganov99b60432015-06-27 13:15:22 -07001011 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001012 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1013 for (int i = 0; i < r.requiredPermissions.length; i++) {
1014 String requiredPermission = r.requiredPermissions[i];
1015 try {
1016 perm = AppGlobals.getPackageManager().
1017 checkPermission(requiredPermission,
1018 info.activityInfo.applicationInfo.packageName,
1019 UserHandle
1020 .getUserId(info.activityInfo.applicationInfo.uid));
1021 } catch (RemoteException e) {
1022 perm = PackageManager.PERMISSION_DENIED;
1023 }
1024 if (perm != PackageManager.PERMISSION_GRANTED) {
1025 Slog.w(TAG, "Permission Denial: receiving "
1026 + r.intent + " to "
1027 + component.flattenToShortString()
1028 + " requires " + requiredPermission
1029 + " due to sender " + r.callerPackage
1030 + " (uid " + r.callingUid + ")");
1031 skip = true;
1032 break;
1033 }
1034 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1035 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1036 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001037 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001038 != AppOpsManager.MODE_ALLOWED) {
1039 Slog.w(TAG, "Appop Denial: receiving "
1040 + r.intent + " to "
1041 + component.flattenToShortString()
1042 + " requires appop " + AppOpsManager.permissionToOp(
1043 requiredPermission)
1044 + " due to sender " + r.callerPackage
1045 + " (uid " + r.callingUid + ")");
1046 skip = true;
1047 break;
1048 }
1049 }
1050 }
1051 if (!skip && r.appOp != AppOpsManager.OP_NONE
1052 && mService.mAppOpsService.noteOperation(r.appOp,
1053 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1054 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001055 Slog.w(TAG, "Appop Denial: receiving "
1056 + r.intent + " to "
1057 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001058 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001059 + " due to sender " + r.callerPackage
1060 + " (uid " + r.callingUid + ")");
1061 skip = true;
1062 }
Ben Gruver49660c72013-08-06 19:54:08 -07001063 if (!skip) {
1064 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1065 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1066 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001067 boolean isSingleton = false;
1068 try {
1069 isSingleton = mService.isSingleton(info.activityInfo.processName,
1070 info.activityInfo.applicationInfo,
1071 info.activityInfo.name, info.activityInfo.flags);
1072 } catch (SecurityException e) {
1073 Slog.w(TAG, e.getMessage());
1074 skip = true;
1075 }
1076 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1077 if (ActivityManager.checkUidPermission(
1078 android.Manifest.permission.INTERACT_ACROSS_USERS,
1079 info.activityInfo.applicationInfo.uid)
1080 != PackageManager.PERMISSION_GRANTED) {
1081 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1082 + " requests FLAG_SINGLE_USER, but app does not hold "
1083 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1084 skip = true;
1085 }
1086 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001087 if (!skip) {
1088 r.manifestCount++;
1089 } else {
1090 r.manifestSkipCount++;
1091 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001092 if (r.curApp != null && r.curApp.crashing) {
1093 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001094 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1095 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001096 skip = true;
1097 }
Christopher Tateba629da2013-11-13 17:42:28 -08001098 if (!skip) {
1099 boolean isAvailable = false;
1100 try {
1101 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1102 info.activityInfo.packageName,
1103 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1104 } catch (Exception e) {
1105 // all such failures mean we skip this receiver
1106 Slog.w(TAG, "Exception getting recipient info for "
1107 + info.activityInfo.packageName, e);
1108 }
1109 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001110 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1111 "Skipping delivery to " + info.activityInfo.packageName + " / "
1112 + info.activityInfo.applicationInfo.uid
1113 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001114 skip = true;
1115 }
1116 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001117
Svet Ganov9c165d72015-12-01 19:52:26 -08001118 // If permissions need a review before any of the app components can run, we drop
1119 // the broadcast and if the calling app is in the foreground and the broadcast is
1120 // explicit we launch the review UI passing it a pending intent to send the skipped
1121 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -07001122 if (mService.mPermissionReviewRequired && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001123 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1124 info.activityInfo.packageName, UserHandle.getUserId(
1125 info.activityInfo.applicationInfo.uid))) {
1126 skip = true;
1127 }
1128 }
1129
Dianne Hackborn76e80092015-12-09 14:15:34 -08001130 // This is safe to do even if we are skipping the broadcast, and we need
1131 // this information now to evaluate whether it is going to be allowed to run.
1132 final int receiverUid = info.activityInfo.applicationInfo.uid;
1133 // If it's a singleton, it needs to be the same app or a special app
1134 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1135 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1136 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1137 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001138 String targetProcess = info.activityInfo.processName;
1139 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1140 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001141
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001142 if (!skip) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001143 final int allowed = mService.getAppStartModeLocked(
1144 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1145 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001146 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1147 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001148 // completely disabled from launches, or it was not explicitly sent
1149 // to it and the app is in a state that should not receive it
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001150 // (depending on how getAppStartModeLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001151 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1152 Slog.w(TAG, "Background execution disabled: receiving "
1153 + r.intent + " to "
1154 + component.flattenToShortString());
1155 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001156 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001157 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001158 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001159 && ((r.intent.getFlags()
1160 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn7fc46d82017-02-14 15:20:06 -08001161 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1162 component.getPackageName());
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001163 Slog.w(TAG, "Background execution not allowed: receiving "
1164 + r.intent + " to "
1165 + component.flattenToShortString());
1166 skip = true;
1167 }
1168 }
1169 }
1170
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001171 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001172 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001173 "Skipping delivery of ordered [" + mQueueName + "] "
1174 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001175 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001176 r.receiver = null;
1177 r.curFilter = null;
1178 r.state = BroadcastRecord.IDLE;
1179 scheduleBroadcastsLocked();
1180 return;
1181 }
1182
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001183 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001184 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001185 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001186 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001187 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001188 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1189 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1190 + info.activityInfo.applicationInfo.uid);
1191 }
1192
Dianne Hackborna750a632015-06-16 17:18:23 -07001193 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1194 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001195 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001196 }
1197
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001198 // Broadcast is being executed, its package can't be stopped.
1199 try {
1200 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001201 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001202 } catch (RemoteException e) {
1203 } catch (IllegalArgumentException e) {
1204 Slog.w(TAG, "Failed trying to unstop package "
1205 + r.curComponent.getPackageName() + ": " + e);
1206 }
1207
1208 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001209 if (app != null && app.thread != null) {
1210 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001211 app.addPackage(info.activityInfo.packageName,
1212 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001213 processCurBroadcastLocked(r, app);
1214 return;
1215 } catch (RemoteException e) {
1216 Slog.w(TAG, "Exception when sending broadcast to "
1217 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001218 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001219 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001220 + r.curComponent + " with " + r.intent, e);
1221 // If some unexpected exception happened, just skip
1222 // this broadcast. At this point we are not in the call
1223 // from a client, so throwing an exception out from here
1224 // will crash the entire system instead of just whoever
1225 // sent the broadcast.
1226 logBroadcastReceiverDiscardLocked(r);
1227 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001228 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001229 scheduleBroadcastsLocked();
1230 // We need to reset the state if we failed to start the receiver.
1231 r.state = BroadcastRecord.IDLE;
1232 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001233 }
1234
1235 // If a dead object exception was thrown -- fall through to
1236 // restart the application.
1237 }
1238
1239 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001240 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001241 "Need to start app ["
1242 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1243 if ((r.curApp=mService.startProcessLocked(targetProcess,
1244 info.activityInfo.applicationInfo, true,
1245 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1246 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001247 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001248 == null) {
1249 // Ah, this recipient is unavailable. Finish it if necessary,
1250 // and mark the broadcast record as ready for the next.
1251 Slog.w(TAG, "Unable to launch app "
1252 + info.activityInfo.applicationInfo.packageName + "/"
1253 + info.activityInfo.applicationInfo.uid + " for broadcast "
1254 + r.intent + ": process is bad");
1255 logBroadcastReceiverDiscardLocked(r);
1256 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001257 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001258 scheduleBroadcastsLocked();
1259 r.state = BroadcastRecord.IDLE;
1260 return;
1261 }
1262
1263 mPendingBroadcast = r;
1264 mPendingBroadcastRecvIndex = recIdx;
1265 }
1266 }
1267
1268 final void setBroadcastTimeoutLocked(long timeoutTime) {
1269 if (! mPendingBroadcastTimeoutMessage) {
1270 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1271 mHandler.sendMessageAtTime(msg, timeoutTime);
1272 mPendingBroadcastTimeoutMessage = true;
1273 }
1274 }
1275
1276 final void cancelBroadcastTimeoutLocked() {
1277 if (mPendingBroadcastTimeoutMessage) {
1278 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1279 mPendingBroadcastTimeoutMessage = false;
1280 }
1281 }
1282
1283 final void broadcastTimeoutLocked(boolean fromMsg) {
1284 if (fromMsg) {
1285 mPendingBroadcastTimeoutMessage = false;
1286 }
1287
1288 if (mOrderedBroadcasts.size() == 0) {
1289 return;
1290 }
1291
1292 long now = SystemClock.uptimeMillis();
1293 BroadcastRecord r = mOrderedBroadcasts.get(0);
1294 if (fromMsg) {
1295 if (mService.mDidDexOpt) {
1296 // Delay timeouts until dexopt finishes.
1297 mService.mDidDexOpt = false;
1298 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1299 setBroadcastTimeoutLocked(timeoutTime);
1300 return;
1301 }
1302 if (!mService.mProcessesReady) {
1303 // Only process broadcast timeouts if the system is ready. That way
1304 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1305 // to do heavy lifting for system up.
1306 return;
1307 }
1308
1309 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1310 if (timeoutTime > now) {
1311 // We can observe premature timeouts because we do not cancel and reset the
1312 // broadcast timeout message after each receiver finishes. Instead, we set up
1313 // an initial timeout then kick it down the road a little further as needed
1314 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001315 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001316 "Premature timeout ["
1317 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1318 + timeoutTime);
1319 setBroadcastTimeoutLocked(timeoutTime);
1320 return;
1321 }
1322 }
1323
Dianne Hackborn6285a322013-09-18 12:09:47 -07001324 BroadcastRecord br = mOrderedBroadcasts.get(0);
1325 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1326 // In this case the broadcast had already finished, but we had decided to wait
1327 // for started services to finish as well before going on. So if we have actually
1328 // waited long enough time timeout the broadcast, let's give up on the whole thing
1329 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001330 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001331 ? br.curComponent.flattenToShortString() : "(null)"));
1332 br.curComponent = null;
1333 br.state = BroadcastRecord.IDLE;
1334 processNextBroadcast(false);
1335 return;
1336 }
1337
1338 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001339 + ", started " + (now - r.receiverTime) + "ms ago");
1340 r.receiverTime = now;
1341 r.anrCount++;
1342
1343 // Current receiver has passed its expiration date.
1344 if (r.nextReceiver <= 0) {
1345 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1346 return;
1347 }
1348
1349 ProcessRecord app = null;
1350 String anrMessage = null;
1351
1352 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001353 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001354 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1355 logBroadcastReceiverDiscardLocked(r);
1356 if (curReceiver instanceof BroadcastFilter) {
1357 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1358 if (bf.receiverList.pid != 0
1359 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1360 synchronized (mService.mPidsSelfLocked) {
1361 app = mService.mPidsSelfLocked.get(
1362 bf.receiverList.pid);
1363 }
1364 }
1365 } else {
1366 app = r.curApp;
1367 }
1368
1369 if (app != null) {
1370 anrMessage = "Broadcast of " + r.intent.toString();
1371 }
1372
1373 if (mPendingBroadcast == r) {
1374 mPendingBroadcast = null;
1375 }
1376
1377 // Move on to the next receiver.
1378 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001379 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001380 scheduleBroadcastsLocked();
1381
1382 if (anrMessage != null) {
1383 // Post the ANR to the handler since we do not want to process ANRs while
1384 // potentially holding our lock.
1385 mHandler.post(new AppNotResponding(app, anrMessage));
1386 }
1387 }
1388
Christopher Tatef278f122015-04-22 13:12:01 -07001389 private final int ringAdvance(int x, final int increment, final int ringSize) {
1390 x += increment;
1391 if (x < 0) return (ringSize - 1);
1392 else if (x >= ringSize) return 0;
1393 else return x;
1394 }
1395
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001396 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1397 if (r.callingUid < 0) {
1398 // This was from a registerReceiver() call; ignore it.
1399 return;
1400 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001401 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001402
1403 mBroadcastHistory[mHistoryNext] = r;
1404 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1405
1406 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1407 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1408 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1409 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1410 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001411 }
1412
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001413 boolean cleanupDisabledPackageReceiversLocked(
1414 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1415 boolean didSomething = false;
1416 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1417 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1418 packageName, filterByClasses, userId, doit);
1419 if (!doit && didSomething) {
1420 return true;
1421 }
1422 }
1423
1424 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1425 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1426 packageName, filterByClasses, userId, doit);
1427 if (!doit && didSomething) {
1428 return true;
1429 }
1430 }
1431
1432 return didSomething;
1433 }
1434
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001435 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001436 final int logIndex = r.nextReceiver - 1;
1437 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1438 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001439 if (curReceiver instanceof BroadcastFilter) {
1440 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1441 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001442 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001443 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001444 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001445 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001446 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001447 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001448 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001449 }
1450 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001451 if (logIndex < 0) Slog.w(TAG,
1452 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001453 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001454 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001455 r.intent.getAction(),
1456 r.nextReceiver,
1457 "NONE");
1458 }
1459 }
1460
1461 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1462 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001463 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001464 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1465 || mPendingBroadcast != null) {
1466 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001467 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001468 BroadcastRecord br = mParallelBroadcasts.get(i);
1469 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1470 continue;
1471 }
1472 if (!printed) {
1473 if (needSep) {
1474 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001475 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001476 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001477 printed = true;
1478 pw.println(" Active broadcasts [" + mQueueName + "]:");
1479 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001480 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001481 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001482 }
1483 printed = false;
1484 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001485 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001486 BroadcastRecord br = mOrderedBroadcasts.get(i);
1487 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1488 continue;
1489 }
1490 if (!printed) {
1491 if (needSep) {
1492 pw.println();
1493 }
1494 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001495 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001496 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1497 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001498 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001499 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001500 }
1501 if (dumpPackage == null || (mPendingBroadcast != null
1502 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1503 if (needSep) {
1504 pw.println();
1505 }
1506 pw.println(" Pending broadcast [" + mQueueName + "]:");
1507 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001508 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001509 } else {
1510 pw.println(" (null)");
1511 }
1512 needSep = true;
1513 }
1514 }
1515
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001516 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001517 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001518
1519 i = -1;
1520 int lastIndex = mHistoryNext;
1521 int ringIndex = lastIndex;
1522 do {
1523 // increasing index = more recent entry, and we want to print the most
1524 // recent first and work backwards, so we roll through the ring backwards.
1525 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1526 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001527 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001528 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001529 }
Christopher Tatef278f122015-04-22 13:12:01 -07001530
1531 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001532 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1533 continue;
1534 }
1535 if (!printed) {
1536 if (needSep) {
1537 pw.println();
1538 }
1539 needSep = true;
1540 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1541 printed = true;
1542 }
1543 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001544 pw.print(" Historical Broadcast " + mQueueName + " #");
1545 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001546 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001547 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001548 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1549 pw.print(" ");
1550 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001551 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1552 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1553 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001554 Bundle bundle = r.intent.getExtras();
1555 if (bundle != null) {
1556 pw.print(" extras: "); pw.println(bundle.toString());
1557 }
1558 }
Christopher Tatef278f122015-04-22 13:12:01 -07001559 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001560
1561 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001562 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001563 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001564 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001565 i = -1;
1566 } else {
1567 // roll over the 'i' full dumps that have already been issued
1568 for (int j = i;
1569 j > 0 && ringIndex != lastIndex;) {
1570 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1571 BroadcastRecord r = mBroadcastHistory[ringIndex];
1572 if (r == null) {
1573 continue;
1574 }
1575 j--;
1576 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001577 }
Christopher Tatef278f122015-04-22 13:12:01 -07001578 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1579 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001580 do {
1581 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1582 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001583 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001584 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001585 }
1586 if (!printed) {
1587 if (needSep) {
1588 pw.println();
1589 }
1590 needSep = true;
1591 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1592 printed = true;
1593 }
1594 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001595 pw.println(" ...");
1596 break;
1597 }
Christopher Tatef278f122015-04-22 13:12:01 -07001598 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001599 pw.print(" #"); pw.print(i); pw.print(": ");
1600 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001601 pw.print(" ");
1602 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1603 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1604 pw.print(" dispatch ");
1605 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1606 - mSummaryHistoryDispatchTime[ringIndex], pw);
1607 pw.println(" finish");
1608 pw.print(" enq=");
1609 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1610 pw.print(" disp=");
1611 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1612 pw.print(" fin=");
1613 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001614 Bundle bundle = intent.getExtras();
1615 if (bundle != null) {
1616 pw.print(" extras: "); pw.println(bundle.toString());
1617 }
Christopher Tatef278f122015-04-22 13:12:01 -07001618 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001619 }
1620
1621 return needSep;
1622 }
1623}