blob: 1222f54d15e8028a4fd21f74f92f1d3e922fea1a [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;
Svet Ganov9c165d72015-12-01 19:52:26 -080039import android.os.Build;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080040import android.os.Bundle;
Joe Onorato5869d1c2016-04-20 15:38:07 -070041import android.os.DeadObjectException;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080042import android.os.Handler;
43import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080044import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080045import android.os.Message;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080050import android.util.EventLog;
51import android.util.Slog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070052import android.util.TimeUtils;
Dianne Hackborna750a632015-06-16 17:18:23 -070053import com.android.server.DeviceIdleController;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080054
Wale Ogunwaled57969f2014-11-15 19:37:29 -080055import static com.android.server.am.ActivityManagerDebugConfig.*;
56
Dianne Hackborn40c8db52012-02-10 18:59:48 -080057/**
58 * BROADCASTS
59 *
60 * We keep two broadcast queues and associated bookkeeping, one for those at
61 * foreground priority, and one for normal (background-priority) broadcasts.
62 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070063public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070064 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080065 private static final String TAG_MU = TAG + POSTFIX_MU;
66 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080067
Dianne Hackborn4c51de42013-10-16 23:34:35 -070068 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070069 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070070 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080071
72 final ActivityManagerService mService;
73
74 /**
75 * Recognizable moniker for this queue
76 */
77 final String mQueueName;
78
79 /**
80 * Timeout period for this queue's broadcasts
81 */
82 final long mTimeoutPeriod;
83
84 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070085 * If true, we can delay broadcasts while waiting services to finish in the previous
86 * receiver's process.
87 */
88 final boolean mDelayBehindServices;
89
90 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080091 * Lists of all active broadcasts that are to be executed immediately
92 * (without waiting for another broadcast to finish). Currently this only
93 * contains broadcasts to registered receivers, to avoid spinning up
94 * a bunch of processes to execute IntentReceiver components. Background-
95 * and foreground-priority broadcasts are queued separately.
96 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070097 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070098
Dianne Hackborn40c8db52012-02-10 18:59:48 -080099 /**
100 * List of all active broadcasts that are to be executed one at a time.
101 * The object at the top of the list is the currently activity broadcasts;
102 * those after it are waiting for the top to finish. As with parallel
103 * broadcasts, separate background- and foreground-priority queues are
104 * maintained.
105 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700106 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800107
108 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700109 * Historical data of past broadcasts, for debugging. This is a ring buffer
110 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800111 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700112 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700113 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800114
115 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700116 * Summary of historical data of past broadcasts, for debugging. This is a
117 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700118 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700119 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700120 int mSummaryHistoryNext = 0;
121
122 /**
123 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
124 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
125 * clock time, not elapsed.
126 */
127 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
128 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
129 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700130
131 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800132 * Set when we current have a BROADCAST_INTENT_MSG in flight.
133 */
134 boolean mBroadcastsScheduled = false;
135
136 /**
137 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
138 */
139 boolean mPendingBroadcastTimeoutMessage;
140
141 /**
142 * Intent broadcasts that we have tried to start, but are
143 * waiting for the application's process to be created. We only
144 * need one per scheduling class (instead of a list) because we always
145 * process broadcasts one at a time, so no others can be started while
146 * waiting for this one.
147 */
148 BroadcastRecord mPendingBroadcast = null;
149
150 /**
151 * The receiver index that is pending, to restart the broadcast if needed.
152 */
153 int mPendingBroadcastRecvIndex;
154
155 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
156 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700157 static final int SCHEDULE_TEMP_WHITELIST_MSG
158 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800159
Jeff Brown6f357d32014-01-15 20:40:55 -0800160 final BroadcastHandler mHandler;
161
162 private final class BroadcastHandler extends Handler {
163 public BroadcastHandler(Looper looper) {
164 super(looper, null, true);
165 }
166
167 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800168 public void handleMessage(Message msg) {
169 switch (msg.what) {
170 case BROADCAST_INTENT_MSG: {
171 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800172 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800173 processNextBroadcast(true);
174 } break;
175 case BROADCAST_TIMEOUT_MSG: {
176 synchronized (mService) {
177 broadcastTimeoutLocked(true);
178 }
179 } break;
Dianne Hackborna750a632015-06-16 17:18:23 -0700180 case SCHEDULE_TEMP_WHITELIST_MSG: {
181 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
182 if (dic != null) {
183 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700184 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700185 }
186 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800187 }
188 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800189 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800190
191 private final class AppNotResponding implements Runnable {
192 private final ProcessRecord mApp;
193 private final String mAnnotation;
194
195 public AppNotResponding(ProcessRecord app, String annotation) {
196 mApp = app;
197 mAnnotation = annotation;
198 }
199
200 @Override
201 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100202 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800203 }
204 }
205
Jeff Brown6f357d32014-01-15 20:40:55 -0800206 BroadcastQueue(ActivityManagerService service, Handler handler,
207 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800208 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800209 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800210 mQueueName = name;
211 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700212 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800213 }
214
215 public boolean isPendingBroadcastProcessLocked(int pid) {
216 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
217 }
218
219 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
220 mParallelBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700221 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800222 }
223
224 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
225 mOrderedBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700226 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800227 }
228
229 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700230 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800231 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
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 ["
234 + mQueueName + "]: " + r.intent);
235 mParallelBroadcasts.set(i, r);
236 return true;
237 }
238 }
239 return false;
240 }
241
242 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700243 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800244 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800245 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800246 "***** DROPPING ORDERED ["
247 + mQueueName + "]: " + r.intent);
248 mOrderedBroadcasts.set(i, r);
249 return true;
250 }
251 }
252 return false;
253 }
254
255 private final void processCurBroadcastLocked(BroadcastRecord r,
256 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800257 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800258 "Process cur broadcast " + r + " for app " + app);
259 if (app.thread == null) {
260 throw new RemoteException();
261 }
262 r.receiver = app.thread.asBinder();
263 r.curApp = app;
264 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700265 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700266 mService.updateLruProcessLocked(app, false, null);
267 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800268
269 // Tell the application to launch this receiver.
270 r.intent.setComponent(r.curComponent);
271
272 boolean started = false;
273 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800274 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275 "Delivering to component " + r.curComponent
276 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700277 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
278 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800279 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
280 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700281 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
282 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800283 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800284 "Process cur broadcast " + r + " DELIVERED for app " + app);
285 started = true;
286 } finally {
287 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800288 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800289 "Process cur broadcast " + r + ": NOT STARTED!");
290 r.receiver = null;
291 r.curApp = null;
292 app.curReceiver = null;
293 }
294 }
295 }
296
297 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
298 boolean didSomething = false;
299 final BroadcastRecord br = mPendingBroadcast;
300 if (br != null && br.curApp.pid == app.pid) {
301 try {
302 mPendingBroadcast = null;
303 processCurBroadcastLocked(br, app);
304 didSomething = true;
305 } catch (Exception e) {
306 Slog.w(TAG, "Exception in new application when starting receiver "
307 + br.curComponent.flattenToShortString(), e);
308 logBroadcastReceiverDiscardLocked(br);
309 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700310 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800311 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700312 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800313 br.state = BroadcastRecord.IDLE;
314 throw new RuntimeException(e.getMessage());
315 }
316 }
317 return didSomething;
318 }
319
320 public void skipPendingBroadcastLocked(int pid) {
321 final BroadcastRecord br = mPendingBroadcast;
322 if (br != null && br.curApp.pid == pid) {
323 br.state = BroadcastRecord.IDLE;
324 br.nextReceiver = mPendingBroadcastRecvIndex;
325 mPendingBroadcast = null;
326 scheduleBroadcastsLocked();
327 }
328 }
329
330 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700331 BroadcastRecord r = null;
332 if (mOrderedBroadcasts.size() > 0) {
333 BroadcastRecord br = mOrderedBroadcasts.get(0);
334 if (br.curApp == app) {
335 r = br;
336 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800337 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800338 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800339 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800340 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800341 r = mPendingBroadcast;
342 }
343
344 if (r != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800345 logBroadcastReceiverDiscardLocked(r);
346 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700347 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800348 scheduleBroadcastsLocked();
349 }
350 }
351
352 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800353 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800354 + mQueueName + "]: current="
355 + mBroadcastsScheduled);
356
357 if (mBroadcastsScheduled) {
358 return;
359 }
360 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
361 mBroadcastsScheduled = true;
362 }
363
364 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
365 if (mOrderedBroadcasts.size() > 0) {
366 final BroadcastRecord r = mOrderedBroadcasts.get(0);
367 if (r != null && r.receiver == receiver) {
368 return r;
369 }
370 }
371 return null;
372 }
373
374 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700375 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
376 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700377 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800378 r.state = BroadcastRecord.IDLE;
379 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700380 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800381 }
382 r.receiver = null;
383 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800384 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800385 r.curApp.curReceiver = null;
386 }
387 if (r.curFilter != null) {
388 r.curFilter.receiverList.curBroadcast = null;
389 }
390 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800391 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700392 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800393 mPendingBroadcast = null;
394
395 r.resultCode = resultCode;
396 r.resultData = resultData;
397 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700398 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
399 r.resultAbort = resultAbort;
400 } else {
401 r.resultAbort = false;
402 }
403
404 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
405 && r.queue.mOrderedBroadcasts.size() > 0
406 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700407 ActivityInfo nextReceiver;
408 if (r.nextReceiver < r.receivers.size()) {
409 Object obj = r.receivers.get(r.nextReceiver);
410 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
411 } else {
412 nextReceiver = null;
413 }
414 // Don't do this if the next receive is in the same process as the current one.
415 if (receiver == null || nextReceiver == null
416 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
417 || !receiver.processName.equals(nextReceiver.processName)) {
418 // In this case, we are ready to process the next receiver for the current broadcast,
419 // but are on a queue that would like to wait for services to finish before moving
420 // on. If there are background services currently starting, then we will go into a
421 // special state where we hold off on continuing this broadcast until they are done.
422 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800423 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700424 r.state = BroadcastRecord.WAITING_SERVICES;
425 return false;
426 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700427 }
428 }
429
430 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800431
432 // We will process the next receiver right now if this is finishing
433 // an app receiver (which is always asynchronous) or after we have
434 // come back from calling a receiver.
435 return state == BroadcastRecord.APP_RECEIVE
436 || state == BroadcastRecord.CALL_DONE_RECEIVE;
437 }
438
Dianne Hackborn6285a322013-09-18 12:09:47 -0700439 public void backgroundServicesFinishedLocked(int userId) {
440 if (mOrderedBroadcasts.size() > 0) {
441 BroadcastRecord br = mOrderedBroadcasts.get(0);
442 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800443 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700444 br.curComponent = null;
445 br.state = BroadcastRecord.IDLE;
446 processNextBroadcast(false);
447 }
448 }
449 }
450
Joe Onorato5869d1c2016-04-20 15:38:07 -0700451 private void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800452 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700453 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800454 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000455 if (app != null) {
456 if (app.thread != null) {
457 // If we have an app thread, do the call through that so it is
458 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700459 try {
460 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
461 data, extras, ordered, sticky, sendingUser, app.repProcState);
462 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
463 // DeadObjectException when the process isn't actually dead.
464 //} catch (DeadObjectException ex) {
465 // Failed to call into the process. It's dying so just let it die and move on.
466 // throw ex;
467 } catch (RemoteException ex) {
468 // Failed to call into the process. It's either dying or wedged. Kill it gently.
469 synchronized (mService) {
470 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
471 + " (pid " + app.pid + "). Crashing it.");
472 app.scheduleCrash("can't deliver broadcast");
473 }
474 throw ex;
475 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000476 } else {
477 // Application has died. Receiver doesn't exist.
478 throw new RemoteException("app.thread must not be null");
479 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800480 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700481 receiver.performReceive(intent, resultCode, data, extras, ordered,
482 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800483 }
484 }
485
Svet Ganov99b60432015-06-27 13:15:22 -0700486 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800487 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800488 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700489 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800490 int perm = mService.checkComponentPermission(filter.requiredPermission,
491 r.callingPid, r.callingUid, -1, true);
492 if (perm != PackageManager.PERMISSION_GRANTED) {
493 Slog.w(TAG, "Permission Denial: broadcasting "
494 + r.intent.toString()
495 + " from " + r.callerPackage + " (pid="
496 + r.callingPid + ", uid=" + r.callingUid + ")"
497 + " requires " + filter.requiredPermission
498 + " due to registered receiver " + filter);
499 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700500 } else {
501 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
502 if (opCode != AppOpsManager.OP_NONE
503 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
504 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
505 Slog.w(TAG, "Appop Denial: broadcasting "
506 + r.intent.toString()
507 + " from " + r.callerPackage + " (pid="
508 + r.callingPid + ", uid=" + r.callingUid + ")"
509 + " requires appop " + AppOpsManager.permissionToOp(
510 filter.requiredPermission)
511 + " due to registered receiver " + filter);
512 skip = true;
513 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800514 }
515 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700516 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
517 for (int i = 0; i < r.requiredPermissions.length; i++) {
518 String requiredPermission = r.requiredPermissions[i];
519 int perm = mService.checkComponentPermission(requiredPermission,
520 filter.receiverList.pid, filter.receiverList.uid, -1, true);
521 if (perm != PackageManager.PERMISSION_GRANTED) {
522 Slog.w(TAG, "Permission Denial: receiving "
523 + r.intent.toString()
524 + " to " + filter.receiverList.app
525 + " (pid=" + filter.receiverList.pid
526 + ", uid=" + filter.receiverList.uid + ")"
527 + " requires " + requiredPermission
528 + " due to sender " + r.callerPackage
529 + " (uid " + r.callingUid + ")");
530 skip = true;
531 break;
532 }
533 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700534 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700535 && mService.mAppOpsService.noteOperation(appOp,
536 filter.receiverList.uid, filter.packageName)
537 != AppOpsManager.MODE_ALLOWED) {
538 Slog.w(TAG, "Appop Denial: receiving "
539 + r.intent.toString()
540 + " to " + filter.receiverList.app
541 + " (pid=" + filter.receiverList.pid
542 + ", uid=" + filter.receiverList.uid + ")"
543 + " requires appop " + AppOpsManager.permissionToOp(
544 requiredPermission)
545 + " due to sender " + r.callerPackage
546 + " (uid " + r.callingUid + ")");
547 skip = true;
548 break;
549 }
550 }
551 }
552 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
553 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000554 filter.receiverList.pid, filter.receiverList.uid, -1, true);
555 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700556 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000557 + r.intent.toString()
558 + " to " + filter.receiverList.app
559 + " (pid=" + filter.receiverList.pid
560 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000561 + " due to sender " + r.callerPackage
562 + " (uid " + r.callingUid + ")");
563 skip = true;
564 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700565 }
566 if (!skip && r.appOp != AppOpsManager.OP_NONE
567 && mService.mAppOpsService.noteOperation(r.appOp,
568 filter.receiverList.uid, filter.packageName)
569 != AppOpsManager.MODE_ALLOWED) {
570 Slog.w(TAG, "Appop Denial: receiving "
571 + r.intent.toString()
572 + " to " + filter.receiverList.app
573 + " (pid=" + filter.receiverList.pid
574 + ", uid=" + filter.receiverList.uid + ")"
575 + " requires appop " + AppOpsManager.opToName(r.appOp)
576 + " due to sender " + r.callerPackage
577 + " (uid " + r.callingUid + ")");
578 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700579 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700580 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800581 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700582 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800583 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700584 Slog.w(TAG, "Background execution not allowed: receiving "
585 + r.intent
586 + " to " + filter.receiverList.app
587 + " (pid=" + filter.receiverList.pid
588 + ", uid=" + filter.receiverList.uid + ")");
589 skip = true;
590 }
591 }
Svet Ganov99b60432015-06-27 13:15:22 -0700592
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700593 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
594 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800595 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700596 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800597
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800598 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700599 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
600 + " to " + filter.receiverList + ": process crashing");
601 skip = true;
602 }
603
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800604 if (skip) {
605 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
606 return;
607 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800608
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800609 // If permissions need a review before any of the app components can run, we drop
610 // the broadcast and if the calling app is in the foreground and the broadcast is
611 // explicit we launch the review UI passing it a pending intent to send the skipped
612 // broadcast.
613 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
614 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
615 filter.owningUserId)) {
616 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
617 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800618 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800619 }
620
621 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
622
623 // If this is not being sent as an ordered broadcast, then we
624 // don't want to touch the fields that keep track of the current
625 // state of ordered broadcasts.
626 if (ordered) {
627 r.receiver = filter.receiverList.receiver.asBinder();
628 r.curFilter = filter;
629 filter.receiverList.curBroadcast = r;
630 r.state = BroadcastRecord.CALL_IN_RECEIVE;
631 if (filter.receiverList.app != null) {
632 // Bump hosting application to no longer be in background
633 // scheduling class. Note that we can't do that if there
634 // isn't an app... but we can only be in that case for
635 // things that directly call the IActivityManager API, which
636 // are already core system stuff so don't matter for this.
637 r.curApp = filter.receiverList.app;
638 filter.receiverList.app.curReceiver = r;
639 mService.updateOomAdjLocked(r.curApp);
640 }
641 }
642 try {
643 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
644 "Delivering to " + filter + " : " + r);
645 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
646 new Intent(r.intent), r.resultCode, r.resultData,
647 r.resultExtras, r.ordered, r.initialSticky, r.userId);
648 if (ordered) {
649 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
650 }
651 } catch (RemoteException e) {
652 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
653 if (ordered) {
654 r.receiver = null;
655 r.curFilter = null;
656 filter.receiverList.curBroadcast = null;
657 if (filter.receiverList.app != null) {
658 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800659 }
660 }
661 }
662 }
663
Svet Ganov9c165d72015-12-01 19:52:26 -0800664 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
665 BroadcastRecord receiverRecord, String receivingPackageName,
666 final int receivingUserId) {
667 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
668 receivingPackageName, receivingUserId)) {
669 return true;
670 }
671
672 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800673 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800674 : true;
675
676 // Show a permission review UI only for explicit broadcast from a foreground app
677 if (callerForeground && receiverRecord.intent.getComponent() != null) {
678 IIntentSender target = mService.getIntentSenderLocked(
679 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
680 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
681 new Intent[]{receiverRecord.intent},
682 new String[]{receiverRecord.intent.resolveType(mService.mContext
683 .getContentResolver())},
684 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
685 | PendingIntent.FLAG_IMMUTABLE, null);
686
687 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
688 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
689 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
690 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
691 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
692
693 if (DEBUG_PERMISSIONS_REVIEW) {
694 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
695 + receivingPackageName);
696 }
697
698 mHandler.post(new Runnable() {
699 @Override
700 public void run() {
701 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
702 }
703 });
704 } else {
705 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
706 + receivingPackageName + " requires a permissions review");
707 }
708
709 return false;
710 }
711
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700712 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700713 if (duration > Integer.MAX_VALUE) {
714 duration = Integer.MAX_VALUE;
715 }
716 // XXX ideally we should pause the broadcast until everything behind this is done,
717 // or else we will likely start dispatching the broadcast before we have opened
718 // access to the app (there is a lot of asynchronicity behind this). It is probably
719 // not that big a deal, however, because the main purpose here is to allow apps
720 // to hold wake locks, and they will be able to acquire their wake lock immediately
721 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700722 StringBuilder b = new StringBuilder();
723 b.append("broadcast:");
724 UserHandle.formatUid(b, r.callingUid);
725 b.append(":");
726 if (r.intent.getAction() != null) {
727 b.append(r.intent.getAction());
728 } else if (r.intent.getComponent() != null) {
729 b.append(r.intent.getComponent().flattenToShortString());
730 } else if (r.intent.getData() != null) {
731 b.append(r.intent.getData());
732 }
733 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
734 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700735 }
736
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800737 final void processNextBroadcast(boolean fromMsg) {
738 synchronized(mService) {
739 BroadcastRecord r;
740
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800741 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800742 + mQueueName + "]: "
743 + mParallelBroadcasts.size() + " broadcasts, "
744 + mOrderedBroadcasts.size() + " ordered broadcasts");
745
746 mService.updateCpuStats();
747
748 if (fromMsg) {
749 mBroadcastsScheduled = false;
750 }
751
752 // First, deliver any non-serialized broadcasts right away.
753 while (mParallelBroadcasts.size() > 0) {
754 r = mParallelBroadcasts.remove(0);
755 r.dispatchTime = SystemClock.uptimeMillis();
756 r.dispatchClockTime = System.currentTimeMillis();
757 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800758 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800759 + mQueueName + "] " + r);
760 for (int i=0; i<N; i++) {
761 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800762 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800763 "Delivering non-ordered on [" + mQueueName + "] to registered "
764 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800765 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800766 }
767 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800768 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800769 + mQueueName + "] " + r);
770 }
771
772 // Now take care of the next serialized one...
773
774 // If we are waiting for a process to come up to handle the next
775 // broadcast, then do nothing at this point. Just in case, we
776 // check that the process we're waiting for still exists.
777 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700778 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
779 "processNextBroadcast [" + mQueueName + "]: waiting for "
780 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800781
782 boolean isDead;
783 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700784 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
785 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800786 }
787 if (!isDead) {
788 // It's still alive, so keep waiting
789 return;
790 } else {
791 Slog.w(TAG, "pending app ["
792 + mQueueName + "]" + mPendingBroadcast.curApp
793 + " died before responding to broadcast");
794 mPendingBroadcast.state = BroadcastRecord.IDLE;
795 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
796 mPendingBroadcast = null;
797 }
798 }
799
800 boolean looped = false;
801
802 do {
803 if (mOrderedBroadcasts.size() == 0) {
804 // No more broadcasts pending, so all done!
805 mService.scheduleAppGcsLocked();
806 if (looped) {
807 // If we had finished the last ordered broadcast, then
808 // make sure all processes have correct oom and sched
809 // adjustments.
810 mService.updateOomAdjLocked();
811 }
812 return;
813 }
814 r = mOrderedBroadcasts.get(0);
815 boolean forceReceive = false;
816
817 // Ensure that even if something goes awry with the timeout
818 // detection, we catch "hung" broadcasts here, discard them,
819 // and continue to make progress.
820 //
821 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
822 // receivers don't get executed with timeouts. They're intended for
823 // one time heavy lifting after system upgrades and can take
824 // significant amounts of time.
825 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
826 if (mService.mProcessesReady && r.dispatchTime > 0) {
827 long now = SystemClock.uptimeMillis();
828 if ((numReceivers > 0) &&
829 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
830 Slog.w(TAG, "Hung broadcast ["
831 + mQueueName + "] discarded after timeout failure:"
832 + " now=" + now
833 + " dispatchTime=" + r.dispatchTime
834 + " startTime=" + r.receiverTime
835 + " intent=" + r.intent
836 + " numReceivers=" + numReceivers
837 + " nextReceiver=" + r.nextReceiver
838 + " state=" + r.state);
839 broadcastTimeoutLocked(false); // forcibly finish this broadcast
840 forceReceive = true;
841 r.state = BroadcastRecord.IDLE;
842 }
843 }
844
845 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800846 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800847 "processNextBroadcast("
848 + mQueueName + ") called when not idle (state="
849 + r.state + ")");
850 return;
851 }
852
853 if (r.receivers == null || r.nextReceiver >= numReceivers
854 || r.resultAbort || forceReceive) {
855 // No more receivers for this broadcast! Send the final
856 // result if requested...
857 if (r.resultTo != null) {
858 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800859 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800860 "Finishing broadcast [" + mQueueName + "] "
861 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800862 performReceiveLocked(r.callerApp, r.resultTo,
863 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700864 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800865 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700866 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800867 r.resultTo = null;
868 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000869 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800870 Slog.w(TAG, "Failure ["
871 + mQueueName + "] sending broadcast result of "
872 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700873
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800874 }
875 }
876
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800877 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800878 cancelBroadcastTimeoutLocked();
879
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700880 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
881 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800882
883 // ... and on to the next...
884 addBroadcastToHistoryLocked(r);
885 mOrderedBroadcasts.remove(0);
886 r = null;
887 looped = true;
888 continue;
889 }
890 } while (r == null);
891
892 // Get the next receiver...
893 int recIdx = r.nextReceiver++;
894
895 // Keep track of when this receiver started, and make sure there
896 // is a timeout message pending to kill it if need be.
897 r.receiverTime = SystemClock.uptimeMillis();
898 if (recIdx == 0) {
899 r.dispatchTime = r.receiverTime;
900 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800901 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800902 + mQueueName + "] " + r);
903 }
904 if (! mPendingBroadcastTimeoutMessage) {
905 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800906 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800907 "Submitting BROADCAST_TIMEOUT_MSG ["
908 + mQueueName + "] for " + r + " at " + timeoutTime);
909 setBroadcastTimeoutLocked(timeoutTime);
910 }
911
Dianne Hackborna750a632015-06-16 17:18:23 -0700912 final BroadcastOptions brOptions = r.options;
913 final Object nextReceiver = r.receivers.get(recIdx);
914
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800915 if (nextReceiver instanceof BroadcastFilter) {
916 // Simple case: this is a registered receiver who gets
917 // a direct call.
918 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800919 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800920 "Delivering ordered ["
921 + mQueueName + "] to registered "
922 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800923 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800924 if (r.receiver == null || !r.ordered) {
925 // The receiver has already finished, so schedule to
926 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800927 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800928 + mQueueName + "]: ordered="
929 + r.ordered + " receiver=" + r.receiver);
930 r.state = BroadcastRecord.IDLE;
931 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700932 } else {
933 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
934 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700935 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700936 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800937 }
938 return;
939 }
940
941 // Hard case: need to instantiate the receiver, possibly
942 // starting its application process to host it.
943
944 ResolveInfo info =
945 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700946 ComponentName component = new ComponentName(
947 info.activityInfo.applicationInfo.packageName,
948 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800949
950 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800951 if (brOptions != null &&
952 (info.activityInfo.applicationInfo.targetSdkVersion
953 < brOptions.getMinManifestReceiverApiLevel() ||
954 info.activityInfo.applicationInfo.targetSdkVersion
955 > brOptions.getMaxManifestReceiverApiLevel())) {
956 skip = true;
957 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800958 int perm = mService.checkComponentPermission(info.activityInfo.permission,
959 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
960 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800961 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800962 if (!info.activityInfo.exported) {
963 Slog.w(TAG, "Permission Denial: broadcasting "
964 + r.intent.toString()
965 + " from " + r.callerPackage + " (pid=" + r.callingPid
966 + ", uid=" + r.callingUid + ")"
967 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700968 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800969 } else {
970 Slog.w(TAG, "Permission Denial: broadcasting "
971 + r.intent.toString()
972 + " from " + r.callerPackage + " (pid=" + r.callingPid
973 + ", uid=" + r.callingUid + ")"
974 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700975 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800976 }
977 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800978 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -0700979 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
980 if (opCode != AppOpsManager.OP_NONE
981 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
982 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
983 Slog.w(TAG, "Appop Denial: broadcasting "
984 + r.intent.toString()
985 + " from " + r.callerPackage + " (pid="
986 + r.callingPid + ", uid=" + r.callingUid + ")"
987 + " requires appop " + AppOpsManager.permissionToOp(
988 info.activityInfo.permission)
989 + " due to registered receiver "
990 + component.flattenToShortString());
991 skip = true;
992 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800993 }
Svet Ganov99b60432015-06-27 13:15:22 -0700994 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700995 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
996 for (int i = 0; i < r.requiredPermissions.length; i++) {
997 String requiredPermission = r.requiredPermissions[i];
998 try {
999 perm = AppGlobals.getPackageManager().
1000 checkPermission(requiredPermission,
1001 info.activityInfo.applicationInfo.packageName,
1002 UserHandle
1003 .getUserId(info.activityInfo.applicationInfo.uid));
1004 } catch (RemoteException e) {
1005 perm = PackageManager.PERMISSION_DENIED;
1006 }
1007 if (perm != PackageManager.PERMISSION_GRANTED) {
1008 Slog.w(TAG, "Permission Denial: receiving "
1009 + r.intent + " to "
1010 + component.flattenToShortString()
1011 + " requires " + requiredPermission
1012 + " due to sender " + r.callerPackage
1013 + " (uid " + r.callingUid + ")");
1014 skip = true;
1015 break;
1016 }
1017 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1018 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1019 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001020 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001021 != AppOpsManager.MODE_ALLOWED) {
1022 Slog.w(TAG, "Appop Denial: receiving "
1023 + r.intent + " to "
1024 + component.flattenToShortString()
1025 + " requires appop " + AppOpsManager.permissionToOp(
1026 requiredPermission)
1027 + " due to sender " + r.callerPackage
1028 + " (uid " + r.callingUid + ")");
1029 skip = true;
1030 break;
1031 }
1032 }
1033 }
1034 if (!skip && r.appOp != AppOpsManager.OP_NONE
1035 && mService.mAppOpsService.noteOperation(r.appOp,
1036 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1037 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001038 Slog.w(TAG, "Appop Denial: receiving "
1039 + r.intent + " to "
1040 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001041 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001042 + " due to sender " + r.callerPackage
1043 + " (uid " + r.callingUid + ")");
1044 skip = true;
1045 }
Ben Gruver49660c72013-08-06 19:54:08 -07001046 if (!skip) {
1047 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1048 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1049 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001050 boolean isSingleton = false;
1051 try {
1052 isSingleton = mService.isSingleton(info.activityInfo.processName,
1053 info.activityInfo.applicationInfo,
1054 info.activityInfo.name, info.activityInfo.flags);
1055 } catch (SecurityException e) {
1056 Slog.w(TAG, e.getMessage());
1057 skip = true;
1058 }
1059 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1060 if (ActivityManager.checkUidPermission(
1061 android.Manifest.permission.INTERACT_ACROSS_USERS,
1062 info.activityInfo.applicationInfo.uid)
1063 != PackageManager.PERMISSION_GRANTED) {
1064 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1065 + " requests FLAG_SINGLE_USER, but app does not hold "
1066 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1067 skip = true;
1068 }
1069 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001070 if (r.curApp != null && r.curApp.crashing) {
1071 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001072 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1073 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001074 skip = true;
1075 }
Christopher Tateba629da2013-11-13 17:42:28 -08001076 if (!skip) {
1077 boolean isAvailable = false;
1078 try {
1079 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1080 info.activityInfo.packageName,
1081 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1082 } catch (Exception e) {
1083 // all such failures mean we skip this receiver
1084 Slog.w(TAG, "Exception getting recipient info for "
1085 + info.activityInfo.packageName, e);
1086 }
1087 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001088 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1089 "Skipping delivery to " + info.activityInfo.packageName + " / "
1090 + info.activityInfo.applicationInfo.uid
1091 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001092 skip = true;
1093 }
1094 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001095
Svet Ganov9c165d72015-12-01 19:52:26 -08001096 // If permissions need a review before any of the app components can run, we drop
1097 // the broadcast and if the calling app is in the foreground and the broadcast is
1098 // explicit we launch the review UI passing it a pending intent to send the skipped
1099 // broadcast.
1100 if (Build.PERMISSIONS_REVIEW_REQUIRED && !skip) {
1101 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1102 info.activityInfo.packageName, UserHandle.getUserId(
1103 info.activityInfo.applicationInfo.uid))) {
1104 skip = true;
1105 }
1106 }
1107
Dianne Hackborn76e80092015-12-09 14:15:34 -08001108 // This is safe to do even if we are skipping the broadcast, and we need
1109 // this information now to evaluate whether it is going to be allowed to run.
1110 final int receiverUid = info.activityInfo.applicationInfo.uid;
1111 // If it's a singleton, it needs to be the same app or a special app
1112 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1113 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1114 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1115 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001116 String targetProcess = info.activityInfo.processName;
1117 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1118 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001119
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001120 if (!skip) {
1121 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001122 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1123 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001124 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1125 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001126 // completely disabled from launches, or it was not explicitly sent
1127 // to it and the app is in a state that should not receive it
1128 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001129 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1130 Slog.w(TAG, "Background execution disabled: receiving "
1131 + r.intent + " to "
1132 + component.flattenToShortString());
1133 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001134 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001135 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001136 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001137 && ((r.intent.getFlags()
1138 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001139 Slog.w(TAG, "Background execution not allowed: receiving "
1140 + r.intent + " to "
1141 + component.flattenToShortString());
1142 skip = true;
1143 }
1144 }
1145 }
1146
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001147 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001148 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001149 "Skipping delivery of ordered [" + mQueueName + "] "
1150 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001151 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001152 r.receiver = null;
1153 r.curFilter = null;
1154 r.state = BroadcastRecord.IDLE;
1155 scheduleBroadcastsLocked();
1156 return;
1157 }
1158
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001159 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001160 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001161 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001162 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001163 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001164 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1165 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1166 + info.activityInfo.applicationInfo.uid);
1167 }
1168
Dianne Hackborna750a632015-06-16 17:18:23 -07001169 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1170 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001171 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001172 }
1173
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001174 // Broadcast is being executed, its package can't be stopped.
1175 try {
1176 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001177 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001178 } catch (RemoteException e) {
1179 } catch (IllegalArgumentException e) {
1180 Slog.w(TAG, "Failed trying to unstop package "
1181 + r.curComponent.getPackageName() + ": " + e);
1182 }
1183
1184 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001185 if (app != null && app.thread != null) {
1186 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001187 app.addPackage(info.activityInfo.packageName,
1188 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001189 processCurBroadcastLocked(r, app);
1190 return;
1191 } catch (RemoteException e) {
1192 Slog.w(TAG, "Exception when sending broadcast to "
1193 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001194 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001195 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001196 + r.curComponent + " with " + r.intent, e);
1197 // If some unexpected exception happened, just skip
1198 // this broadcast. At this point we are not in the call
1199 // from a client, so throwing an exception out from here
1200 // will crash the entire system instead of just whoever
1201 // sent the broadcast.
1202 logBroadcastReceiverDiscardLocked(r);
1203 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001204 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001205 scheduleBroadcastsLocked();
1206 // We need to reset the state if we failed to start the receiver.
1207 r.state = BroadcastRecord.IDLE;
1208 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001209 }
1210
1211 // If a dead object exception was thrown -- fall through to
1212 // restart the application.
1213 }
1214
1215 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001216 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001217 "Need to start app ["
1218 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1219 if ((r.curApp=mService.startProcessLocked(targetProcess,
1220 info.activityInfo.applicationInfo, true,
1221 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1222 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001223 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001224 == null) {
1225 // Ah, this recipient is unavailable. Finish it if necessary,
1226 // and mark the broadcast record as ready for the next.
1227 Slog.w(TAG, "Unable to launch app "
1228 + info.activityInfo.applicationInfo.packageName + "/"
1229 + info.activityInfo.applicationInfo.uid + " for broadcast "
1230 + r.intent + ": process is bad");
1231 logBroadcastReceiverDiscardLocked(r);
1232 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001233 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001234 scheduleBroadcastsLocked();
1235 r.state = BroadcastRecord.IDLE;
1236 return;
1237 }
1238
1239 mPendingBroadcast = r;
1240 mPendingBroadcastRecvIndex = recIdx;
1241 }
1242 }
1243
1244 final void setBroadcastTimeoutLocked(long timeoutTime) {
1245 if (! mPendingBroadcastTimeoutMessage) {
1246 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1247 mHandler.sendMessageAtTime(msg, timeoutTime);
1248 mPendingBroadcastTimeoutMessage = true;
1249 }
1250 }
1251
1252 final void cancelBroadcastTimeoutLocked() {
1253 if (mPendingBroadcastTimeoutMessage) {
1254 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1255 mPendingBroadcastTimeoutMessage = false;
1256 }
1257 }
1258
1259 final void broadcastTimeoutLocked(boolean fromMsg) {
1260 if (fromMsg) {
1261 mPendingBroadcastTimeoutMessage = false;
1262 }
1263
1264 if (mOrderedBroadcasts.size() == 0) {
1265 return;
1266 }
1267
1268 long now = SystemClock.uptimeMillis();
1269 BroadcastRecord r = mOrderedBroadcasts.get(0);
1270 if (fromMsg) {
1271 if (mService.mDidDexOpt) {
1272 // Delay timeouts until dexopt finishes.
1273 mService.mDidDexOpt = false;
1274 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1275 setBroadcastTimeoutLocked(timeoutTime);
1276 return;
1277 }
1278 if (!mService.mProcessesReady) {
1279 // Only process broadcast timeouts if the system is ready. That way
1280 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1281 // to do heavy lifting for system up.
1282 return;
1283 }
1284
1285 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1286 if (timeoutTime > now) {
1287 // We can observe premature timeouts because we do not cancel and reset the
1288 // broadcast timeout message after each receiver finishes. Instead, we set up
1289 // an initial timeout then kick it down the road a little further as needed
1290 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001291 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001292 "Premature timeout ["
1293 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1294 + timeoutTime);
1295 setBroadcastTimeoutLocked(timeoutTime);
1296 return;
1297 }
1298 }
1299
Dianne Hackborn6285a322013-09-18 12:09:47 -07001300 BroadcastRecord br = mOrderedBroadcasts.get(0);
1301 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1302 // In this case the broadcast had already finished, but we had decided to wait
1303 // for started services to finish as well before going on. So if we have actually
1304 // waited long enough time timeout the broadcast, let's give up on the whole thing
1305 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001306 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001307 ? br.curComponent.flattenToShortString() : "(null)"));
1308 br.curComponent = null;
1309 br.state = BroadcastRecord.IDLE;
1310 processNextBroadcast(false);
1311 return;
1312 }
1313
1314 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001315 + ", started " + (now - r.receiverTime) + "ms ago");
1316 r.receiverTime = now;
1317 r.anrCount++;
1318
1319 // Current receiver has passed its expiration date.
1320 if (r.nextReceiver <= 0) {
1321 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1322 return;
1323 }
1324
1325 ProcessRecord app = null;
1326 String anrMessage = null;
1327
1328 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001329 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001330 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1331 logBroadcastReceiverDiscardLocked(r);
1332 if (curReceiver instanceof BroadcastFilter) {
1333 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1334 if (bf.receiverList.pid != 0
1335 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1336 synchronized (mService.mPidsSelfLocked) {
1337 app = mService.mPidsSelfLocked.get(
1338 bf.receiverList.pid);
1339 }
1340 }
1341 } else {
1342 app = r.curApp;
1343 }
1344
1345 if (app != null) {
1346 anrMessage = "Broadcast of " + r.intent.toString();
1347 }
1348
1349 if (mPendingBroadcast == r) {
1350 mPendingBroadcast = null;
1351 }
1352
1353 // Move on to the next receiver.
1354 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001355 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001356 scheduleBroadcastsLocked();
1357
1358 if (anrMessage != null) {
1359 // Post the ANR to the handler since we do not want to process ANRs while
1360 // potentially holding our lock.
1361 mHandler.post(new AppNotResponding(app, anrMessage));
1362 }
1363 }
1364
Christopher Tatef278f122015-04-22 13:12:01 -07001365 private final int ringAdvance(int x, final int increment, final int ringSize) {
1366 x += increment;
1367 if (x < 0) return (ringSize - 1);
1368 else if (x >= ringSize) return 0;
1369 else return x;
1370 }
1371
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001372 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1373 if (r.callingUid < 0) {
1374 // This was from a registerReceiver() call; ignore it.
1375 return;
1376 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001377 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001378
1379 mBroadcastHistory[mHistoryNext] = r;
1380 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1381
1382 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1383 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1384 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1385 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1386 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001387 }
1388
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001389 boolean cleanupDisabledPackageReceiversLocked(
1390 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1391 boolean didSomething = false;
1392 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1393 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1394 packageName, filterByClasses, userId, doit);
1395 if (!doit && didSomething) {
1396 return true;
1397 }
1398 }
1399
1400 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1401 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1402 packageName, filterByClasses, userId, doit);
1403 if (!doit && didSomething) {
1404 return true;
1405 }
1406 }
1407
1408 return didSomething;
1409 }
1410
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001411 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001412 final int logIndex = r.nextReceiver - 1;
1413 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1414 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001415 if (curReceiver instanceof BroadcastFilter) {
1416 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1417 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001418 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001419 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001420 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001421 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001422 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001423 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001424 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001425 }
1426 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001427 if (logIndex < 0) Slog.w(TAG,
1428 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001429 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001430 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001431 r.intent.getAction(),
1432 r.nextReceiver,
1433 "NONE");
1434 }
1435 }
1436
1437 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1438 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001439 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001440 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1441 || mPendingBroadcast != null) {
1442 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001443 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001444 BroadcastRecord br = mParallelBroadcasts.get(i);
1445 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1446 continue;
1447 }
1448 if (!printed) {
1449 if (needSep) {
1450 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001451 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001452 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001453 printed = true;
1454 pw.println(" Active broadcasts [" + mQueueName + "]:");
1455 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001456 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001457 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001458 }
1459 printed = false;
1460 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001461 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001462 BroadcastRecord br = mOrderedBroadcasts.get(i);
1463 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1464 continue;
1465 }
1466 if (!printed) {
1467 if (needSep) {
1468 pw.println();
1469 }
1470 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001471 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001472 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1473 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001474 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001475 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001476 }
1477 if (dumpPackage == null || (mPendingBroadcast != null
1478 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1479 if (needSep) {
1480 pw.println();
1481 }
1482 pw.println(" Pending broadcast [" + mQueueName + "]:");
1483 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001484 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001485 } else {
1486 pw.println(" (null)");
1487 }
1488 needSep = true;
1489 }
1490 }
1491
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001492 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001493 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001494
1495 i = -1;
1496 int lastIndex = mHistoryNext;
1497 int ringIndex = lastIndex;
1498 do {
1499 // increasing index = more recent entry, and we want to print the most
1500 // recent first and work backwards, so we roll through the ring backwards.
1501 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1502 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001504 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001505 }
Christopher Tatef278f122015-04-22 13:12:01 -07001506
1507 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001508 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1509 continue;
1510 }
1511 if (!printed) {
1512 if (needSep) {
1513 pw.println();
1514 }
1515 needSep = true;
1516 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1517 printed = true;
1518 }
1519 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001520 pw.print(" Historical Broadcast " + mQueueName + " #");
1521 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001522 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001523 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001524 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1525 pw.print(" ");
1526 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001527 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1528 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1529 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001530 Bundle bundle = r.intent.getExtras();
1531 if (bundle != null) {
1532 pw.print(" extras: "); pw.println(bundle.toString());
1533 }
1534 }
Christopher Tatef278f122015-04-22 13:12:01 -07001535 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001536
1537 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001538 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001539 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001540 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001541 i = -1;
1542 } else {
1543 // roll over the 'i' full dumps that have already been issued
1544 for (int j = i;
1545 j > 0 && ringIndex != lastIndex;) {
1546 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1547 BroadcastRecord r = mBroadcastHistory[ringIndex];
1548 if (r == null) {
1549 continue;
1550 }
1551 j--;
1552 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001553 }
Christopher Tatef278f122015-04-22 13:12:01 -07001554 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1555 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001556 do {
1557 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1558 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001559 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001560 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001561 }
1562 if (!printed) {
1563 if (needSep) {
1564 pw.println();
1565 }
1566 needSep = true;
1567 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1568 printed = true;
1569 }
1570 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001571 pw.println(" ...");
1572 break;
1573 }
Christopher Tatef278f122015-04-22 13:12:01 -07001574 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001575 pw.print(" #"); pw.print(i); pw.print(": ");
1576 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001577 pw.print(" ");
1578 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1579 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1580 pw.print(" dispatch ");
1581 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1582 - mSummaryHistoryDispatchTime[ringIndex], pw);
1583 pw.println(" finish");
1584 pw.print(" enq=");
1585 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1586 pw.print(" disp=");
1587 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1588 pw.print(" fin=");
1589 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001590 Bundle bundle = intent.getExtras();
1591 if (bundle != null) {
1592 pw.print(" extras: "); pw.println(bundle.toString());
1593 }
Christopher Tatef278f122015-04-22 13:12:01 -07001594 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001595 }
1596
1597 return needSep;
1598 }
1599}