blob: a279290a34beb9426db3069d99769b2ab7cac9e6 [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;
41import android.os.Handler;
42import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080043import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080044import android.os.Message;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080049import android.util.EventLog;
50import android.util.Slog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070051import android.util.TimeUtils;
Dianne Hackborna750a632015-06-16 17:18:23 -070052import com.android.server.DeviceIdleController;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080053
Wale Ogunwaled57969f2014-11-15 19:37:29 -080054import static com.android.server.am.ActivityManagerDebugConfig.*;
55
Dianne Hackborn40c8db52012-02-10 18:59:48 -080056/**
57 * BROADCASTS
58 *
59 * We keep two broadcast queues and associated bookkeeping, one for those at
60 * foreground priority, and one for normal (background-priority) broadcasts.
61 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070062public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070063 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080064 private static final String TAG_MU = TAG + POSTFIX_MU;
65 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080066
Dianne Hackborn4c51de42013-10-16 23:34:35 -070067 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070068 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070069 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080070
71 final ActivityManagerService mService;
72
73 /**
74 * Recognizable moniker for this queue
75 */
76 final String mQueueName;
77
78 /**
79 * Timeout period for this queue's broadcasts
80 */
81 final long mTimeoutPeriod;
82
83 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070084 * If true, we can delay broadcasts while waiting services to finish in the previous
85 * receiver's process.
86 */
87 final boolean mDelayBehindServices;
88
89 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080090 * Lists of all active broadcasts that are to be executed immediately
91 * (without waiting for another broadcast to finish). Currently this only
92 * contains broadcasts to registered receivers, to avoid spinning up
93 * a bunch of processes to execute IntentReceiver components. Background-
94 * and foreground-priority broadcasts are queued separately.
95 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070096 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070097
Dianne Hackborn40c8db52012-02-10 18:59:48 -080098 /**
99 * List of all active broadcasts that are to be executed one at a time.
100 * The object at the top of the list is the currently activity broadcasts;
101 * those after it are waiting for the top to finish. As with parallel
102 * broadcasts, separate background- and foreground-priority queues are
103 * maintained.
104 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700105 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800106
107 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700108 * Historical data of past broadcasts, for debugging. This is a ring buffer
109 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800110 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700111 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700112 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800113
114 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700115 * Summary of historical data of past broadcasts, for debugging. This is a
116 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700117 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700118 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700119 int mSummaryHistoryNext = 0;
120
121 /**
122 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
123 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
124 * clock time, not elapsed.
125 */
126 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
127 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
128 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700129
130 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800131 * Set when we current have a BROADCAST_INTENT_MSG in flight.
132 */
133 boolean mBroadcastsScheduled = false;
134
135 /**
136 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
137 */
138 boolean mPendingBroadcastTimeoutMessage;
139
140 /**
141 * Intent broadcasts that we have tried to start, but are
142 * waiting for the application's process to be created. We only
143 * need one per scheduling class (instead of a list) because we always
144 * process broadcasts one at a time, so no others can be started while
145 * waiting for this one.
146 */
147 BroadcastRecord mPendingBroadcast = null;
148
149 /**
150 * The receiver index that is pending, to restart the broadcast if needed.
151 */
152 int mPendingBroadcastRecvIndex;
153
154 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
155 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700156 static final int SCHEDULE_TEMP_WHITELIST_MSG
157 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800158
Jeff Brown6f357d32014-01-15 20:40:55 -0800159 final BroadcastHandler mHandler;
160
161 private final class BroadcastHandler extends Handler {
162 public BroadcastHandler(Looper looper) {
163 super(looper, null, true);
164 }
165
166 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800167 public void handleMessage(Message msg) {
168 switch (msg.what) {
169 case BROADCAST_INTENT_MSG: {
170 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800171 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800172 processNextBroadcast(true);
173 } break;
174 case BROADCAST_TIMEOUT_MSG: {
175 synchronized (mService) {
176 broadcastTimeoutLocked(true);
177 }
178 } break;
Dianne Hackborna750a632015-06-16 17:18:23 -0700179 case SCHEDULE_TEMP_WHITELIST_MSG: {
180 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
181 if (dic != null) {
182 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700183 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700184 }
185 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800186 }
187 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800188 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800189
190 private final class AppNotResponding implements Runnable {
191 private final ProcessRecord mApp;
192 private final String mAnnotation;
193
194 public AppNotResponding(ProcessRecord app, String annotation) {
195 mApp = app;
196 mAnnotation = annotation;
197 }
198
199 @Override
200 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100201 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800202 }
203 }
204
Jeff Brown6f357d32014-01-15 20:40:55 -0800205 BroadcastQueue(ActivityManagerService service, Handler handler,
206 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800207 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800208 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800209 mQueueName = name;
210 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700211 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800212 }
213
214 public boolean isPendingBroadcastProcessLocked(int pid) {
215 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
216 }
217
218 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
219 mParallelBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700220 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800221 }
222
223 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
224 mOrderedBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700225 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800226 }
227
228 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700229 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800230 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800231 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800232 "***** DROPPING PARALLEL ["
233 + mQueueName + "]: " + r.intent);
234 mParallelBroadcasts.set(i, r);
235 return true;
236 }
237 }
238 return false;
239 }
240
241 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700242 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800243 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800244 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800245 "***** DROPPING ORDERED ["
246 + mQueueName + "]: " + r.intent);
247 mOrderedBroadcasts.set(i, r);
248 return true;
249 }
250 }
251 return false;
252 }
253
254 private final void processCurBroadcastLocked(BroadcastRecord r,
255 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800256 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800257 "Process cur broadcast " + r + " for app " + app);
258 if (app.thread == null) {
259 throw new RemoteException();
260 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700261 if (app.inFullBackup) {
262 skipReceiverLocked(r);
263 return;
264 }
265
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800266 r.receiver = app.thread.asBinder();
267 r.curApp = app;
268 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700269 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700270 mService.updateLruProcessLocked(app, false, null);
271 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800272
273 // Tell the application to launch this receiver.
274 r.intent.setComponent(r.curComponent);
275
276 boolean started = false;
277 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800278 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800279 "Delivering to component " + r.curComponent
280 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700281 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
282 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800283 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
284 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700285 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
286 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800287 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800288 "Process cur broadcast " + r + " DELIVERED for app " + app);
289 started = true;
290 } finally {
291 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800292 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800293 "Process cur broadcast " + r + ": NOT STARTED!");
294 r.receiver = null;
295 r.curApp = null;
296 app.curReceiver = null;
297 }
298 }
299 }
300
301 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
302 boolean didSomething = false;
303 final BroadcastRecord br = mPendingBroadcast;
304 if (br != null && br.curApp.pid == app.pid) {
305 try {
306 mPendingBroadcast = null;
307 processCurBroadcastLocked(br, app);
308 didSomething = true;
309 } catch (Exception e) {
310 Slog.w(TAG, "Exception in new application when starting receiver "
311 + br.curComponent.flattenToShortString(), e);
312 logBroadcastReceiverDiscardLocked(br);
313 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700314 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800315 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700316 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800317 br.state = BroadcastRecord.IDLE;
318 throw new RuntimeException(e.getMessage());
319 }
320 }
321 return didSomething;
322 }
323
324 public void skipPendingBroadcastLocked(int pid) {
325 final BroadcastRecord br = mPendingBroadcast;
326 if (br != null && br.curApp.pid == pid) {
327 br.state = BroadcastRecord.IDLE;
328 br.nextReceiver = mPendingBroadcastRecvIndex;
329 mPendingBroadcast = null;
330 scheduleBroadcastsLocked();
331 }
332 }
333
334 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700335 BroadcastRecord r = null;
336 if (mOrderedBroadcasts.size() > 0) {
337 BroadcastRecord br = mOrderedBroadcasts.get(0);
338 if (br.curApp == app) {
339 r = br;
340 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800341 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800342 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800343 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800344 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800345 r = mPendingBroadcast;
346 }
347
348 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700349 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800350 }
351 }
352
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700353 private void skipReceiverLocked(BroadcastRecord r) {
354 logBroadcastReceiverDiscardLocked(r);
355 finishReceiverLocked(r, r.resultCode, r.resultData,
356 r.resultExtras, r.resultAbort, false);
357 scheduleBroadcastsLocked();
358 }
359
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800360 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800361 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800362 + mQueueName + "]: current="
363 + mBroadcastsScheduled);
364
365 if (mBroadcastsScheduled) {
366 return;
367 }
368 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
369 mBroadcastsScheduled = true;
370 }
371
372 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
373 if (mOrderedBroadcasts.size() > 0) {
374 final BroadcastRecord r = mOrderedBroadcasts.get(0);
375 if (r != null && r.receiver == receiver) {
376 return r;
377 }
378 }
379 return null;
380 }
381
382 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700383 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
384 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700385 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800386 r.state = BroadcastRecord.IDLE;
387 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700388 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800389 }
390 r.receiver = null;
391 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800392 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800393 r.curApp.curReceiver = null;
394 }
395 if (r.curFilter != null) {
396 r.curFilter.receiverList.curBroadcast = null;
397 }
398 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800399 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700400 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800401 mPendingBroadcast = null;
402
403 r.resultCode = resultCode;
404 r.resultData = resultData;
405 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700406 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
407 r.resultAbort = resultAbort;
408 } else {
409 r.resultAbort = false;
410 }
411
412 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
413 && r.queue.mOrderedBroadcasts.size() > 0
414 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700415 ActivityInfo nextReceiver;
416 if (r.nextReceiver < r.receivers.size()) {
417 Object obj = r.receivers.get(r.nextReceiver);
418 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
419 } else {
420 nextReceiver = null;
421 }
422 // Don't do this if the next receive is in the same process as the current one.
423 if (receiver == null || nextReceiver == null
424 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
425 || !receiver.processName.equals(nextReceiver.processName)) {
426 // In this case, we are ready to process the next receiver for the current broadcast,
427 // but are on a queue that would like to wait for services to finish before moving
428 // on. If there are background services currently starting, then we will go into a
429 // special state where we hold off on continuing this broadcast until they are done.
430 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800431 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700432 r.state = BroadcastRecord.WAITING_SERVICES;
433 return false;
434 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700435 }
436 }
437
438 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800439
440 // We will process the next receiver right now if this is finishing
441 // an app receiver (which is always asynchronous) or after we have
442 // come back from calling a receiver.
443 return state == BroadcastRecord.APP_RECEIVE
444 || state == BroadcastRecord.CALL_DONE_RECEIVE;
445 }
446
Dianne Hackborn6285a322013-09-18 12:09:47 -0700447 public void backgroundServicesFinishedLocked(int userId) {
448 if (mOrderedBroadcasts.size() > 0) {
449 BroadcastRecord br = mOrderedBroadcasts.get(0);
450 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800451 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700452 br.curComponent = null;
453 br.state = BroadcastRecord.IDLE;
454 processNextBroadcast(false);
455 }
456 }
457 }
458
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700459 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800460 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700461 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800462 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000463 if (app != null) {
464 if (app.thread != null) {
465 // If we have an app thread, do the call through that so it is
466 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700467 try {
468 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
469 data, extras, ordered, sticky, sendingUser, app.repProcState);
470 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
471 // DeadObjectException when the process isn't actually dead.
472 //} catch (DeadObjectException ex) {
473 // Failed to call into the process. It's dying so just let it die and move on.
474 // throw ex;
475 } catch (RemoteException ex) {
476 // Failed to call into the process. It's either dying or wedged. Kill it gently.
477 synchronized (mService) {
478 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
479 + " (pid " + app.pid + "). Crashing it.");
480 app.scheduleCrash("can't deliver broadcast");
481 }
482 throw ex;
483 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000484 } else {
485 // Application has died. Receiver doesn't exist.
486 throw new RemoteException("app.thread must not be null");
487 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800488 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700489 receiver.performReceive(intent, resultCode, data, extras, ordered,
490 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800491 }
492 }
493
Svet Ganov99b60432015-06-27 13:15:22 -0700494 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800495 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800496 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700497 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800498 int perm = mService.checkComponentPermission(filter.requiredPermission,
499 r.callingPid, r.callingUid, -1, true);
500 if (perm != PackageManager.PERMISSION_GRANTED) {
501 Slog.w(TAG, "Permission Denial: broadcasting "
502 + r.intent.toString()
503 + " from " + r.callerPackage + " (pid="
504 + r.callingPid + ", uid=" + r.callingUid + ")"
505 + " requires " + filter.requiredPermission
506 + " due to registered receiver " + filter);
507 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700508 } else {
509 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
510 if (opCode != AppOpsManager.OP_NONE
511 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
512 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
513 Slog.w(TAG, "Appop Denial: broadcasting "
514 + r.intent.toString()
515 + " from " + r.callerPackage + " (pid="
516 + r.callingPid + ", uid=" + r.callingUid + ")"
517 + " requires appop " + AppOpsManager.permissionToOp(
518 filter.requiredPermission)
519 + " due to registered receiver " + filter);
520 skip = true;
521 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800522 }
523 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700524 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
525 for (int i = 0; i < r.requiredPermissions.length; i++) {
526 String requiredPermission = r.requiredPermissions[i];
527 int perm = mService.checkComponentPermission(requiredPermission,
528 filter.receiverList.pid, filter.receiverList.uid, -1, true);
529 if (perm != PackageManager.PERMISSION_GRANTED) {
530 Slog.w(TAG, "Permission Denial: receiving "
531 + r.intent.toString()
532 + " to " + filter.receiverList.app
533 + " (pid=" + filter.receiverList.pid
534 + ", uid=" + filter.receiverList.uid + ")"
535 + " requires " + requiredPermission
536 + " due to sender " + r.callerPackage
537 + " (uid " + r.callingUid + ")");
538 skip = true;
539 break;
540 }
541 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700542 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700543 && mService.mAppOpsService.noteOperation(appOp,
544 filter.receiverList.uid, filter.packageName)
545 != AppOpsManager.MODE_ALLOWED) {
546 Slog.w(TAG, "Appop Denial: receiving "
547 + r.intent.toString()
548 + " to " + filter.receiverList.app
549 + " (pid=" + filter.receiverList.pid
550 + ", uid=" + filter.receiverList.uid + ")"
551 + " requires appop " + AppOpsManager.permissionToOp(
552 requiredPermission)
553 + " due to sender " + r.callerPackage
554 + " (uid " + r.callingUid + ")");
555 skip = true;
556 break;
557 }
558 }
559 }
560 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
561 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000562 filter.receiverList.pid, filter.receiverList.uid, -1, true);
563 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700564 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000565 + r.intent.toString()
566 + " to " + filter.receiverList.app
567 + " (pid=" + filter.receiverList.pid
568 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000569 + " due to sender " + r.callerPackage
570 + " (uid " + r.callingUid + ")");
571 skip = true;
572 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700573 }
574 if (!skip && r.appOp != AppOpsManager.OP_NONE
575 && mService.mAppOpsService.noteOperation(r.appOp,
576 filter.receiverList.uid, filter.packageName)
577 != AppOpsManager.MODE_ALLOWED) {
578 Slog.w(TAG, "Appop Denial: receiving "
579 + r.intent.toString()
580 + " to " + filter.receiverList.app
581 + " (pid=" + filter.receiverList.pid
582 + ", uid=" + filter.receiverList.uid + ")"
583 + " requires appop " + AppOpsManager.opToName(r.appOp)
584 + " due to sender " + r.callerPackage
585 + " (uid " + r.callingUid + ")");
586 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700587 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700588 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800589 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700590 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800591 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700592 Slog.w(TAG, "Background execution not allowed: receiving "
593 + r.intent
594 + " to " + filter.receiverList.app
595 + " (pid=" + filter.receiverList.pid
596 + ", uid=" + filter.receiverList.uid + ")");
597 skip = true;
598 }
599 }
Svet Ganov99b60432015-06-27 13:15:22 -0700600
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700601 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
602 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800603 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700604 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800605
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800606 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700607 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
608 + " to " + filter.receiverList + ": process crashing");
609 skip = true;
610 }
611
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800612 if (skip) {
613 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
614 return;
615 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800616
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800617 // If permissions need a review before any of the app components can run, we drop
618 // the broadcast and if the calling app is in the foreground and the broadcast is
619 // explicit we launch the review UI passing it a pending intent to send the skipped
620 // broadcast.
621 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
622 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
623 filter.owningUserId)) {
624 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
625 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800626 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800627 }
628
629 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
630
631 // If this is not being sent as an ordered broadcast, then we
632 // don't want to touch the fields that keep track of the current
633 // state of ordered broadcasts.
634 if (ordered) {
635 r.receiver = filter.receiverList.receiver.asBinder();
636 r.curFilter = filter;
637 filter.receiverList.curBroadcast = r;
638 r.state = BroadcastRecord.CALL_IN_RECEIVE;
639 if (filter.receiverList.app != null) {
640 // Bump hosting application to no longer be in background
641 // scheduling class. Note that we can't do that if there
642 // isn't an app... but we can only be in that case for
643 // things that directly call the IActivityManager API, which
644 // are already core system stuff so don't matter for this.
645 r.curApp = filter.receiverList.app;
646 filter.receiverList.app.curReceiver = r;
647 mService.updateOomAdjLocked(r.curApp);
648 }
649 }
650 try {
651 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
652 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700653 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
654 // Skip delivery if full backup in progress
655 // If it's an ordered broadcast, we need to continue to the next receiver.
656 if (ordered) {
657 skipReceiverLocked(r);
658 }
659 } else {
660 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
661 new Intent(r.intent), r.resultCode, r.resultData,
662 r.resultExtras, r.ordered, r.initialSticky, r.userId);
663 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800664 if (ordered) {
665 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
666 }
667 } catch (RemoteException e) {
668 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
669 if (ordered) {
670 r.receiver = null;
671 r.curFilter = null;
672 filter.receiverList.curBroadcast = null;
673 if (filter.receiverList.app != null) {
674 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800675 }
676 }
677 }
678 }
679
Svet Ganov9c165d72015-12-01 19:52:26 -0800680 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
681 BroadcastRecord receiverRecord, String receivingPackageName,
682 final int receivingUserId) {
683 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
684 receivingPackageName, receivingUserId)) {
685 return true;
686 }
687
688 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800689 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800690 : true;
691
692 // Show a permission review UI only for explicit broadcast from a foreground app
693 if (callerForeground && receiverRecord.intent.getComponent() != null) {
694 IIntentSender target = mService.getIntentSenderLocked(
695 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
696 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
697 new Intent[]{receiverRecord.intent},
698 new String[]{receiverRecord.intent.resolveType(mService.mContext
699 .getContentResolver())},
700 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
701 | PendingIntent.FLAG_IMMUTABLE, null);
702
703 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
704 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
705 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
706 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
707 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
708
709 if (DEBUG_PERMISSIONS_REVIEW) {
710 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
711 + receivingPackageName);
712 }
713
714 mHandler.post(new Runnable() {
715 @Override
716 public void run() {
717 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
718 }
719 });
720 } else {
721 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
722 + receivingPackageName + " requires a permissions review");
723 }
724
725 return false;
726 }
727
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700728 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700729 if (duration > Integer.MAX_VALUE) {
730 duration = Integer.MAX_VALUE;
731 }
732 // XXX ideally we should pause the broadcast until everything behind this is done,
733 // or else we will likely start dispatching the broadcast before we have opened
734 // access to the app (there is a lot of asynchronicity behind this). It is probably
735 // not that big a deal, however, because the main purpose here is to allow apps
736 // to hold wake locks, and they will be able to acquire their wake lock immediately
737 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700738 StringBuilder b = new StringBuilder();
739 b.append("broadcast:");
740 UserHandle.formatUid(b, r.callingUid);
741 b.append(":");
742 if (r.intent.getAction() != null) {
743 b.append(r.intent.getAction());
744 } else if (r.intent.getComponent() != null) {
745 b.append(r.intent.getComponent().flattenToShortString());
746 } else if (r.intent.getData() != null) {
747 b.append(r.intent.getData());
748 }
749 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
750 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700751 }
752
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800753 final void processNextBroadcast(boolean fromMsg) {
754 synchronized(mService) {
755 BroadcastRecord r;
756
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800757 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800758 + mQueueName + "]: "
759 + mParallelBroadcasts.size() + " broadcasts, "
760 + mOrderedBroadcasts.size() + " ordered broadcasts");
761
762 mService.updateCpuStats();
763
764 if (fromMsg) {
765 mBroadcastsScheduled = false;
766 }
767
768 // First, deliver any non-serialized broadcasts right away.
769 while (mParallelBroadcasts.size() > 0) {
770 r = mParallelBroadcasts.remove(0);
771 r.dispatchTime = SystemClock.uptimeMillis();
772 r.dispatchClockTime = System.currentTimeMillis();
773 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800774 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800775 + mQueueName + "] " + r);
776 for (int i=0; i<N; i++) {
777 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800778 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800779 "Delivering non-ordered on [" + mQueueName + "] to registered "
780 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800781 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800782 }
783 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800784 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800785 + mQueueName + "] " + r);
786 }
787
788 // Now take care of the next serialized one...
789
790 // If we are waiting for a process to come up to handle the next
791 // broadcast, then do nothing at this point. Just in case, we
792 // check that the process we're waiting for still exists.
793 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700794 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
795 "processNextBroadcast [" + mQueueName + "]: waiting for "
796 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800797
798 boolean isDead;
799 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700800 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
801 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800802 }
803 if (!isDead) {
804 // It's still alive, so keep waiting
805 return;
806 } else {
807 Slog.w(TAG, "pending app ["
808 + mQueueName + "]" + mPendingBroadcast.curApp
809 + " died before responding to broadcast");
810 mPendingBroadcast.state = BroadcastRecord.IDLE;
811 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
812 mPendingBroadcast = null;
813 }
814 }
815
816 boolean looped = false;
817
818 do {
819 if (mOrderedBroadcasts.size() == 0) {
820 // No more broadcasts pending, so all done!
821 mService.scheduleAppGcsLocked();
822 if (looped) {
823 // If we had finished the last ordered broadcast, then
824 // make sure all processes have correct oom and sched
825 // adjustments.
826 mService.updateOomAdjLocked();
827 }
828 return;
829 }
830 r = mOrderedBroadcasts.get(0);
831 boolean forceReceive = false;
832
833 // Ensure that even if something goes awry with the timeout
834 // detection, we catch "hung" broadcasts here, discard them,
835 // and continue to make progress.
836 //
837 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
838 // receivers don't get executed with timeouts. They're intended for
839 // one time heavy lifting after system upgrades and can take
840 // significant amounts of time.
841 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
842 if (mService.mProcessesReady && r.dispatchTime > 0) {
843 long now = SystemClock.uptimeMillis();
844 if ((numReceivers > 0) &&
845 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
846 Slog.w(TAG, "Hung broadcast ["
847 + mQueueName + "] discarded after timeout failure:"
848 + " now=" + now
849 + " dispatchTime=" + r.dispatchTime
850 + " startTime=" + r.receiverTime
851 + " intent=" + r.intent
852 + " numReceivers=" + numReceivers
853 + " nextReceiver=" + r.nextReceiver
854 + " state=" + r.state);
855 broadcastTimeoutLocked(false); // forcibly finish this broadcast
856 forceReceive = true;
857 r.state = BroadcastRecord.IDLE;
858 }
859 }
860
861 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800862 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800863 "processNextBroadcast("
864 + mQueueName + ") called when not idle (state="
865 + r.state + ")");
866 return;
867 }
868
869 if (r.receivers == null || r.nextReceiver >= numReceivers
870 || r.resultAbort || forceReceive) {
871 // No more receivers for this broadcast! Send the final
872 // result if requested...
873 if (r.resultTo != null) {
874 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800875 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800876 "Finishing broadcast [" + mQueueName + "] "
877 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800878 performReceiveLocked(r.callerApp, r.resultTo,
879 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700880 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800881 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700882 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800883 r.resultTo = null;
884 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000885 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800886 Slog.w(TAG, "Failure ["
887 + mQueueName + "] sending broadcast result of "
888 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700889
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800890 }
891 }
892
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800893 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800894 cancelBroadcastTimeoutLocked();
895
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700896 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
897 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800898
899 // ... and on to the next...
900 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700901 if (r.intent.getComponent() == null && r.intent.getPackage() == null
902 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
903 // This was an implicit broadcast... let's record it for posterity.
904 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
905 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
906 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800907 mOrderedBroadcasts.remove(0);
908 r = null;
909 looped = true;
910 continue;
911 }
912 } while (r == null);
913
914 // Get the next receiver...
915 int recIdx = r.nextReceiver++;
916
917 // Keep track of when this receiver started, and make sure there
918 // is a timeout message pending to kill it if need be.
919 r.receiverTime = SystemClock.uptimeMillis();
920 if (recIdx == 0) {
921 r.dispatchTime = r.receiverTime;
922 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800923 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800924 + mQueueName + "] " + r);
925 }
926 if (! mPendingBroadcastTimeoutMessage) {
927 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800928 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800929 "Submitting BROADCAST_TIMEOUT_MSG ["
930 + mQueueName + "] for " + r + " at " + timeoutTime);
931 setBroadcastTimeoutLocked(timeoutTime);
932 }
933
Dianne Hackborna750a632015-06-16 17:18:23 -0700934 final BroadcastOptions brOptions = r.options;
935 final Object nextReceiver = r.receivers.get(recIdx);
936
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800937 if (nextReceiver instanceof BroadcastFilter) {
938 // Simple case: this is a registered receiver who gets
939 // a direct call.
940 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800941 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800942 "Delivering ordered ["
943 + mQueueName + "] to registered "
944 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800945 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800946 if (r.receiver == null || !r.ordered) {
947 // The receiver has already finished, so schedule to
948 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800949 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800950 + mQueueName + "]: ordered="
951 + r.ordered + " receiver=" + r.receiver);
952 r.state = BroadcastRecord.IDLE;
953 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700954 } else {
955 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
956 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700957 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700958 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800959 }
960 return;
961 }
962
963 // Hard case: need to instantiate the receiver, possibly
964 // starting its application process to host it.
965
966 ResolveInfo info =
967 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700968 ComponentName component = new ComponentName(
969 info.activityInfo.applicationInfo.packageName,
970 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800971
972 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800973 if (brOptions != null &&
974 (info.activityInfo.applicationInfo.targetSdkVersion
975 < brOptions.getMinManifestReceiverApiLevel() ||
976 info.activityInfo.applicationInfo.targetSdkVersion
977 > brOptions.getMaxManifestReceiverApiLevel())) {
978 skip = true;
979 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800980 int perm = mService.checkComponentPermission(info.activityInfo.permission,
981 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
982 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800983 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800984 if (!info.activityInfo.exported) {
985 Slog.w(TAG, "Permission Denial: broadcasting "
986 + r.intent.toString()
987 + " from " + r.callerPackage + " (pid=" + r.callingPid
988 + ", uid=" + r.callingUid + ")"
989 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700990 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800991 } else {
992 Slog.w(TAG, "Permission Denial: broadcasting "
993 + r.intent.toString()
994 + " from " + r.callerPackage + " (pid=" + r.callingPid
995 + ", uid=" + r.callingUid + ")"
996 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700997 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800998 }
999 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001000 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001001 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1002 if (opCode != AppOpsManager.OP_NONE
1003 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1004 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1005 Slog.w(TAG, "Appop Denial: broadcasting "
1006 + r.intent.toString()
1007 + " from " + r.callerPackage + " (pid="
1008 + r.callingPid + ", uid=" + r.callingUid + ")"
1009 + " requires appop " + AppOpsManager.permissionToOp(
1010 info.activityInfo.permission)
1011 + " due to registered receiver "
1012 + component.flattenToShortString());
1013 skip = true;
1014 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001015 }
Svet Ganov99b60432015-06-27 13:15:22 -07001016 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001017 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1018 for (int i = 0; i < r.requiredPermissions.length; i++) {
1019 String requiredPermission = r.requiredPermissions[i];
1020 try {
1021 perm = AppGlobals.getPackageManager().
1022 checkPermission(requiredPermission,
1023 info.activityInfo.applicationInfo.packageName,
1024 UserHandle
1025 .getUserId(info.activityInfo.applicationInfo.uid));
1026 } catch (RemoteException e) {
1027 perm = PackageManager.PERMISSION_DENIED;
1028 }
1029 if (perm != PackageManager.PERMISSION_GRANTED) {
1030 Slog.w(TAG, "Permission Denial: receiving "
1031 + r.intent + " to "
1032 + component.flattenToShortString()
1033 + " requires " + requiredPermission
1034 + " due to sender " + r.callerPackage
1035 + " (uid " + r.callingUid + ")");
1036 skip = true;
1037 break;
1038 }
1039 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1040 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1041 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001042 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001043 != AppOpsManager.MODE_ALLOWED) {
1044 Slog.w(TAG, "Appop Denial: receiving "
1045 + r.intent + " to "
1046 + component.flattenToShortString()
1047 + " requires appop " + AppOpsManager.permissionToOp(
1048 requiredPermission)
1049 + " due to sender " + r.callerPackage
1050 + " (uid " + r.callingUid + ")");
1051 skip = true;
1052 break;
1053 }
1054 }
1055 }
1056 if (!skip && r.appOp != AppOpsManager.OP_NONE
1057 && mService.mAppOpsService.noteOperation(r.appOp,
1058 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1059 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001060 Slog.w(TAG, "Appop Denial: receiving "
1061 + r.intent + " to "
1062 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001063 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001064 + " due to sender " + r.callerPackage
1065 + " (uid " + r.callingUid + ")");
1066 skip = true;
1067 }
Ben Gruver49660c72013-08-06 19:54:08 -07001068 if (!skip) {
1069 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1070 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1071 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001072 boolean isSingleton = false;
1073 try {
1074 isSingleton = mService.isSingleton(info.activityInfo.processName,
1075 info.activityInfo.applicationInfo,
1076 info.activityInfo.name, info.activityInfo.flags);
1077 } catch (SecurityException e) {
1078 Slog.w(TAG, e.getMessage());
1079 skip = true;
1080 }
1081 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1082 if (ActivityManager.checkUidPermission(
1083 android.Manifest.permission.INTERACT_ACROSS_USERS,
1084 info.activityInfo.applicationInfo.uid)
1085 != PackageManager.PERMISSION_GRANTED) {
1086 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1087 + " requests FLAG_SINGLE_USER, but app does not hold "
1088 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1089 skip = true;
1090 }
1091 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001092 if (!skip) {
1093 r.manifestCount++;
1094 } else {
1095 r.manifestSkipCount++;
1096 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001097 if (r.curApp != null && r.curApp.crashing) {
1098 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001099 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1100 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001101 skip = true;
1102 }
Christopher Tateba629da2013-11-13 17:42:28 -08001103 if (!skip) {
1104 boolean isAvailable = false;
1105 try {
1106 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1107 info.activityInfo.packageName,
1108 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1109 } catch (Exception e) {
1110 // all such failures mean we skip this receiver
1111 Slog.w(TAG, "Exception getting recipient info for "
1112 + info.activityInfo.packageName, e);
1113 }
1114 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001115 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1116 "Skipping delivery to " + info.activityInfo.packageName + " / "
1117 + info.activityInfo.applicationInfo.uid
1118 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001119 skip = true;
1120 }
1121 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001122
Svet Ganov9c165d72015-12-01 19:52:26 -08001123 // If permissions need a review before any of the app components can run, we drop
1124 // the broadcast and if the calling app is in the foreground and the broadcast is
1125 // explicit we launch the review UI passing it a pending intent to send the skipped
1126 // broadcast.
1127 if (Build.PERMISSIONS_REVIEW_REQUIRED && !skip) {
1128 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1129 info.activityInfo.packageName, UserHandle.getUserId(
1130 info.activityInfo.applicationInfo.uid))) {
1131 skip = true;
1132 }
1133 }
1134
Dianne Hackborn76e80092015-12-09 14:15:34 -08001135 // This is safe to do even if we are skipping the broadcast, and we need
1136 // this information now to evaluate whether it is going to be allowed to run.
1137 final int receiverUid = info.activityInfo.applicationInfo.uid;
1138 // If it's a singleton, it needs to be the same app or a special app
1139 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1140 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1141 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1142 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001143 String targetProcess = info.activityInfo.processName;
1144 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1145 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001146
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001147 if (!skip) {
1148 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001149 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1150 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001151 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1152 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001153 // completely disabled from launches, or it was not explicitly sent
1154 // to it and the app is in a state that should not receive it
1155 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001156 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1157 Slog.w(TAG, "Background execution disabled: receiving "
1158 + r.intent + " to "
1159 + component.flattenToShortString());
1160 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001161 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001162 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001163 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001164 && ((r.intent.getFlags()
1165 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001166 Slog.w(TAG, "Background execution not allowed: receiving "
1167 + r.intent + " to "
1168 + component.flattenToShortString());
1169 skip = true;
1170 }
1171 }
1172 }
1173
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001174 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001175 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001176 "Skipping delivery of ordered [" + mQueueName + "] "
1177 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001178 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001179 r.receiver = null;
1180 r.curFilter = null;
1181 r.state = BroadcastRecord.IDLE;
1182 scheduleBroadcastsLocked();
1183 return;
1184 }
1185
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001186 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001187 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001188 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001189 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001190 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001191 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1192 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1193 + info.activityInfo.applicationInfo.uid);
1194 }
1195
Dianne Hackborna750a632015-06-16 17:18:23 -07001196 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1197 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001198 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001199 }
1200
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001201 // Broadcast is being executed, its package can't be stopped.
1202 try {
1203 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001204 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001205 } catch (RemoteException e) {
1206 } catch (IllegalArgumentException e) {
1207 Slog.w(TAG, "Failed trying to unstop package "
1208 + r.curComponent.getPackageName() + ": " + e);
1209 }
1210
1211 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001212 if (app != null && app.thread != null) {
1213 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001214 app.addPackage(info.activityInfo.packageName,
1215 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001216 processCurBroadcastLocked(r, app);
1217 return;
1218 } catch (RemoteException e) {
1219 Slog.w(TAG, "Exception when sending broadcast to "
1220 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001221 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001222 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001223 + r.curComponent + " with " + r.intent, e);
1224 // If some unexpected exception happened, just skip
1225 // this broadcast. At this point we are not in the call
1226 // from a client, so throwing an exception out from here
1227 // will crash the entire system instead of just whoever
1228 // sent the broadcast.
1229 logBroadcastReceiverDiscardLocked(r);
1230 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001231 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001232 scheduleBroadcastsLocked();
1233 // We need to reset the state if we failed to start the receiver.
1234 r.state = BroadcastRecord.IDLE;
1235 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001236 }
1237
1238 // If a dead object exception was thrown -- fall through to
1239 // restart the application.
1240 }
1241
1242 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001243 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001244 "Need to start app ["
1245 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1246 if ((r.curApp=mService.startProcessLocked(targetProcess,
1247 info.activityInfo.applicationInfo, true,
1248 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1249 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001250 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001251 == null) {
1252 // Ah, this recipient is unavailable. Finish it if necessary,
1253 // and mark the broadcast record as ready for the next.
1254 Slog.w(TAG, "Unable to launch app "
1255 + info.activityInfo.applicationInfo.packageName + "/"
1256 + info.activityInfo.applicationInfo.uid + " for broadcast "
1257 + r.intent + ": process is bad");
1258 logBroadcastReceiverDiscardLocked(r);
1259 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001260 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001261 scheduleBroadcastsLocked();
1262 r.state = BroadcastRecord.IDLE;
1263 return;
1264 }
1265
1266 mPendingBroadcast = r;
1267 mPendingBroadcastRecvIndex = recIdx;
1268 }
1269 }
1270
1271 final void setBroadcastTimeoutLocked(long timeoutTime) {
1272 if (! mPendingBroadcastTimeoutMessage) {
1273 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1274 mHandler.sendMessageAtTime(msg, timeoutTime);
1275 mPendingBroadcastTimeoutMessage = true;
1276 }
1277 }
1278
1279 final void cancelBroadcastTimeoutLocked() {
1280 if (mPendingBroadcastTimeoutMessage) {
1281 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1282 mPendingBroadcastTimeoutMessage = false;
1283 }
1284 }
1285
1286 final void broadcastTimeoutLocked(boolean fromMsg) {
1287 if (fromMsg) {
1288 mPendingBroadcastTimeoutMessage = false;
1289 }
1290
1291 if (mOrderedBroadcasts.size() == 0) {
1292 return;
1293 }
1294
1295 long now = SystemClock.uptimeMillis();
1296 BroadcastRecord r = mOrderedBroadcasts.get(0);
1297 if (fromMsg) {
1298 if (mService.mDidDexOpt) {
1299 // Delay timeouts until dexopt finishes.
1300 mService.mDidDexOpt = false;
1301 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1302 setBroadcastTimeoutLocked(timeoutTime);
1303 return;
1304 }
1305 if (!mService.mProcessesReady) {
1306 // Only process broadcast timeouts if the system is ready. That way
1307 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1308 // to do heavy lifting for system up.
1309 return;
1310 }
1311
1312 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1313 if (timeoutTime > now) {
1314 // We can observe premature timeouts because we do not cancel and reset the
1315 // broadcast timeout message after each receiver finishes. Instead, we set up
1316 // an initial timeout then kick it down the road a little further as needed
1317 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001318 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001319 "Premature timeout ["
1320 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1321 + timeoutTime);
1322 setBroadcastTimeoutLocked(timeoutTime);
1323 return;
1324 }
1325 }
1326
Dianne Hackborn6285a322013-09-18 12:09:47 -07001327 BroadcastRecord br = mOrderedBroadcasts.get(0);
1328 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1329 // In this case the broadcast had already finished, but we had decided to wait
1330 // for started services to finish as well before going on. So if we have actually
1331 // waited long enough time timeout the broadcast, let's give up on the whole thing
1332 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001333 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001334 ? br.curComponent.flattenToShortString() : "(null)"));
1335 br.curComponent = null;
1336 br.state = BroadcastRecord.IDLE;
1337 processNextBroadcast(false);
1338 return;
1339 }
1340
1341 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001342 + ", started " + (now - r.receiverTime) + "ms ago");
1343 r.receiverTime = now;
1344 r.anrCount++;
1345
1346 // Current receiver has passed its expiration date.
1347 if (r.nextReceiver <= 0) {
1348 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1349 return;
1350 }
1351
1352 ProcessRecord app = null;
1353 String anrMessage = null;
1354
1355 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001356 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001357 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1358 logBroadcastReceiverDiscardLocked(r);
1359 if (curReceiver instanceof BroadcastFilter) {
1360 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1361 if (bf.receiverList.pid != 0
1362 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1363 synchronized (mService.mPidsSelfLocked) {
1364 app = mService.mPidsSelfLocked.get(
1365 bf.receiverList.pid);
1366 }
1367 }
1368 } else {
1369 app = r.curApp;
1370 }
1371
1372 if (app != null) {
1373 anrMessage = "Broadcast of " + r.intent.toString();
1374 }
1375
1376 if (mPendingBroadcast == r) {
1377 mPendingBroadcast = null;
1378 }
1379
1380 // Move on to the next receiver.
1381 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001382 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001383 scheduleBroadcastsLocked();
1384
1385 if (anrMessage != null) {
1386 // Post the ANR to the handler since we do not want to process ANRs while
1387 // potentially holding our lock.
1388 mHandler.post(new AppNotResponding(app, anrMessage));
1389 }
1390 }
1391
Christopher Tatef278f122015-04-22 13:12:01 -07001392 private final int ringAdvance(int x, final int increment, final int ringSize) {
1393 x += increment;
1394 if (x < 0) return (ringSize - 1);
1395 else if (x >= ringSize) return 0;
1396 else return x;
1397 }
1398
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001399 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1400 if (r.callingUid < 0) {
1401 // This was from a registerReceiver() call; ignore it.
1402 return;
1403 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001404 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001405
1406 mBroadcastHistory[mHistoryNext] = r;
1407 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1408
1409 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1410 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1411 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1412 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1413 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001414 }
1415
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001416 boolean cleanupDisabledPackageReceiversLocked(
1417 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1418 boolean didSomething = false;
1419 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1420 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1421 packageName, filterByClasses, userId, doit);
1422 if (!doit && didSomething) {
1423 return true;
1424 }
1425 }
1426
1427 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1428 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1429 packageName, filterByClasses, userId, doit);
1430 if (!doit && didSomething) {
1431 return true;
1432 }
1433 }
1434
1435 return didSomething;
1436 }
1437
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001438 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001439 final int logIndex = r.nextReceiver - 1;
1440 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1441 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001442 if (curReceiver instanceof BroadcastFilter) {
1443 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1444 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001445 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001446 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001447 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001448 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001449 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001450 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001451 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001452 }
1453 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001454 if (logIndex < 0) Slog.w(TAG,
1455 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001456 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001457 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001458 r.intent.getAction(),
1459 r.nextReceiver,
1460 "NONE");
1461 }
1462 }
1463
1464 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1465 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001466 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001467 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1468 || mPendingBroadcast != null) {
1469 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001470 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001471 BroadcastRecord br = mParallelBroadcasts.get(i);
1472 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1473 continue;
1474 }
1475 if (!printed) {
1476 if (needSep) {
1477 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001478 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001479 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001480 printed = true;
1481 pw.println(" Active broadcasts [" + mQueueName + "]:");
1482 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001483 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001484 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001485 }
1486 printed = false;
1487 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001488 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001489 BroadcastRecord br = mOrderedBroadcasts.get(i);
1490 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1491 continue;
1492 }
1493 if (!printed) {
1494 if (needSep) {
1495 pw.println();
1496 }
1497 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001498 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001499 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1500 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001501 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001502 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001503 }
1504 if (dumpPackage == null || (mPendingBroadcast != null
1505 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1506 if (needSep) {
1507 pw.println();
1508 }
1509 pw.println(" Pending broadcast [" + mQueueName + "]:");
1510 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001511 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001512 } else {
1513 pw.println(" (null)");
1514 }
1515 needSep = true;
1516 }
1517 }
1518
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001519 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001520 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001521
1522 i = -1;
1523 int lastIndex = mHistoryNext;
1524 int ringIndex = lastIndex;
1525 do {
1526 // increasing index = more recent entry, and we want to print the most
1527 // recent first and work backwards, so we roll through the ring backwards.
1528 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1529 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001530 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001531 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001532 }
Christopher Tatef278f122015-04-22 13:12:01 -07001533
1534 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001535 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1536 continue;
1537 }
1538 if (!printed) {
1539 if (needSep) {
1540 pw.println();
1541 }
1542 needSep = true;
1543 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1544 printed = true;
1545 }
1546 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001547 pw.print(" Historical Broadcast " + mQueueName + " #");
1548 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001549 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001550 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001551 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1552 pw.print(" ");
1553 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001554 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1555 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1556 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001557 Bundle bundle = r.intent.getExtras();
1558 if (bundle != null) {
1559 pw.print(" extras: "); pw.println(bundle.toString());
1560 }
1561 }
Christopher Tatef278f122015-04-22 13:12:01 -07001562 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001563
1564 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001565 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001566 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001567 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001568 i = -1;
1569 } else {
1570 // roll over the 'i' full dumps that have already been issued
1571 for (int j = i;
1572 j > 0 && ringIndex != lastIndex;) {
1573 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1574 BroadcastRecord r = mBroadcastHistory[ringIndex];
1575 if (r == null) {
1576 continue;
1577 }
1578 j--;
1579 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001580 }
Christopher Tatef278f122015-04-22 13:12:01 -07001581 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1582 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001583 do {
1584 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1585 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001586 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001587 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001588 }
1589 if (!printed) {
1590 if (needSep) {
1591 pw.println();
1592 }
1593 needSep = true;
1594 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1595 printed = true;
1596 }
1597 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001598 pw.println(" ...");
1599 break;
1600 }
Christopher Tatef278f122015-04-22 13:12:01 -07001601 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001602 pw.print(" #"); pw.print(i); pw.print(": ");
1603 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001604 pw.print(" ");
1605 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1606 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1607 pw.print(" dispatch ");
1608 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1609 - mSummaryHistoryDispatchTime[ringIndex], pw);
1610 pw.println(" finish");
1611 pw.print(" enq=");
1612 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1613 pw.print(" disp=");
1614 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1615 pw.print(" fin=");
1616 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001617 Bundle bundle = intent.getExtras();
1618 if (bundle != null) {
1619 pw.print(" extras: "); pw.println(bundle.toString());
1620 }
Christopher Tatef278f122015-04-22 13:12:01 -07001621 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001622 }
1623
1624 return needSep;
1625 }
1626}