blob: 6b3be7a03fcdbb336d991cbd177a5d29535a5925 [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) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700229 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700230 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700231 if (intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800232 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800233 "***** DROPPING PARALLEL ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700234 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800235 mParallelBroadcasts.set(i, r);
236 return true;
237 }
238 }
239 return false;
240 }
241
242 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700243 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700244 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700245 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800246 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800247 "***** DROPPING ORDERED ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700248 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800249 mOrderedBroadcasts.set(i, r);
250 return true;
251 }
252 }
253 return false;
254 }
255
256 private final void processCurBroadcastLocked(BroadcastRecord r,
257 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800258 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800259 "Process cur broadcast " + r + " for app " + app);
260 if (app.thread == null) {
261 throw new RemoteException();
262 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700263 if (app.inFullBackup) {
264 skipReceiverLocked(r);
265 return;
266 }
267
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800268 r.receiver = app.thread.asBinder();
269 r.curApp = app;
270 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700271 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700272 mService.updateLruProcessLocked(app, false, null);
273 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800274
275 // Tell the application to launch this receiver.
276 r.intent.setComponent(r.curComponent);
277
278 boolean started = false;
279 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800280 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 "Delivering to component " + r.curComponent
282 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700283 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
284 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800285 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
286 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700287 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
288 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800289 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800290 "Process cur broadcast " + r + " DELIVERED for app " + app);
291 started = true;
292 } finally {
293 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800294 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295 "Process cur broadcast " + r + ": NOT STARTED!");
296 r.receiver = null;
297 r.curApp = null;
298 app.curReceiver = null;
299 }
300 }
301 }
302
303 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
304 boolean didSomething = false;
305 final BroadcastRecord br = mPendingBroadcast;
306 if (br != null && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700307 if (br.curApp != app) {
308 Slog.e(TAG, "App mismatch when sending pending broadcast to "
309 + app.processName + ", intended target is " + br.curApp.processName);
310 return false;
311 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800312 try {
313 mPendingBroadcast = null;
314 processCurBroadcastLocked(br, app);
315 didSomething = true;
316 } catch (Exception e) {
317 Slog.w(TAG, "Exception in new application when starting receiver "
318 + br.curComponent.flattenToShortString(), e);
319 logBroadcastReceiverDiscardLocked(br);
320 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700321 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800322 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700323 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800324 br.state = BroadcastRecord.IDLE;
325 throw new RuntimeException(e.getMessage());
326 }
327 }
328 return didSomething;
329 }
330
331 public void skipPendingBroadcastLocked(int pid) {
332 final BroadcastRecord br = mPendingBroadcast;
333 if (br != null && br.curApp.pid == pid) {
334 br.state = BroadcastRecord.IDLE;
335 br.nextReceiver = mPendingBroadcastRecvIndex;
336 mPendingBroadcast = null;
337 scheduleBroadcastsLocked();
338 }
339 }
340
341 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700342 BroadcastRecord r = null;
343 if (mOrderedBroadcasts.size() > 0) {
344 BroadcastRecord br = mOrderedBroadcasts.get(0);
345 if (br.curApp == app) {
346 r = br;
347 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800348 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800349 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800350 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800351 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800352 r = mPendingBroadcast;
353 }
354
355 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700356 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800357 }
358 }
359
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700360 private void skipReceiverLocked(BroadcastRecord r) {
361 logBroadcastReceiverDiscardLocked(r);
362 finishReceiverLocked(r, r.resultCode, r.resultData,
363 r.resultExtras, r.resultAbort, false);
364 scheduleBroadcastsLocked();
365 }
366
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800367 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800368 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800369 + mQueueName + "]: current="
370 + mBroadcastsScheduled);
371
372 if (mBroadcastsScheduled) {
373 return;
374 }
375 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
376 mBroadcastsScheduled = true;
377 }
378
379 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
380 if (mOrderedBroadcasts.size() > 0) {
381 final BroadcastRecord r = mOrderedBroadcasts.get(0);
382 if (r != null && r.receiver == receiver) {
383 return r;
384 }
385 }
386 return null;
387 }
388
389 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700390 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
391 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700392 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800393 r.state = BroadcastRecord.IDLE;
394 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700395 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800396 }
397 r.receiver = null;
398 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800399 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800400 r.curApp.curReceiver = null;
401 }
402 if (r.curFilter != null) {
403 r.curFilter.receiverList.curBroadcast = null;
404 }
405 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800406 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700407 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800408 mPendingBroadcast = null;
409
410 r.resultCode = resultCode;
411 r.resultData = resultData;
412 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700413 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
414 r.resultAbort = resultAbort;
415 } else {
416 r.resultAbort = false;
417 }
418
419 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
420 && r.queue.mOrderedBroadcasts.size() > 0
421 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700422 ActivityInfo nextReceiver;
423 if (r.nextReceiver < r.receivers.size()) {
424 Object obj = r.receivers.get(r.nextReceiver);
425 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
426 } else {
427 nextReceiver = null;
428 }
429 // Don't do this if the next receive is in the same process as the current one.
430 if (receiver == null || nextReceiver == null
431 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
432 || !receiver.processName.equals(nextReceiver.processName)) {
433 // In this case, we are ready to process the next receiver for the current broadcast,
434 // but are on a queue that would like to wait for services to finish before moving
435 // on. If there are background services currently starting, then we will go into a
436 // special state where we hold off on continuing this broadcast until they are done.
437 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800438 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700439 r.state = BroadcastRecord.WAITING_SERVICES;
440 return false;
441 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700442 }
443 }
444
445 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800446
447 // We will process the next receiver right now if this is finishing
448 // an app receiver (which is always asynchronous) or after we have
449 // come back from calling a receiver.
450 return state == BroadcastRecord.APP_RECEIVE
451 || state == BroadcastRecord.CALL_DONE_RECEIVE;
452 }
453
Dianne Hackborn6285a322013-09-18 12:09:47 -0700454 public void backgroundServicesFinishedLocked(int userId) {
455 if (mOrderedBroadcasts.size() > 0) {
456 BroadcastRecord br = mOrderedBroadcasts.get(0);
457 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800458 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700459 br.curComponent = null;
460 br.state = BroadcastRecord.IDLE;
461 processNextBroadcast(false);
462 }
463 }
464 }
465
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700466 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800467 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700468 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800469 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000470 if (app != null) {
471 if (app.thread != null) {
472 // If we have an app thread, do the call through that so it is
473 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700474 try {
475 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
476 data, extras, ordered, sticky, sendingUser, app.repProcState);
477 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
478 // DeadObjectException when the process isn't actually dead.
479 //} catch (DeadObjectException ex) {
480 // Failed to call into the process. It's dying so just let it die and move on.
481 // throw ex;
482 } catch (RemoteException ex) {
483 // Failed to call into the process. It's either dying or wedged. Kill it gently.
484 synchronized (mService) {
485 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
486 + " (pid " + app.pid + "). Crashing it.");
487 app.scheduleCrash("can't deliver broadcast");
488 }
489 throw ex;
490 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000491 } else {
492 // Application has died. Receiver doesn't exist.
493 throw new RemoteException("app.thread must not be null");
494 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800495 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700496 receiver.performReceive(intent, resultCode, data, extras, ordered,
497 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800498 }
499 }
500
Svet Ganov99b60432015-06-27 13:15:22 -0700501 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800502 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800503 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700504 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800505 int perm = mService.checkComponentPermission(filter.requiredPermission,
506 r.callingPid, r.callingUid, -1, true);
507 if (perm != PackageManager.PERMISSION_GRANTED) {
508 Slog.w(TAG, "Permission Denial: broadcasting "
509 + r.intent.toString()
510 + " from " + r.callerPackage + " (pid="
511 + r.callingPid + ", uid=" + r.callingUid + ")"
512 + " requires " + filter.requiredPermission
513 + " due to registered receiver " + filter);
514 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700515 } else {
516 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
517 if (opCode != AppOpsManager.OP_NONE
518 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
519 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
520 Slog.w(TAG, "Appop Denial: broadcasting "
521 + r.intent.toString()
522 + " from " + r.callerPackage + " (pid="
523 + r.callingPid + ", uid=" + r.callingUid + ")"
524 + " requires appop " + AppOpsManager.permissionToOp(
525 filter.requiredPermission)
526 + " due to registered receiver " + filter);
527 skip = true;
528 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800529 }
530 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700531 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
532 for (int i = 0; i < r.requiredPermissions.length; i++) {
533 String requiredPermission = r.requiredPermissions[i];
534 int perm = mService.checkComponentPermission(requiredPermission,
535 filter.receiverList.pid, filter.receiverList.uid, -1, true);
536 if (perm != PackageManager.PERMISSION_GRANTED) {
537 Slog.w(TAG, "Permission Denial: receiving "
538 + r.intent.toString()
539 + " to " + filter.receiverList.app
540 + " (pid=" + filter.receiverList.pid
541 + ", uid=" + filter.receiverList.uid + ")"
542 + " requires " + requiredPermission
543 + " due to sender " + r.callerPackage
544 + " (uid " + r.callingUid + ")");
545 skip = true;
546 break;
547 }
548 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700549 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700550 && mService.mAppOpsService.noteOperation(appOp,
551 filter.receiverList.uid, filter.packageName)
552 != AppOpsManager.MODE_ALLOWED) {
553 Slog.w(TAG, "Appop Denial: receiving "
554 + r.intent.toString()
555 + " to " + filter.receiverList.app
556 + " (pid=" + filter.receiverList.pid
557 + ", uid=" + filter.receiverList.uid + ")"
558 + " requires appop " + AppOpsManager.permissionToOp(
559 requiredPermission)
560 + " due to sender " + r.callerPackage
561 + " (uid " + r.callingUid + ")");
562 skip = true;
563 break;
564 }
565 }
566 }
567 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
568 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000569 filter.receiverList.pid, filter.receiverList.uid, -1, true);
570 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700571 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000572 + r.intent.toString()
573 + " to " + filter.receiverList.app
574 + " (pid=" + filter.receiverList.pid
575 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000576 + " due to sender " + r.callerPackage
577 + " (uid " + r.callingUid + ")");
578 skip = true;
579 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700580 }
581 if (!skip && r.appOp != AppOpsManager.OP_NONE
582 && mService.mAppOpsService.noteOperation(r.appOp,
583 filter.receiverList.uid, filter.packageName)
584 != AppOpsManager.MODE_ALLOWED) {
585 Slog.w(TAG, "Appop Denial: receiving "
586 + r.intent.toString()
587 + " to " + filter.receiverList.app
588 + " (pid=" + filter.receiverList.pid
589 + ", uid=" + filter.receiverList.uid + ")"
590 + " requires appop " + AppOpsManager.opToName(r.appOp)
591 + " due to sender " + r.callerPackage
592 + " (uid " + r.callingUid + ")");
593 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700594 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700595 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800596 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700597 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800598 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700599 Slog.w(TAG, "Background execution not allowed: receiving "
600 + r.intent
601 + " to " + filter.receiverList.app
602 + " (pid=" + filter.receiverList.pid
603 + ", uid=" + filter.receiverList.uid + ")");
604 skip = true;
605 }
606 }
Svet Ganov99b60432015-06-27 13:15:22 -0700607
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700608 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
609 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800610 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700611 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800612
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800613 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700614 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
615 + " to " + filter.receiverList + ": process crashing");
616 skip = true;
617 }
618
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800619 if (skip) {
620 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
621 return;
622 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800623
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800624 // If permissions need a review before any of the app components can run, we drop
625 // the broadcast and if the calling app is in the foreground and the broadcast is
626 // explicit we launch the review UI passing it a pending intent to send the skipped
627 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -0700628 if (mService.mPermissionReviewRequired) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800629 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
630 filter.owningUserId)) {
631 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
632 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800633 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800634 }
635
636 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
637
638 // If this is not being sent as an ordered broadcast, then we
639 // don't want to touch the fields that keep track of the current
640 // state of ordered broadcasts.
641 if (ordered) {
642 r.receiver = filter.receiverList.receiver.asBinder();
643 r.curFilter = filter;
644 filter.receiverList.curBroadcast = r;
645 r.state = BroadcastRecord.CALL_IN_RECEIVE;
646 if (filter.receiverList.app != null) {
647 // Bump hosting application to no longer be in background
648 // scheduling class. Note that we can't do that if there
649 // isn't an app... but we can only be in that case for
650 // things that directly call the IActivityManager API, which
651 // are already core system stuff so don't matter for this.
652 r.curApp = filter.receiverList.app;
653 filter.receiverList.app.curReceiver = r;
654 mService.updateOomAdjLocked(r.curApp);
655 }
656 }
657 try {
658 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
659 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700660 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
661 // Skip delivery if full backup in progress
662 // If it's an ordered broadcast, we need to continue to the next receiver.
663 if (ordered) {
664 skipReceiverLocked(r);
665 }
666 } else {
667 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
668 new Intent(r.intent), r.resultCode, r.resultData,
669 r.resultExtras, r.ordered, r.initialSticky, r.userId);
670 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800671 if (ordered) {
672 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
673 }
674 } catch (RemoteException e) {
675 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
676 if (ordered) {
677 r.receiver = null;
678 r.curFilter = null;
679 filter.receiverList.curBroadcast = null;
680 if (filter.receiverList.app != null) {
681 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800682 }
683 }
684 }
685 }
686
Svet Ganov9c165d72015-12-01 19:52:26 -0800687 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
688 BroadcastRecord receiverRecord, String receivingPackageName,
689 final int receivingUserId) {
690 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
691 receivingPackageName, receivingUserId)) {
692 return true;
693 }
694
695 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800696 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800697 : true;
698
699 // Show a permission review UI only for explicit broadcast from a foreground app
700 if (callerForeground && receiverRecord.intent.getComponent() != null) {
701 IIntentSender target = mService.getIntentSenderLocked(
702 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
703 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
704 new Intent[]{receiverRecord.intent},
705 new String[]{receiverRecord.intent.resolveType(mService.mContext
706 .getContentResolver())},
707 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
708 | PendingIntent.FLAG_IMMUTABLE, null);
709
710 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
711 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
712 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
713 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
714 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
715
716 if (DEBUG_PERMISSIONS_REVIEW) {
717 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
718 + receivingPackageName);
719 }
720
721 mHandler.post(new Runnable() {
722 @Override
723 public void run() {
724 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
725 }
726 });
727 } else {
728 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
729 + receivingPackageName + " requires a permissions review");
730 }
731
732 return false;
733 }
734
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700735 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700736 if (duration > Integer.MAX_VALUE) {
737 duration = Integer.MAX_VALUE;
738 }
739 // XXX ideally we should pause the broadcast until everything behind this is done,
740 // or else we will likely start dispatching the broadcast before we have opened
741 // access to the app (there is a lot of asynchronicity behind this). It is probably
742 // not that big a deal, however, because the main purpose here is to allow apps
743 // to hold wake locks, and they will be able to acquire their wake lock immediately
744 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700745 StringBuilder b = new StringBuilder();
746 b.append("broadcast:");
747 UserHandle.formatUid(b, r.callingUid);
748 b.append(":");
749 if (r.intent.getAction() != null) {
750 b.append(r.intent.getAction());
751 } else if (r.intent.getComponent() != null) {
752 b.append(r.intent.getComponent().flattenToShortString());
753 } else if (r.intent.getData() != null) {
754 b.append(r.intent.getData());
755 }
756 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
757 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700758 }
759
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800760 final void processNextBroadcast(boolean fromMsg) {
761 synchronized(mService) {
762 BroadcastRecord r;
763
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800764 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800765 + mQueueName + "]: "
766 + mParallelBroadcasts.size() + " broadcasts, "
767 + mOrderedBroadcasts.size() + " ordered broadcasts");
768
769 mService.updateCpuStats();
770
771 if (fromMsg) {
772 mBroadcastsScheduled = false;
773 }
774
775 // First, deliver any non-serialized broadcasts right away.
776 while (mParallelBroadcasts.size() > 0) {
777 r = mParallelBroadcasts.remove(0);
778 r.dispatchTime = SystemClock.uptimeMillis();
779 r.dispatchClockTime = System.currentTimeMillis();
780 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800781 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800782 + mQueueName + "] " + r);
783 for (int i=0; i<N; i++) {
784 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800785 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800786 "Delivering non-ordered on [" + mQueueName + "] to registered "
787 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800788 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800789 }
790 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800791 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800792 + mQueueName + "] " + r);
793 }
794
795 // Now take care of the next serialized one...
796
797 // If we are waiting for a process to come up to handle the next
798 // broadcast, then do nothing at this point. Just in case, we
799 // check that the process we're waiting for still exists.
800 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700801 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
802 "processNextBroadcast [" + mQueueName + "]: waiting for "
803 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800804
805 boolean isDead;
806 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700807 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
808 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800809 }
810 if (!isDead) {
811 // It's still alive, so keep waiting
812 return;
813 } else {
814 Slog.w(TAG, "pending app ["
815 + mQueueName + "]" + mPendingBroadcast.curApp
816 + " died before responding to broadcast");
817 mPendingBroadcast.state = BroadcastRecord.IDLE;
818 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
819 mPendingBroadcast = null;
820 }
821 }
822
823 boolean looped = false;
824
825 do {
826 if (mOrderedBroadcasts.size() == 0) {
827 // No more broadcasts pending, so all done!
828 mService.scheduleAppGcsLocked();
829 if (looped) {
830 // If we had finished the last ordered broadcast, then
831 // make sure all processes have correct oom and sched
832 // adjustments.
833 mService.updateOomAdjLocked();
834 }
835 return;
836 }
837 r = mOrderedBroadcasts.get(0);
838 boolean forceReceive = false;
839
840 // Ensure that even if something goes awry with the timeout
841 // detection, we catch "hung" broadcasts here, discard them,
842 // and continue to make progress.
843 //
844 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
845 // receivers don't get executed with timeouts. They're intended for
846 // one time heavy lifting after system upgrades and can take
847 // significant amounts of time.
848 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
849 if (mService.mProcessesReady && r.dispatchTime > 0) {
850 long now = SystemClock.uptimeMillis();
851 if ((numReceivers > 0) &&
852 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
853 Slog.w(TAG, "Hung broadcast ["
854 + mQueueName + "] discarded after timeout failure:"
855 + " now=" + now
856 + " dispatchTime=" + r.dispatchTime
857 + " startTime=" + r.receiverTime
858 + " intent=" + r.intent
859 + " numReceivers=" + numReceivers
860 + " nextReceiver=" + r.nextReceiver
861 + " state=" + r.state);
862 broadcastTimeoutLocked(false); // forcibly finish this broadcast
863 forceReceive = true;
864 r.state = BroadcastRecord.IDLE;
865 }
866 }
867
868 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800869 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800870 "processNextBroadcast("
871 + mQueueName + ") called when not idle (state="
872 + r.state + ")");
873 return;
874 }
875
876 if (r.receivers == null || r.nextReceiver >= numReceivers
877 || r.resultAbort || forceReceive) {
878 // No more receivers for this broadcast! Send the final
879 // result if requested...
880 if (r.resultTo != null) {
881 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800882 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800883 "Finishing broadcast [" + mQueueName + "] "
884 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800885 performReceiveLocked(r.callerApp, r.resultTo,
886 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700887 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800888 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700889 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800890 r.resultTo = null;
891 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000892 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800893 Slog.w(TAG, "Failure ["
894 + mQueueName + "] sending broadcast result of "
895 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700896
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800897 }
898 }
899
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800900 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800901 cancelBroadcastTimeoutLocked();
902
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700903 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
904 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800905
906 // ... and on to the next...
907 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700908 if (r.intent.getComponent() == null && r.intent.getPackage() == null
909 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
910 // This was an implicit broadcast... let's record it for posterity.
911 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
912 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
913 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800914 mOrderedBroadcasts.remove(0);
915 r = null;
916 looped = true;
917 continue;
918 }
919 } while (r == null);
920
921 // Get the next receiver...
922 int recIdx = r.nextReceiver++;
923
924 // Keep track of when this receiver started, and make sure there
925 // is a timeout message pending to kill it if need be.
926 r.receiverTime = SystemClock.uptimeMillis();
927 if (recIdx == 0) {
928 r.dispatchTime = r.receiverTime;
929 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800930 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800931 + mQueueName + "] " + r);
932 }
933 if (! mPendingBroadcastTimeoutMessage) {
934 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800935 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800936 "Submitting BROADCAST_TIMEOUT_MSG ["
937 + mQueueName + "] for " + r + " at " + timeoutTime);
938 setBroadcastTimeoutLocked(timeoutTime);
939 }
940
Dianne Hackborna750a632015-06-16 17:18:23 -0700941 final BroadcastOptions brOptions = r.options;
942 final Object nextReceiver = r.receivers.get(recIdx);
943
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800944 if (nextReceiver instanceof BroadcastFilter) {
945 // Simple case: this is a registered receiver who gets
946 // a direct call.
947 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800948 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800949 "Delivering ordered ["
950 + mQueueName + "] to registered "
951 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800952 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800953 if (r.receiver == null || !r.ordered) {
954 // The receiver has already finished, so schedule to
955 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800956 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800957 + mQueueName + "]: ordered="
958 + r.ordered + " receiver=" + r.receiver);
959 r.state = BroadcastRecord.IDLE;
960 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700961 } else {
962 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
963 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700964 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700965 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800966 }
967 return;
968 }
969
970 // Hard case: need to instantiate the receiver, possibly
971 // starting its application process to host it.
972
973 ResolveInfo info =
974 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700975 ComponentName component = new ComponentName(
976 info.activityInfo.applicationInfo.packageName,
977 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800978
979 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800980 if (brOptions != null &&
981 (info.activityInfo.applicationInfo.targetSdkVersion
982 < brOptions.getMinManifestReceiverApiLevel() ||
983 info.activityInfo.applicationInfo.targetSdkVersion
984 > brOptions.getMaxManifestReceiverApiLevel())) {
985 skip = true;
986 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800987 int perm = mService.checkComponentPermission(info.activityInfo.permission,
988 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
989 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800990 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800991 if (!info.activityInfo.exported) {
992 Slog.w(TAG, "Permission Denial: broadcasting "
993 + r.intent.toString()
994 + " from " + r.callerPackage + " (pid=" + r.callingPid
995 + ", uid=" + r.callingUid + ")"
996 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700997 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800998 } else {
999 Slog.w(TAG, "Permission Denial: broadcasting "
1000 + r.intent.toString()
1001 + " from " + r.callerPackage + " (pid=" + r.callingPid
1002 + ", uid=" + r.callingUid + ")"
1003 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001004 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001005 }
1006 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001007 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001008 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1009 if (opCode != AppOpsManager.OP_NONE
1010 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1011 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1012 Slog.w(TAG, "Appop Denial: broadcasting "
1013 + r.intent.toString()
1014 + " from " + r.callerPackage + " (pid="
1015 + r.callingPid + ", uid=" + r.callingUid + ")"
1016 + " requires appop " + AppOpsManager.permissionToOp(
1017 info.activityInfo.permission)
1018 + " due to registered receiver "
1019 + component.flattenToShortString());
1020 skip = true;
1021 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001022 }
Svet Ganov99b60432015-06-27 13:15:22 -07001023 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001024 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1025 for (int i = 0; i < r.requiredPermissions.length; i++) {
1026 String requiredPermission = r.requiredPermissions[i];
1027 try {
1028 perm = AppGlobals.getPackageManager().
1029 checkPermission(requiredPermission,
1030 info.activityInfo.applicationInfo.packageName,
1031 UserHandle
1032 .getUserId(info.activityInfo.applicationInfo.uid));
1033 } catch (RemoteException e) {
1034 perm = PackageManager.PERMISSION_DENIED;
1035 }
1036 if (perm != PackageManager.PERMISSION_GRANTED) {
1037 Slog.w(TAG, "Permission Denial: receiving "
1038 + r.intent + " to "
1039 + component.flattenToShortString()
1040 + " requires " + requiredPermission
1041 + " due to sender " + r.callerPackage
1042 + " (uid " + r.callingUid + ")");
1043 skip = true;
1044 break;
1045 }
1046 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1047 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1048 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001049 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001050 != AppOpsManager.MODE_ALLOWED) {
1051 Slog.w(TAG, "Appop Denial: receiving "
1052 + r.intent + " to "
1053 + component.flattenToShortString()
1054 + " requires appop " + AppOpsManager.permissionToOp(
1055 requiredPermission)
1056 + " due to sender " + r.callerPackage
1057 + " (uid " + r.callingUid + ")");
1058 skip = true;
1059 break;
1060 }
1061 }
1062 }
1063 if (!skip && r.appOp != AppOpsManager.OP_NONE
1064 && mService.mAppOpsService.noteOperation(r.appOp,
1065 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1066 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001067 Slog.w(TAG, "Appop Denial: receiving "
1068 + r.intent + " to "
1069 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001070 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001071 + " due to sender " + r.callerPackage
1072 + " (uid " + r.callingUid + ")");
1073 skip = true;
1074 }
Ben Gruver49660c72013-08-06 19:54:08 -07001075 if (!skip) {
1076 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1077 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1078 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001079 boolean isSingleton = false;
1080 try {
1081 isSingleton = mService.isSingleton(info.activityInfo.processName,
1082 info.activityInfo.applicationInfo,
1083 info.activityInfo.name, info.activityInfo.flags);
1084 } catch (SecurityException e) {
1085 Slog.w(TAG, e.getMessage());
1086 skip = true;
1087 }
1088 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1089 if (ActivityManager.checkUidPermission(
1090 android.Manifest.permission.INTERACT_ACROSS_USERS,
1091 info.activityInfo.applicationInfo.uid)
1092 != PackageManager.PERMISSION_GRANTED) {
1093 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1094 + " requests FLAG_SINGLE_USER, but app does not hold "
1095 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1096 skip = true;
1097 }
1098 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001099 if (!skip) {
1100 r.manifestCount++;
1101 } else {
1102 r.manifestSkipCount++;
1103 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001104 if (r.curApp != null && r.curApp.crashing) {
1105 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001106 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1107 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001108 skip = true;
1109 }
Christopher Tateba629da2013-11-13 17:42:28 -08001110 if (!skip) {
1111 boolean isAvailable = false;
1112 try {
1113 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1114 info.activityInfo.packageName,
1115 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1116 } catch (Exception e) {
1117 // all such failures mean we skip this receiver
1118 Slog.w(TAG, "Exception getting recipient info for "
1119 + info.activityInfo.packageName, e);
1120 }
1121 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001122 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1123 "Skipping delivery to " + info.activityInfo.packageName + " / "
1124 + info.activityInfo.applicationInfo.uid
1125 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001126 skip = true;
1127 }
1128 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001129
Svet Ganov9c165d72015-12-01 19:52:26 -08001130 // If permissions need a review before any of the app components can run, we drop
1131 // the broadcast and if the calling app is in the foreground and the broadcast is
1132 // explicit we launch the review UI passing it a pending intent to send the skipped
1133 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -07001134 if (mService.mPermissionReviewRequired && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001135 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1136 info.activityInfo.packageName, UserHandle.getUserId(
1137 info.activityInfo.applicationInfo.uid))) {
1138 skip = true;
1139 }
1140 }
1141
Dianne Hackborn76e80092015-12-09 14:15:34 -08001142 // This is safe to do even if we are skipping the broadcast, and we need
1143 // this information now to evaluate whether it is going to be allowed to run.
1144 final int receiverUid = info.activityInfo.applicationInfo.uid;
1145 // If it's a singleton, it needs to be the same app or a special app
1146 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1147 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1148 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1149 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001150 String targetProcess = info.activityInfo.processName;
1151 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1152 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001153
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001154 if (!skip) {
1155 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001156 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1157 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001158 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1159 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001160 // completely disabled from launches, or it was not explicitly sent
1161 // to it and the app is in a state that should not receive it
1162 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001163 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1164 Slog.w(TAG, "Background execution disabled: receiving "
1165 + r.intent + " to "
1166 + component.flattenToShortString());
1167 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001168 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001169 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001170 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001171 && ((r.intent.getFlags()
1172 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001173 Slog.w(TAG, "Background execution not allowed: receiving "
1174 + r.intent + " to "
1175 + component.flattenToShortString());
1176 skip = true;
1177 }
1178 }
1179 }
1180
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001181 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001182 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001183 "Skipping delivery of ordered [" + mQueueName + "] "
1184 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001185 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001186 r.receiver = null;
1187 r.curFilter = null;
1188 r.state = BroadcastRecord.IDLE;
1189 scheduleBroadcastsLocked();
1190 return;
1191 }
1192
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001193 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001194 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001195 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001196 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001197 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001198 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1199 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1200 + info.activityInfo.applicationInfo.uid);
1201 }
1202
Dianne Hackborna750a632015-06-16 17:18:23 -07001203 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1204 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001205 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001206 }
1207
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001208 // Broadcast is being executed, its package can't be stopped.
1209 try {
1210 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001211 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001212 } catch (RemoteException e) {
1213 } catch (IllegalArgumentException e) {
1214 Slog.w(TAG, "Failed trying to unstop package "
1215 + r.curComponent.getPackageName() + ": " + e);
1216 }
1217
1218 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001219 if (app != null && app.thread != null) {
1220 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001221 app.addPackage(info.activityInfo.packageName,
1222 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001223 processCurBroadcastLocked(r, app);
1224 return;
1225 } catch (RemoteException e) {
1226 Slog.w(TAG, "Exception when sending broadcast to "
1227 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001228 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001229 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001230 + r.curComponent + " with " + r.intent, e);
1231 // If some unexpected exception happened, just skip
1232 // this broadcast. At this point we are not in the call
1233 // from a client, so throwing an exception out from here
1234 // will crash the entire system instead of just whoever
1235 // sent the broadcast.
1236 logBroadcastReceiverDiscardLocked(r);
1237 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001238 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001239 scheduleBroadcastsLocked();
1240 // We need to reset the state if we failed to start the receiver.
1241 r.state = BroadcastRecord.IDLE;
1242 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001243 }
1244
1245 // If a dead object exception was thrown -- fall through to
1246 // restart the application.
1247 }
1248
1249 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001250 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001251 "Need to start app ["
1252 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1253 if ((r.curApp=mService.startProcessLocked(targetProcess,
1254 info.activityInfo.applicationInfo, true,
1255 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1256 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001257 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001258 == null) {
1259 // Ah, this recipient is unavailable. Finish it if necessary,
1260 // and mark the broadcast record as ready for the next.
1261 Slog.w(TAG, "Unable to launch app "
1262 + info.activityInfo.applicationInfo.packageName + "/"
1263 + info.activityInfo.applicationInfo.uid + " for broadcast "
1264 + r.intent + ": process is bad");
1265 logBroadcastReceiverDiscardLocked(r);
1266 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001267 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001268 scheduleBroadcastsLocked();
1269 r.state = BroadcastRecord.IDLE;
1270 return;
1271 }
1272
1273 mPendingBroadcast = r;
1274 mPendingBroadcastRecvIndex = recIdx;
1275 }
1276 }
1277
1278 final void setBroadcastTimeoutLocked(long timeoutTime) {
1279 if (! mPendingBroadcastTimeoutMessage) {
1280 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1281 mHandler.sendMessageAtTime(msg, timeoutTime);
1282 mPendingBroadcastTimeoutMessage = true;
1283 }
1284 }
1285
1286 final void cancelBroadcastTimeoutLocked() {
1287 if (mPendingBroadcastTimeoutMessage) {
1288 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1289 mPendingBroadcastTimeoutMessage = false;
1290 }
1291 }
1292
1293 final void broadcastTimeoutLocked(boolean fromMsg) {
1294 if (fromMsg) {
1295 mPendingBroadcastTimeoutMessage = false;
1296 }
1297
1298 if (mOrderedBroadcasts.size() == 0) {
1299 return;
1300 }
1301
1302 long now = SystemClock.uptimeMillis();
1303 BroadcastRecord r = mOrderedBroadcasts.get(0);
1304 if (fromMsg) {
1305 if (mService.mDidDexOpt) {
1306 // Delay timeouts until dexopt finishes.
1307 mService.mDidDexOpt = false;
1308 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1309 setBroadcastTimeoutLocked(timeoutTime);
1310 return;
1311 }
1312 if (!mService.mProcessesReady) {
1313 // Only process broadcast timeouts if the system is ready. That way
1314 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1315 // to do heavy lifting for system up.
1316 return;
1317 }
1318
1319 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1320 if (timeoutTime > now) {
1321 // We can observe premature timeouts because we do not cancel and reset the
1322 // broadcast timeout message after each receiver finishes. Instead, we set up
1323 // an initial timeout then kick it down the road a little further as needed
1324 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001325 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001326 "Premature timeout ["
1327 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1328 + timeoutTime);
1329 setBroadcastTimeoutLocked(timeoutTime);
1330 return;
1331 }
1332 }
1333
Dianne Hackborn6285a322013-09-18 12:09:47 -07001334 BroadcastRecord br = mOrderedBroadcasts.get(0);
1335 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1336 // In this case the broadcast had already finished, but we had decided to wait
1337 // for started services to finish as well before going on. So if we have actually
1338 // waited long enough time timeout the broadcast, let's give up on the whole thing
1339 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001340 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001341 ? br.curComponent.flattenToShortString() : "(null)"));
1342 br.curComponent = null;
1343 br.state = BroadcastRecord.IDLE;
1344 processNextBroadcast(false);
1345 return;
1346 }
1347
1348 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001349 + ", started " + (now - r.receiverTime) + "ms ago");
1350 r.receiverTime = now;
1351 r.anrCount++;
1352
1353 // Current receiver has passed its expiration date.
1354 if (r.nextReceiver <= 0) {
1355 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1356 return;
1357 }
1358
1359 ProcessRecord app = null;
1360 String anrMessage = null;
1361
1362 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001363 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001364 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1365 logBroadcastReceiverDiscardLocked(r);
1366 if (curReceiver instanceof BroadcastFilter) {
1367 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1368 if (bf.receiverList.pid != 0
1369 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1370 synchronized (mService.mPidsSelfLocked) {
1371 app = mService.mPidsSelfLocked.get(
1372 bf.receiverList.pid);
1373 }
1374 }
1375 } else {
1376 app = r.curApp;
1377 }
1378
1379 if (app != null) {
1380 anrMessage = "Broadcast of " + r.intent.toString();
1381 }
1382
1383 if (mPendingBroadcast == r) {
1384 mPendingBroadcast = null;
1385 }
1386
1387 // Move on to the next receiver.
1388 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001389 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001390 scheduleBroadcastsLocked();
1391
1392 if (anrMessage != null) {
1393 // Post the ANR to the handler since we do not want to process ANRs while
1394 // potentially holding our lock.
1395 mHandler.post(new AppNotResponding(app, anrMessage));
1396 }
1397 }
1398
Christopher Tatef278f122015-04-22 13:12:01 -07001399 private final int ringAdvance(int x, final int increment, final int ringSize) {
1400 x += increment;
1401 if (x < 0) return (ringSize - 1);
1402 else if (x >= ringSize) return 0;
1403 else return x;
1404 }
1405
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001406 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1407 if (r.callingUid < 0) {
1408 // This was from a registerReceiver() call; ignore it.
1409 return;
1410 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001411 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001412
1413 mBroadcastHistory[mHistoryNext] = r;
1414 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1415
1416 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1417 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1418 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1419 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1420 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001421 }
1422
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001423 boolean cleanupDisabledPackageReceiversLocked(
1424 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1425 boolean didSomething = false;
1426 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1427 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1428 packageName, filterByClasses, userId, doit);
1429 if (!doit && didSomething) {
1430 return true;
1431 }
1432 }
1433
1434 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1435 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1436 packageName, filterByClasses, userId, doit);
1437 if (!doit && didSomething) {
1438 return true;
1439 }
1440 }
1441
1442 return didSomething;
1443 }
1444
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001445 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001446 final int logIndex = r.nextReceiver - 1;
1447 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1448 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001449 if (curReceiver instanceof BroadcastFilter) {
1450 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1451 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001452 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001453 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001454 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001455 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001456 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001457 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001458 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001459 }
1460 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001461 if (logIndex < 0) Slog.w(TAG,
1462 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001463 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001464 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001465 r.intent.getAction(),
1466 r.nextReceiver,
1467 "NONE");
1468 }
1469 }
1470
1471 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1472 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001473 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001474 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1475 || mPendingBroadcast != null) {
1476 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001477 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001478 BroadcastRecord br = mParallelBroadcasts.get(i);
1479 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1480 continue;
1481 }
1482 if (!printed) {
1483 if (needSep) {
1484 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001485 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001486 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 printed = true;
1488 pw.println(" Active broadcasts [" + mQueueName + "]:");
1489 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001490 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001491 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001492 }
1493 printed = false;
1494 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001495 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001496 BroadcastRecord br = mOrderedBroadcasts.get(i);
1497 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1498 continue;
1499 }
1500 if (!printed) {
1501 if (needSep) {
1502 pw.println();
1503 }
1504 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001505 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001506 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1507 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001508 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001509 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001510 }
1511 if (dumpPackage == null || (mPendingBroadcast != null
1512 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1513 if (needSep) {
1514 pw.println();
1515 }
1516 pw.println(" Pending broadcast [" + mQueueName + "]:");
1517 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001518 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001519 } else {
1520 pw.println(" (null)");
1521 }
1522 needSep = true;
1523 }
1524 }
1525
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001526 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001527 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001528
1529 i = -1;
1530 int lastIndex = mHistoryNext;
1531 int ringIndex = lastIndex;
1532 do {
1533 // increasing index = more recent entry, and we want to print the most
1534 // recent first and work backwards, so we roll through the ring backwards.
1535 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1536 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001537 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001538 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001539 }
Christopher Tatef278f122015-04-22 13:12:01 -07001540
1541 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001542 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1543 continue;
1544 }
1545 if (!printed) {
1546 if (needSep) {
1547 pw.println();
1548 }
1549 needSep = true;
1550 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1551 printed = true;
1552 }
1553 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001554 pw.print(" Historical Broadcast " + mQueueName + " #");
1555 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001556 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001557 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001558 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1559 pw.print(" ");
1560 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001561 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1562 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1563 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001564 Bundle bundle = r.intent.getExtras();
1565 if (bundle != null) {
1566 pw.print(" extras: "); pw.println(bundle.toString());
1567 }
1568 }
Christopher Tatef278f122015-04-22 13:12:01 -07001569 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001570
1571 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001572 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001573 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001574 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001575 i = -1;
1576 } else {
1577 // roll over the 'i' full dumps that have already been issued
1578 for (int j = i;
1579 j > 0 && ringIndex != lastIndex;) {
1580 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1581 BroadcastRecord r = mBroadcastHistory[ringIndex];
1582 if (r == null) {
1583 continue;
1584 }
1585 j--;
1586 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001587 }
Christopher Tatef278f122015-04-22 13:12:01 -07001588 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1589 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001590 do {
1591 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1592 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001593 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001594 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001595 }
1596 if (!printed) {
1597 if (needSep) {
1598 pw.println();
1599 }
1600 needSep = true;
1601 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1602 printed = true;
1603 }
1604 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001605 pw.println(" ...");
1606 break;
1607 }
Christopher Tatef278f122015-04-22 13:12:01 -07001608 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001609 pw.print(" #"); pw.print(i); pw.print(": ");
1610 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001611 pw.print(" ");
1612 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1613 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1614 pw.print(" dispatch ");
1615 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1616 - mSummaryHistoryDispatchTime[ringIndex], pw);
1617 pw.println(" finish");
1618 pw.print(" enq=");
1619 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1620 pw.print(" disp=");
1621 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1622 pw.print(" fin=");
1623 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001624 Bundle bundle = intent.getExtras();
1625 if (bundle != null) {
1626 pw.print(" extras: "); pw.println(bundle.toString());
1627 }
Christopher Tatef278f122015-04-22 13:12:01 -07001628 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001629 }
1630
1631 return needSep;
1632 }
1633}