blob: f78f29c4ac6dc82dce0f5645bfc7eeee7780bec3 [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) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700305 if (br.curApp != app) {
306 Slog.e(TAG, "App mismatch when sending pending broadcast to "
307 + app.processName + ", intended target is " + br.curApp.processName);
308 return false;
309 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800310 try {
311 mPendingBroadcast = null;
312 processCurBroadcastLocked(br, app);
313 didSomething = true;
314 } catch (Exception e) {
315 Slog.w(TAG, "Exception in new application when starting receiver "
316 + br.curComponent.flattenToShortString(), e);
317 logBroadcastReceiverDiscardLocked(br);
318 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700319 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800320 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700321 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800322 br.state = BroadcastRecord.IDLE;
323 throw new RuntimeException(e.getMessage());
324 }
325 }
326 return didSomething;
327 }
328
329 public void skipPendingBroadcastLocked(int pid) {
330 final BroadcastRecord br = mPendingBroadcast;
331 if (br != null && br.curApp.pid == pid) {
332 br.state = BroadcastRecord.IDLE;
333 br.nextReceiver = mPendingBroadcastRecvIndex;
334 mPendingBroadcast = null;
335 scheduleBroadcastsLocked();
336 }
337 }
338
339 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700340 BroadcastRecord r = null;
341 if (mOrderedBroadcasts.size() > 0) {
342 BroadcastRecord br = mOrderedBroadcasts.get(0);
343 if (br.curApp == app) {
344 r = br;
345 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800346 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800347 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800348 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800349 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800350 r = mPendingBroadcast;
351 }
352
353 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700354 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800355 }
356 }
357
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700358 private void skipReceiverLocked(BroadcastRecord r) {
359 logBroadcastReceiverDiscardLocked(r);
360 finishReceiverLocked(r, r.resultCode, r.resultData,
361 r.resultExtras, r.resultAbort, false);
362 scheduleBroadcastsLocked();
363 }
364
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800365 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800366 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800367 + mQueueName + "]: current="
368 + mBroadcastsScheduled);
369
370 if (mBroadcastsScheduled) {
371 return;
372 }
373 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
374 mBroadcastsScheduled = true;
375 }
376
377 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
378 if (mOrderedBroadcasts.size() > 0) {
379 final BroadcastRecord r = mOrderedBroadcasts.get(0);
380 if (r != null && r.receiver == receiver) {
381 return r;
382 }
383 }
384 return null;
385 }
386
387 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700388 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
389 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700390 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800391 r.state = BroadcastRecord.IDLE;
392 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700393 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800394 }
395 r.receiver = null;
396 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800397 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800398 r.curApp.curReceiver = null;
399 }
400 if (r.curFilter != null) {
401 r.curFilter.receiverList.curBroadcast = null;
402 }
403 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800404 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700405 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800406 mPendingBroadcast = null;
407
408 r.resultCode = resultCode;
409 r.resultData = resultData;
410 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700411 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
412 r.resultAbort = resultAbort;
413 } else {
414 r.resultAbort = false;
415 }
416
417 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
418 && r.queue.mOrderedBroadcasts.size() > 0
419 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700420 ActivityInfo nextReceiver;
421 if (r.nextReceiver < r.receivers.size()) {
422 Object obj = r.receivers.get(r.nextReceiver);
423 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
424 } else {
425 nextReceiver = null;
426 }
427 // Don't do this if the next receive is in the same process as the current one.
428 if (receiver == null || nextReceiver == null
429 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
430 || !receiver.processName.equals(nextReceiver.processName)) {
431 // In this case, we are ready to process the next receiver for the current broadcast,
432 // but are on a queue that would like to wait for services to finish before moving
433 // on. If there are background services currently starting, then we will go into a
434 // special state where we hold off on continuing this broadcast until they are done.
435 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800436 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700437 r.state = BroadcastRecord.WAITING_SERVICES;
438 return false;
439 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700440 }
441 }
442
443 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800444
445 // We will process the next receiver right now if this is finishing
446 // an app receiver (which is always asynchronous) or after we have
447 // come back from calling a receiver.
448 return state == BroadcastRecord.APP_RECEIVE
449 || state == BroadcastRecord.CALL_DONE_RECEIVE;
450 }
451
Dianne Hackborn6285a322013-09-18 12:09:47 -0700452 public void backgroundServicesFinishedLocked(int userId) {
453 if (mOrderedBroadcasts.size() > 0) {
454 BroadcastRecord br = mOrderedBroadcasts.get(0);
455 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800456 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700457 br.curComponent = null;
458 br.state = BroadcastRecord.IDLE;
459 processNextBroadcast(false);
460 }
461 }
462 }
463
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700464 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800465 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700466 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800467 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000468 if (app != null) {
469 if (app.thread != null) {
470 // If we have an app thread, do the call through that so it is
471 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700472 try {
473 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
474 data, extras, ordered, sticky, sendingUser, app.repProcState);
475 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
476 // DeadObjectException when the process isn't actually dead.
477 //} catch (DeadObjectException ex) {
478 // Failed to call into the process. It's dying so just let it die and move on.
479 // throw ex;
480 } catch (RemoteException ex) {
481 // Failed to call into the process. It's either dying or wedged. Kill it gently.
482 synchronized (mService) {
483 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
484 + " (pid " + app.pid + "). Crashing it.");
485 app.scheduleCrash("can't deliver broadcast");
486 }
487 throw ex;
488 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000489 } else {
490 // Application has died. Receiver doesn't exist.
491 throw new RemoteException("app.thread must not be null");
492 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800493 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700494 receiver.performReceive(intent, resultCode, data, extras, ordered,
495 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800496 }
497 }
498
Svet Ganov99b60432015-06-27 13:15:22 -0700499 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800500 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800501 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700502 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800503 int perm = mService.checkComponentPermission(filter.requiredPermission,
504 r.callingPid, r.callingUid, -1, true);
505 if (perm != PackageManager.PERMISSION_GRANTED) {
506 Slog.w(TAG, "Permission Denial: broadcasting "
507 + r.intent.toString()
508 + " from " + r.callerPackage + " (pid="
509 + r.callingPid + ", uid=" + r.callingUid + ")"
510 + " requires " + filter.requiredPermission
511 + " due to registered receiver " + filter);
512 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700513 } else {
514 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
515 if (opCode != AppOpsManager.OP_NONE
516 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
517 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
518 Slog.w(TAG, "Appop Denial: broadcasting "
519 + r.intent.toString()
520 + " from " + r.callerPackage + " (pid="
521 + r.callingPid + ", uid=" + r.callingUid + ")"
522 + " requires appop " + AppOpsManager.permissionToOp(
523 filter.requiredPermission)
524 + " due to registered receiver " + filter);
525 skip = true;
526 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800527 }
528 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700529 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
530 for (int i = 0; i < r.requiredPermissions.length; i++) {
531 String requiredPermission = r.requiredPermissions[i];
532 int perm = mService.checkComponentPermission(requiredPermission,
533 filter.receiverList.pid, filter.receiverList.uid, -1, true);
534 if (perm != PackageManager.PERMISSION_GRANTED) {
535 Slog.w(TAG, "Permission Denial: receiving "
536 + r.intent.toString()
537 + " to " + filter.receiverList.app
538 + " (pid=" + filter.receiverList.pid
539 + ", uid=" + filter.receiverList.uid + ")"
540 + " requires " + requiredPermission
541 + " due to sender " + r.callerPackage
542 + " (uid " + r.callingUid + ")");
543 skip = true;
544 break;
545 }
546 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700547 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700548 && mService.mAppOpsService.noteOperation(appOp,
549 filter.receiverList.uid, filter.packageName)
550 != AppOpsManager.MODE_ALLOWED) {
551 Slog.w(TAG, "Appop Denial: receiving "
552 + r.intent.toString()
553 + " to " + filter.receiverList.app
554 + " (pid=" + filter.receiverList.pid
555 + ", uid=" + filter.receiverList.uid + ")"
556 + " requires appop " + AppOpsManager.permissionToOp(
557 requiredPermission)
558 + " due to sender " + r.callerPackage
559 + " (uid " + r.callingUid + ")");
560 skip = true;
561 break;
562 }
563 }
564 }
565 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
566 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000567 filter.receiverList.pid, filter.receiverList.uid, -1, true);
568 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700569 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000570 + r.intent.toString()
571 + " to " + filter.receiverList.app
572 + " (pid=" + filter.receiverList.pid
573 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000574 + " due to sender " + r.callerPackage
575 + " (uid " + r.callingUid + ")");
576 skip = true;
577 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700578 }
579 if (!skip && r.appOp != AppOpsManager.OP_NONE
580 && mService.mAppOpsService.noteOperation(r.appOp,
581 filter.receiverList.uid, filter.packageName)
582 != AppOpsManager.MODE_ALLOWED) {
583 Slog.w(TAG, "Appop Denial: receiving "
584 + r.intent.toString()
585 + " to " + filter.receiverList.app
586 + " (pid=" + filter.receiverList.pid
587 + ", uid=" + filter.receiverList.uid + ")"
588 + " requires appop " + AppOpsManager.opToName(r.appOp)
589 + " due to sender " + r.callerPackage
590 + " (uid " + r.callingUid + ")");
591 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700592 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700593 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800594 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700595 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800596 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700597 Slog.w(TAG, "Background execution not allowed: receiving "
598 + r.intent
599 + " to " + filter.receiverList.app
600 + " (pid=" + filter.receiverList.pid
601 + ", uid=" + filter.receiverList.uid + ")");
602 skip = true;
603 }
604 }
Svet Ganov99b60432015-06-27 13:15:22 -0700605
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700606 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
607 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800608 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700609 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800610
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800611 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700612 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
613 + " to " + filter.receiverList + ": process crashing");
614 skip = true;
615 }
616
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800617 if (skip) {
618 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
619 return;
620 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800621
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800622 // If permissions need a review before any of the app components can run, we drop
623 // the broadcast and if the calling app is in the foreground and the broadcast is
624 // explicit we launch the review UI passing it a pending intent to send the skipped
625 // broadcast.
626 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
627 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
628 filter.owningUserId)) {
629 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
630 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800631 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800632 }
633
634 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
635
636 // If this is not being sent as an ordered broadcast, then we
637 // don't want to touch the fields that keep track of the current
638 // state of ordered broadcasts.
639 if (ordered) {
640 r.receiver = filter.receiverList.receiver.asBinder();
641 r.curFilter = filter;
642 filter.receiverList.curBroadcast = r;
643 r.state = BroadcastRecord.CALL_IN_RECEIVE;
644 if (filter.receiverList.app != null) {
645 // Bump hosting application to no longer be in background
646 // scheduling class. Note that we can't do that if there
647 // isn't an app... but we can only be in that case for
648 // things that directly call the IActivityManager API, which
649 // are already core system stuff so don't matter for this.
650 r.curApp = filter.receiverList.app;
651 filter.receiverList.app.curReceiver = r;
652 mService.updateOomAdjLocked(r.curApp);
653 }
654 }
655 try {
656 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
657 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700658 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
659 // Skip delivery if full backup in progress
660 // If it's an ordered broadcast, we need to continue to the next receiver.
661 if (ordered) {
662 skipReceiverLocked(r);
663 }
664 } else {
665 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
666 new Intent(r.intent), r.resultCode, r.resultData,
667 r.resultExtras, r.ordered, r.initialSticky, r.userId);
668 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800669 if (ordered) {
670 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
671 }
672 } catch (RemoteException e) {
673 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
674 if (ordered) {
675 r.receiver = null;
676 r.curFilter = null;
677 filter.receiverList.curBroadcast = null;
678 if (filter.receiverList.app != null) {
679 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800680 }
681 }
682 }
683 }
684
Svet Ganov9c165d72015-12-01 19:52:26 -0800685 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
686 BroadcastRecord receiverRecord, String receivingPackageName,
687 final int receivingUserId) {
688 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
689 receivingPackageName, receivingUserId)) {
690 return true;
691 }
692
693 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800694 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800695 : true;
696
697 // Show a permission review UI only for explicit broadcast from a foreground app
698 if (callerForeground && receiverRecord.intent.getComponent() != null) {
699 IIntentSender target = mService.getIntentSenderLocked(
700 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
701 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
702 new Intent[]{receiverRecord.intent},
703 new String[]{receiverRecord.intent.resolveType(mService.mContext
704 .getContentResolver())},
705 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
706 | PendingIntent.FLAG_IMMUTABLE, null);
707
708 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
709 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
710 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
711 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
712 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
713
714 if (DEBUG_PERMISSIONS_REVIEW) {
715 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
716 + receivingPackageName);
717 }
718
719 mHandler.post(new Runnable() {
720 @Override
721 public void run() {
722 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
723 }
724 });
725 } else {
726 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
727 + receivingPackageName + " requires a permissions review");
728 }
729
730 return false;
731 }
732
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700733 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700734 if (duration > Integer.MAX_VALUE) {
735 duration = Integer.MAX_VALUE;
736 }
737 // XXX ideally we should pause the broadcast until everything behind this is done,
738 // or else we will likely start dispatching the broadcast before we have opened
739 // access to the app (there is a lot of asynchronicity behind this). It is probably
740 // not that big a deal, however, because the main purpose here is to allow apps
741 // to hold wake locks, and they will be able to acquire their wake lock immediately
742 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700743 StringBuilder b = new StringBuilder();
744 b.append("broadcast:");
745 UserHandle.formatUid(b, r.callingUid);
746 b.append(":");
747 if (r.intent.getAction() != null) {
748 b.append(r.intent.getAction());
749 } else if (r.intent.getComponent() != null) {
750 b.append(r.intent.getComponent().flattenToShortString());
751 } else if (r.intent.getData() != null) {
752 b.append(r.intent.getData());
753 }
754 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
755 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700756 }
757
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800758 final void processNextBroadcast(boolean fromMsg) {
759 synchronized(mService) {
760 BroadcastRecord r;
761
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800762 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800763 + mQueueName + "]: "
764 + mParallelBroadcasts.size() + " broadcasts, "
765 + mOrderedBroadcasts.size() + " ordered broadcasts");
766
767 mService.updateCpuStats();
768
769 if (fromMsg) {
770 mBroadcastsScheduled = false;
771 }
772
773 // First, deliver any non-serialized broadcasts right away.
774 while (mParallelBroadcasts.size() > 0) {
775 r = mParallelBroadcasts.remove(0);
776 r.dispatchTime = SystemClock.uptimeMillis();
777 r.dispatchClockTime = System.currentTimeMillis();
778 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800779 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800780 + mQueueName + "] " + r);
781 for (int i=0; i<N; i++) {
782 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800783 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800784 "Delivering non-ordered on [" + mQueueName + "] to registered "
785 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800786 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800787 }
788 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800789 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800790 + mQueueName + "] " + r);
791 }
792
793 // Now take care of the next serialized one...
794
795 // If we are waiting for a process to come up to handle the next
796 // broadcast, then do nothing at this point. Just in case, we
797 // check that the process we're waiting for still exists.
798 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700799 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
800 "processNextBroadcast [" + mQueueName + "]: waiting for "
801 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800802
803 boolean isDead;
804 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700805 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
806 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800807 }
808 if (!isDead) {
809 // It's still alive, so keep waiting
810 return;
811 } else {
812 Slog.w(TAG, "pending app ["
813 + mQueueName + "]" + mPendingBroadcast.curApp
814 + " died before responding to broadcast");
815 mPendingBroadcast.state = BroadcastRecord.IDLE;
816 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
817 mPendingBroadcast = null;
818 }
819 }
820
821 boolean looped = false;
822
823 do {
824 if (mOrderedBroadcasts.size() == 0) {
825 // No more broadcasts pending, so all done!
826 mService.scheduleAppGcsLocked();
827 if (looped) {
828 // If we had finished the last ordered broadcast, then
829 // make sure all processes have correct oom and sched
830 // adjustments.
831 mService.updateOomAdjLocked();
832 }
833 return;
834 }
835 r = mOrderedBroadcasts.get(0);
836 boolean forceReceive = false;
837
838 // Ensure that even if something goes awry with the timeout
839 // detection, we catch "hung" broadcasts here, discard them,
840 // and continue to make progress.
841 //
842 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
843 // receivers don't get executed with timeouts. They're intended for
844 // one time heavy lifting after system upgrades and can take
845 // significant amounts of time.
846 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
847 if (mService.mProcessesReady && r.dispatchTime > 0) {
848 long now = SystemClock.uptimeMillis();
849 if ((numReceivers > 0) &&
850 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
851 Slog.w(TAG, "Hung broadcast ["
852 + mQueueName + "] discarded after timeout failure:"
853 + " now=" + now
854 + " dispatchTime=" + r.dispatchTime
855 + " startTime=" + r.receiverTime
856 + " intent=" + r.intent
857 + " numReceivers=" + numReceivers
858 + " nextReceiver=" + r.nextReceiver
859 + " state=" + r.state);
860 broadcastTimeoutLocked(false); // forcibly finish this broadcast
861 forceReceive = true;
862 r.state = BroadcastRecord.IDLE;
863 }
864 }
865
866 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800867 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800868 "processNextBroadcast("
869 + mQueueName + ") called when not idle (state="
870 + r.state + ")");
871 return;
872 }
873
874 if (r.receivers == null || r.nextReceiver >= numReceivers
875 || r.resultAbort || forceReceive) {
876 // No more receivers for this broadcast! Send the final
877 // result if requested...
878 if (r.resultTo != null) {
879 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800880 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800881 "Finishing broadcast [" + mQueueName + "] "
882 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800883 performReceiveLocked(r.callerApp, r.resultTo,
884 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700885 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800886 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700887 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800888 r.resultTo = null;
889 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000890 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800891 Slog.w(TAG, "Failure ["
892 + mQueueName + "] sending broadcast result of "
893 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700894
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800895 }
896 }
897
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800898 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800899 cancelBroadcastTimeoutLocked();
900
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700901 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
902 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800903
904 // ... and on to the next...
905 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700906 if (r.intent.getComponent() == null && r.intent.getPackage() == null
907 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
908 // This was an implicit broadcast... let's record it for posterity.
909 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
910 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
911 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800912 mOrderedBroadcasts.remove(0);
913 r = null;
914 looped = true;
915 continue;
916 }
917 } while (r == null);
918
919 // Get the next receiver...
920 int recIdx = r.nextReceiver++;
921
922 // Keep track of when this receiver started, and make sure there
923 // is a timeout message pending to kill it if need be.
924 r.receiverTime = SystemClock.uptimeMillis();
925 if (recIdx == 0) {
926 r.dispatchTime = r.receiverTime;
927 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800928 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800929 + mQueueName + "] " + r);
930 }
931 if (! mPendingBroadcastTimeoutMessage) {
932 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800933 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800934 "Submitting BROADCAST_TIMEOUT_MSG ["
935 + mQueueName + "] for " + r + " at " + timeoutTime);
936 setBroadcastTimeoutLocked(timeoutTime);
937 }
938
Dianne Hackborna750a632015-06-16 17:18:23 -0700939 final BroadcastOptions brOptions = r.options;
940 final Object nextReceiver = r.receivers.get(recIdx);
941
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800942 if (nextReceiver instanceof BroadcastFilter) {
943 // Simple case: this is a registered receiver who gets
944 // a direct call.
945 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800946 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800947 "Delivering ordered ["
948 + mQueueName + "] to registered "
949 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800950 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800951 if (r.receiver == null || !r.ordered) {
952 // The receiver has already finished, so schedule to
953 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800954 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800955 + mQueueName + "]: ordered="
956 + r.ordered + " receiver=" + r.receiver);
957 r.state = BroadcastRecord.IDLE;
958 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700959 } else {
960 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
961 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700963 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800964 }
965 return;
966 }
967
968 // Hard case: need to instantiate the receiver, possibly
969 // starting its application process to host it.
970
971 ResolveInfo info =
972 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700973 ComponentName component = new ComponentName(
974 info.activityInfo.applicationInfo.packageName,
975 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800976
977 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800978 if (brOptions != null &&
979 (info.activityInfo.applicationInfo.targetSdkVersion
980 < brOptions.getMinManifestReceiverApiLevel() ||
981 info.activityInfo.applicationInfo.targetSdkVersion
982 > brOptions.getMaxManifestReceiverApiLevel())) {
983 skip = true;
984 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800985 int perm = mService.checkComponentPermission(info.activityInfo.permission,
986 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
987 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800988 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800989 if (!info.activityInfo.exported) {
990 Slog.w(TAG, "Permission Denial: broadcasting "
991 + r.intent.toString()
992 + " from " + r.callerPackage + " (pid=" + r.callingPid
993 + ", uid=" + r.callingUid + ")"
994 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700995 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800996 } else {
997 Slog.w(TAG, "Permission Denial: broadcasting "
998 + r.intent.toString()
999 + " from " + r.callerPackage + " (pid=" + r.callingPid
1000 + ", uid=" + r.callingUid + ")"
1001 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001002 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001003 }
1004 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001005 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001006 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1007 if (opCode != AppOpsManager.OP_NONE
1008 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1009 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1010 Slog.w(TAG, "Appop Denial: broadcasting "
1011 + r.intent.toString()
1012 + " from " + r.callerPackage + " (pid="
1013 + r.callingPid + ", uid=" + r.callingUid + ")"
1014 + " requires appop " + AppOpsManager.permissionToOp(
1015 info.activityInfo.permission)
1016 + " due to registered receiver "
1017 + component.flattenToShortString());
1018 skip = true;
1019 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001020 }
Svet Ganov99b60432015-06-27 13:15:22 -07001021 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001022 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1023 for (int i = 0; i < r.requiredPermissions.length; i++) {
1024 String requiredPermission = r.requiredPermissions[i];
1025 try {
1026 perm = AppGlobals.getPackageManager().
1027 checkPermission(requiredPermission,
1028 info.activityInfo.applicationInfo.packageName,
1029 UserHandle
1030 .getUserId(info.activityInfo.applicationInfo.uid));
1031 } catch (RemoteException e) {
1032 perm = PackageManager.PERMISSION_DENIED;
1033 }
1034 if (perm != PackageManager.PERMISSION_GRANTED) {
1035 Slog.w(TAG, "Permission Denial: receiving "
1036 + r.intent + " to "
1037 + component.flattenToShortString()
1038 + " requires " + requiredPermission
1039 + " due to sender " + r.callerPackage
1040 + " (uid " + r.callingUid + ")");
1041 skip = true;
1042 break;
1043 }
1044 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1045 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1046 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001047 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001048 != AppOpsManager.MODE_ALLOWED) {
1049 Slog.w(TAG, "Appop Denial: receiving "
1050 + r.intent + " to "
1051 + component.flattenToShortString()
1052 + " requires appop " + AppOpsManager.permissionToOp(
1053 requiredPermission)
1054 + " due to sender " + r.callerPackage
1055 + " (uid " + r.callingUid + ")");
1056 skip = true;
1057 break;
1058 }
1059 }
1060 }
1061 if (!skip && r.appOp != AppOpsManager.OP_NONE
1062 && mService.mAppOpsService.noteOperation(r.appOp,
1063 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1064 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001065 Slog.w(TAG, "Appop Denial: receiving "
1066 + r.intent + " to "
1067 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001068 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001069 + " due to sender " + r.callerPackage
1070 + " (uid " + r.callingUid + ")");
1071 skip = true;
1072 }
Ben Gruver49660c72013-08-06 19:54:08 -07001073 if (!skip) {
1074 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1075 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1076 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001077 boolean isSingleton = false;
1078 try {
1079 isSingleton = mService.isSingleton(info.activityInfo.processName,
1080 info.activityInfo.applicationInfo,
1081 info.activityInfo.name, info.activityInfo.flags);
1082 } catch (SecurityException e) {
1083 Slog.w(TAG, e.getMessage());
1084 skip = true;
1085 }
1086 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1087 if (ActivityManager.checkUidPermission(
1088 android.Manifest.permission.INTERACT_ACROSS_USERS,
1089 info.activityInfo.applicationInfo.uid)
1090 != PackageManager.PERMISSION_GRANTED) {
1091 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1092 + " requests FLAG_SINGLE_USER, but app does not hold "
1093 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1094 skip = true;
1095 }
1096 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001097 if (!skip) {
1098 r.manifestCount++;
1099 } else {
1100 r.manifestSkipCount++;
1101 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001102 if (r.curApp != null && r.curApp.crashing) {
1103 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001104 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1105 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001106 skip = true;
1107 }
Christopher Tateba629da2013-11-13 17:42:28 -08001108 if (!skip) {
1109 boolean isAvailable = false;
1110 try {
1111 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1112 info.activityInfo.packageName,
1113 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1114 } catch (Exception e) {
1115 // all such failures mean we skip this receiver
1116 Slog.w(TAG, "Exception getting recipient info for "
1117 + info.activityInfo.packageName, e);
1118 }
1119 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001120 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1121 "Skipping delivery to " + info.activityInfo.packageName + " / "
1122 + info.activityInfo.applicationInfo.uid
1123 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001124 skip = true;
1125 }
1126 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001127
Svet Ganov9c165d72015-12-01 19:52:26 -08001128 // If permissions need a review before any of the app components can run, we drop
1129 // the broadcast and if the calling app is in the foreground and the broadcast is
1130 // explicit we launch the review UI passing it a pending intent to send the skipped
1131 // broadcast.
1132 if (Build.PERMISSIONS_REVIEW_REQUIRED && !skip) {
1133 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1134 info.activityInfo.packageName, UserHandle.getUserId(
1135 info.activityInfo.applicationInfo.uid))) {
1136 skip = true;
1137 }
1138 }
1139
Dianne Hackborn76e80092015-12-09 14:15:34 -08001140 // This is safe to do even if we are skipping the broadcast, and we need
1141 // this information now to evaluate whether it is going to be allowed to run.
1142 final int receiverUid = info.activityInfo.applicationInfo.uid;
1143 // If it's a singleton, it needs to be the same app or a special app
1144 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1145 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1146 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1147 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001148 String targetProcess = info.activityInfo.processName;
1149 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1150 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001151
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001152 if (!skip) {
1153 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001154 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1155 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001156 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1157 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001158 // completely disabled from launches, or it was not explicitly sent
1159 // to it and the app is in a state that should not receive it
1160 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001161 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1162 Slog.w(TAG, "Background execution disabled: receiving "
1163 + r.intent + " to "
1164 + component.flattenToShortString());
1165 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001166 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001167 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001168 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001169 && ((r.intent.getFlags()
1170 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001171 Slog.w(TAG, "Background execution not allowed: receiving "
1172 + r.intent + " to "
1173 + component.flattenToShortString());
1174 skip = true;
1175 }
1176 }
1177 }
1178
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001179 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001180 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001181 "Skipping delivery of ordered [" + mQueueName + "] "
1182 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001183 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001184 r.receiver = null;
1185 r.curFilter = null;
1186 r.state = BroadcastRecord.IDLE;
1187 scheduleBroadcastsLocked();
1188 return;
1189 }
1190
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001191 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001192 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001193 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001194 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001195 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001196 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1197 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1198 + info.activityInfo.applicationInfo.uid);
1199 }
1200
Dianne Hackborna750a632015-06-16 17:18:23 -07001201 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1202 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001203 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001204 }
1205
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001206 // Broadcast is being executed, its package can't be stopped.
1207 try {
1208 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001209 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001210 } catch (RemoteException e) {
1211 } catch (IllegalArgumentException e) {
1212 Slog.w(TAG, "Failed trying to unstop package "
1213 + r.curComponent.getPackageName() + ": " + e);
1214 }
1215
1216 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001217 if (app != null && app.thread != null) {
1218 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001219 app.addPackage(info.activityInfo.packageName,
1220 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001221 processCurBroadcastLocked(r, app);
1222 return;
1223 } catch (RemoteException e) {
1224 Slog.w(TAG, "Exception when sending broadcast to "
1225 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001226 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001227 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001228 + r.curComponent + " with " + r.intent, e);
1229 // If some unexpected exception happened, just skip
1230 // this broadcast. At this point we are not in the call
1231 // from a client, so throwing an exception out from here
1232 // will crash the entire system instead of just whoever
1233 // sent the broadcast.
1234 logBroadcastReceiverDiscardLocked(r);
1235 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001236 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001237 scheduleBroadcastsLocked();
1238 // We need to reset the state if we failed to start the receiver.
1239 r.state = BroadcastRecord.IDLE;
1240 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001241 }
1242
1243 // If a dead object exception was thrown -- fall through to
1244 // restart the application.
1245 }
1246
1247 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001248 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001249 "Need to start app ["
1250 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1251 if ((r.curApp=mService.startProcessLocked(targetProcess,
1252 info.activityInfo.applicationInfo, true,
1253 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1254 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001255 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001256 == null) {
1257 // Ah, this recipient is unavailable. Finish it if necessary,
1258 // and mark the broadcast record as ready for the next.
1259 Slog.w(TAG, "Unable to launch app "
1260 + info.activityInfo.applicationInfo.packageName + "/"
1261 + info.activityInfo.applicationInfo.uid + " for broadcast "
1262 + r.intent + ": process is bad");
1263 logBroadcastReceiverDiscardLocked(r);
1264 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001265 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001266 scheduleBroadcastsLocked();
1267 r.state = BroadcastRecord.IDLE;
1268 return;
1269 }
1270
1271 mPendingBroadcast = r;
1272 mPendingBroadcastRecvIndex = recIdx;
1273 }
1274 }
1275
1276 final void setBroadcastTimeoutLocked(long timeoutTime) {
1277 if (! mPendingBroadcastTimeoutMessage) {
1278 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1279 mHandler.sendMessageAtTime(msg, timeoutTime);
1280 mPendingBroadcastTimeoutMessage = true;
1281 }
1282 }
1283
1284 final void cancelBroadcastTimeoutLocked() {
1285 if (mPendingBroadcastTimeoutMessage) {
1286 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1287 mPendingBroadcastTimeoutMessage = false;
1288 }
1289 }
1290
1291 final void broadcastTimeoutLocked(boolean fromMsg) {
1292 if (fromMsg) {
1293 mPendingBroadcastTimeoutMessage = false;
1294 }
1295
1296 if (mOrderedBroadcasts.size() == 0) {
1297 return;
1298 }
1299
1300 long now = SystemClock.uptimeMillis();
1301 BroadcastRecord r = mOrderedBroadcasts.get(0);
1302 if (fromMsg) {
1303 if (mService.mDidDexOpt) {
1304 // Delay timeouts until dexopt finishes.
1305 mService.mDidDexOpt = false;
1306 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1307 setBroadcastTimeoutLocked(timeoutTime);
1308 return;
1309 }
1310 if (!mService.mProcessesReady) {
1311 // Only process broadcast timeouts if the system is ready. That way
1312 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1313 // to do heavy lifting for system up.
1314 return;
1315 }
1316
1317 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1318 if (timeoutTime > now) {
1319 // We can observe premature timeouts because we do not cancel and reset the
1320 // broadcast timeout message after each receiver finishes. Instead, we set up
1321 // an initial timeout then kick it down the road a little further as needed
1322 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001323 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001324 "Premature timeout ["
1325 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1326 + timeoutTime);
1327 setBroadcastTimeoutLocked(timeoutTime);
1328 return;
1329 }
1330 }
1331
Dianne Hackborn6285a322013-09-18 12:09:47 -07001332 BroadcastRecord br = mOrderedBroadcasts.get(0);
1333 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1334 // In this case the broadcast had already finished, but we had decided to wait
1335 // for started services to finish as well before going on. So if we have actually
1336 // waited long enough time timeout the broadcast, let's give up on the whole thing
1337 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001338 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001339 ? br.curComponent.flattenToShortString() : "(null)"));
1340 br.curComponent = null;
1341 br.state = BroadcastRecord.IDLE;
1342 processNextBroadcast(false);
1343 return;
1344 }
1345
1346 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001347 + ", started " + (now - r.receiverTime) + "ms ago");
1348 r.receiverTime = now;
1349 r.anrCount++;
1350
1351 // Current receiver has passed its expiration date.
1352 if (r.nextReceiver <= 0) {
1353 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1354 return;
1355 }
1356
1357 ProcessRecord app = null;
1358 String anrMessage = null;
1359
1360 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001361 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001362 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1363 logBroadcastReceiverDiscardLocked(r);
1364 if (curReceiver instanceof BroadcastFilter) {
1365 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1366 if (bf.receiverList.pid != 0
1367 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1368 synchronized (mService.mPidsSelfLocked) {
1369 app = mService.mPidsSelfLocked.get(
1370 bf.receiverList.pid);
1371 }
1372 }
1373 } else {
1374 app = r.curApp;
1375 }
1376
1377 if (app != null) {
1378 anrMessage = "Broadcast of " + r.intent.toString();
1379 }
1380
1381 if (mPendingBroadcast == r) {
1382 mPendingBroadcast = null;
1383 }
1384
1385 // Move on to the next receiver.
1386 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001387 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001388 scheduleBroadcastsLocked();
1389
1390 if (anrMessage != null) {
1391 // Post the ANR to the handler since we do not want to process ANRs while
1392 // potentially holding our lock.
1393 mHandler.post(new AppNotResponding(app, anrMessage));
1394 }
1395 }
1396
Christopher Tatef278f122015-04-22 13:12:01 -07001397 private final int ringAdvance(int x, final int increment, final int ringSize) {
1398 x += increment;
1399 if (x < 0) return (ringSize - 1);
1400 else if (x >= ringSize) return 0;
1401 else return x;
1402 }
1403
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001404 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1405 if (r.callingUid < 0) {
1406 // This was from a registerReceiver() call; ignore it.
1407 return;
1408 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001409 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001410
1411 mBroadcastHistory[mHistoryNext] = r;
1412 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1413
1414 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1415 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1416 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1417 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1418 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001419 }
1420
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001421 boolean cleanupDisabledPackageReceiversLocked(
1422 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1423 boolean didSomething = false;
1424 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1425 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1426 packageName, filterByClasses, userId, doit);
1427 if (!doit && didSomething) {
1428 return true;
1429 }
1430 }
1431
1432 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1433 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1434 packageName, filterByClasses, userId, doit);
1435 if (!doit && didSomething) {
1436 return true;
1437 }
1438 }
1439
1440 return didSomething;
1441 }
1442
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001443 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001444 final int logIndex = r.nextReceiver - 1;
1445 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1446 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001447 if (curReceiver instanceof BroadcastFilter) {
1448 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1449 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001450 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001451 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001452 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001453 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001454 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001455 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001456 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001457 }
1458 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001459 if (logIndex < 0) Slog.w(TAG,
1460 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001461 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001462 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001463 r.intent.getAction(),
1464 r.nextReceiver,
1465 "NONE");
1466 }
1467 }
1468
1469 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1470 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001471 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001472 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1473 || mPendingBroadcast != null) {
1474 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001475 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001476 BroadcastRecord br = mParallelBroadcasts.get(i);
1477 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1478 continue;
1479 }
1480 if (!printed) {
1481 if (needSep) {
1482 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001483 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001484 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001485 printed = true;
1486 pw.println(" Active broadcasts [" + mQueueName + "]:");
1487 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001488 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001489 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001490 }
1491 printed = false;
1492 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001493 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001494 BroadcastRecord br = mOrderedBroadcasts.get(i);
1495 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1496 continue;
1497 }
1498 if (!printed) {
1499 if (needSep) {
1500 pw.println();
1501 }
1502 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001503 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001504 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1505 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001506 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001507 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001508 }
1509 if (dumpPackage == null || (mPendingBroadcast != null
1510 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1511 if (needSep) {
1512 pw.println();
1513 }
1514 pw.println(" Pending broadcast [" + mQueueName + "]:");
1515 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001516 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001517 } else {
1518 pw.println(" (null)");
1519 }
1520 needSep = true;
1521 }
1522 }
1523
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001524 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001525 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001526
1527 i = -1;
1528 int lastIndex = mHistoryNext;
1529 int ringIndex = lastIndex;
1530 do {
1531 // increasing index = more recent entry, and we want to print the most
1532 // recent first and work backwards, so we roll through the ring backwards.
1533 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1534 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001535 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001536 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001537 }
Christopher Tatef278f122015-04-22 13:12:01 -07001538
1539 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001540 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1541 continue;
1542 }
1543 if (!printed) {
1544 if (needSep) {
1545 pw.println();
1546 }
1547 needSep = true;
1548 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1549 printed = true;
1550 }
1551 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001552 pw.print(" Historical Broadcast " + mQueueName + " #");
1553 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001554 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001555 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001556 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1557 pw.print(" ");
1558 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001559 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1560 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1561 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001562 Bundle bundle = r.intent.getExtras();
1563 if (bundle != null) {
1564 pw.print(" extras: "); pw.println(bundle.toString());
1565 }
1566 }
Christopher Tatef278f122015-04-22 13:12:01 -07001567 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001568
1569 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001570 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001571 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001572 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001573 i = -1;
1574 } else {
1575 // roll over the 'i' full dumps that have already been issued
1576 for (int j = i;
1577 j > 0 && ringIndex != lastIndex;) {
1578 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1579 BroadcastRecord r = mBroadcastHistory[ringIndex];
1580 if (r == null) {
1581 continue;
1582 }
1583 j--;
1584 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001585 }
Christopher Tatef278f122015-04-22 13:12:01 -07001586 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1587 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001588 do {
1589 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1590 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001591 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001592 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001593 }
1594 if (!printed) {
1595 if (needSep) {
1596 pw.println();
1597 }
1598 needSep = true;
1599 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1600 printed = true;
1601 }
1602 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001603 pw.println(" ...");
1604 break;
1605 }
Christopher Tatef278f122015-04-22 13:12:01 -07001606 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001607 pw.print(" #"); pw.print(i); pw.print(": ");
1608 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001609 pw.print(" ");
1610 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1611 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1612 pw.print(" dispatch ");
1613 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1614 - mSummaryHistoryDispatchTime[ringIndex], pw);
1615 pw.println(" finish");
1616 pw.print(" enq=");
1617 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1618 pw.print(" disp=");
1619 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1620 pw.print(" fin=");
1621 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001622 Bundle bundle = intent.getExtras();
1623 if (bundle != null) {
1624 pw.print(" extras: "); pw.println(bundle.toString());
1625 }
Christopher Tatef278f122015-04-22 13:12:01 -07001626 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001627 }
1628
1629 return needSep;
1630 }
1631}