blob: 37c7765f26e3839afaf76d35c57a999d40d8bf98 [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 }
261 r.receiver = app.thread.asBinder();
262 r.curApp = app;
263 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700264 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700265 mService.updateLruProcessLocked(app, false, null);
266 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800267
268 // Tell the application to launch this receiver.
269 r.intent.setComponent(r.curComponent);
270
271 boolean started = false;
272 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800273 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800274 "Delivering to component " + r.curComponent
275 + ": " + r);
Nicolas Geoffray27c07372015-11-05 16:54:09 +0000276 mService.notifyPackageUse(r.intent.getComponent().getPackageName());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800277 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
278 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700279 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
280 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800281 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800282 "Process cur broadcast " + r + " DELIVERED for app " + app);
283 started = true;
284 } finally {
285 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800286 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800287 "Process cur broadcast " + r + ": NOT STARTED!");
288 r.receiver = null;
289 r.curApp = null;
290 app.curReceiver = null;
291 }
292 }
293 }
294
295 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
296 boolean didSomething = false;
297 final BroadcastRecord br = mPendingBroadcast;
298 if (br != null && br.curApp.pid == app.pid) {
299 try {
300 mPendingBroadcast = null;
301 processCurBroadcastLocked(br, app);
302 didSomething = true;
303 } catch (Exception e) {
304 Slog.w(TAG, "Exception in new application when starting receiver "
305 + br.curComponent.flattenToShortString(), e);
306 logBroadcastReceiverDiscardLocked(br);
307 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700308 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800309 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700310 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800311 br.state = BroadcastRecord.IDLE;
312 throw new RuntimeException(e.getMessage());
313 }
314 }
315 return didSomething;
316 }
317
318 public void skipPendingBroadcastLocked(int pid) {
319 final BroadcastRecord br = mPendingBroadcast;
320 if (br != null && br.curApp.pid == pid) {
321 br.state = BroadcastRecord.IDLE;
322 br.nextReceiver = mPendingBroadcastRecvIndex;
323 mPendingBroadcast = null;
324 scheduleBroadcastsLocked();
325 }
326 }
327
328 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700329 BroadcastRecord r = null;
330 if (mOrderedBroadcasts.size() > 0) {
331 BroadcastRecord br = mOrderedBroadcasts.get(0);
332 if (br.curApp == app) {
333 r = br;
334 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800335 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800336 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800337 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800338 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800339 r = mPendingBroadcast;
340 }
341
342 if (r != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800343 logBroadcastReceiverDiscardLocked(r);
344 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700345 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800346 scheduleBroadcastsLocked();
347 }
348 }
349
350 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800351 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800352 + mQueueName + "]: current="
353 + mBroadcastsScheduled);
354
355 if (mBroadcastsScheduled) {
356 return;
357 }
358 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
359 mBroadcastsScheduled = true;
360 }
361
362 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
363 if (mOrderedBroadcasts.size() > 0) {
364 final BroadcastRecord r = mOrderedBroadcasts.get(0);
365 if (r != null && r.receiver == receiver) {
366 return r;
367 }
368 }
369 return null;
370 }
371
372 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700373 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
374 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700375 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800376 r.state = BroadcastRecord.IDLE;
377 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700378 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800379 }
380 r.receiver = null;
381 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800382 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800383 r.curApp.curReceiver = null;
384 }
385 if (r.curFilter != null) {
386 r.curFilter.receiverList.curBroadcast = null;
387 }
388 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800389 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700390 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800391 mPendingBroadcast = null;
392
393 r.resultCode = resultCode;
394 r.resultData = resultData;
395 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700396 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
397 r.resultAbort = resultAbort;
398 } else {
399 r.resultAbort = false;
400 }
401
402 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
403 && r.queue.mOrderedBroadcasts.size() > 0
404 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700405 ActivityInfo nextReceiver;
406 if (r.nextReceiver < r.receivers.size()) {
407 Object obj = r.receivers.get(r.nextReceiver);
408 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
409 } else {
410 nextReceiver = null;
411 }
412 // Don't do this if the next receive is in the same process as the current one.
413 if (receiver == null || nextReceiver == null
414 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
415 || !receiver.processName.equals(nextReceiver.processName)) {
416 // In this case, we are ready to process the next receiver for the current broadcast,
417 // but are on a queue that would like to wait for services to finish before moving
418 // on. If there are background services currently starting, then we will go into a
419 // special state where we hold off on continuing this broadcast until they are done.
420 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800421 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700422 r.state = BroadcastRecord.WAITING_SERVICES;
423 return false;
424 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700425 }
426 }
427
428 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800429
430 // We will process the next receiver right now if this is finishing
431 // an app receiver (which is always asynchronous) or after we have
432 // come back from calling a receiver.
433 return state == BroadcastRecord.APP_RECEIVE
434 || state == BroadcastRecord.CALL_DONE_RECEIVE;
435 }
436
Dianne Hackborn6285a322013-09-18 12:09:47 -0700437 public void backgroundServicesFinishedLocked(int userId) {
438 if (mOrderedBroadcasts.size() > 0) {
439 BroadcastRecord br = mOrderedBroadcasts.get(0);
440 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800441 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700442 br.curComponent = null;
443 br.state = BroadcastRecord.IDLE;
444 processNextBroadcast(false);
445 }
446 }
447 }
448
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800449 private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
450 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700451 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800452 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000453 if (app != null) {
454 if (app.thread != null) {
455 // If we have an app thread, do the call through that so it is
456 // correctly ordered with other one-way calls.
457 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
458 data, extras, ordered, sticky, sendingUser, app.repProcState);
459 } else {
460 // Application has died. Receiver doesn't exist.
461 throw new RemoteException("app.thread must not be null");
462 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800463 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700464 receiver.performReceive(intent, resultCode, data, extras, ordered,
465 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800466 }
467 }
468
Svet Ganov99b60432015-06-27 13:15:22 -0700469 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800470 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800471 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700472 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800473 int perm = mService.checkComponentPermission(filter.requiredPermission,
474 r.callingPid, r.callingUid, -1, true);
475 if (perm != PackageManager.PERMISSION_GRANTED) {
476 Slog.w(TAG, "Permission Denial: broadcasting "
477 + r.intent.toString()
478 + " from " + r.callerPackage + " (pid="
479 + r.callingPid + ", uid=" + r.callingUid + ")"
480 + " requires " + filter.requiredPermission
481 + " due to registered receiver " + filter);
482 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700483 } else {
484 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
485 if (opCode != AppOpsManager.OP_NONE
486 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
487 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
488 Slog.w(TAG, "Appop Denial: broadcasting "
489 + r.intent.toString()
490 + " from " + r.callerPackage + " (pid="
491 + r.callingPid + ", uid=" + r.callingUid + ")"
492 + " requires appop " + AppOpsManager.permissionToOp(
493 filter.requiredPermission)
494 + " due to registered receiver " + filter);
495 skip = true;
496 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800497 }
498 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700499 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
500 for (int i = 0; i < r.requiredPermissions.length; i++) {
501 String requiredPermission = r.requiredPermissions[i];
502 int perm = mService.checkComponentPermission(requiredPermission,
503 filter.receiverList.pid, filter.receiverList.uid, -1, true);
504 if (perm != PackageManager.PERMISSION_GRANTED) {
505 Slog.w(TAG, "Permission Denial: receiving "
506 + r.intent.toString()
507 + " to " + filter.receiverList.app
508 + " (pid=" + filter.receiverList.pid
509 + ", uid=" + filter.receiverList.uid + ")"
510 + " requires " + requiredPermission
511 + " due to sender " + r.callerPackage
512 + " (uid " + r.callingUid + ")");
513 skip = true;
514 break;
515 }
516 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700517 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700518 && mService.mAppOpsService.noteOperation(appOp,
519 filter.receiverList.uid, filter.packageName)
520 != AppOpsManager.MODE_ALLOWED) {
521 Slog.w(TAG, "Appop Denial: receiving "
522 + r.intent.toString()
523 + " to " + filter.receiverList.app
524 + " (pid=" + filter.receiverList.pid
525 + ", uid=" + filter.receiverList.uid + ")"
526 + " requires appop " + AppOpsManager.permissionToOp(
527 requiredPermission)
528 + " due to sender " + r.callerPackage
529 + " (uid " + r.callingUid + ")");
530 skip = true;
531 break;
532 }
533 }
534 }
535 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
536 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000537 filter.receiverList.pid, filter.receiverList.uid, -1, true);
538 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700539 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000540 + r.intent.toString()
541 + " to " + filter.receiverList.app
542 + " (pid=" + filter.receiverList.pid
543 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000544 + " due to sender " + r.callerPackage
545 + " (uid " + r.callingUid + ")");
546 skip = true;
547 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700548 }
549 if (!skip && r.appOp != AppOpsManager.OP_NONE
550 && mService.mAppOpsService.noteOperation(r.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.opToName(r.appOp)
559 + " due to sender " + r.callerPackage
560 + " (uid " + r.callingUid + ")");
561 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700562 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700563 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800564 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700565 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800566 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700567 Slog.w(TAG, "Background execution not allowed: receiving "
568 + r.intent
569 + " to " + filter.receiverList.app
570 + " (pid=" + filter.receiverList.pid
571 + ", uid=" + filter.receiverList.uid + ")");
572 skip = true;
573 }
574 }
Svet Ganov99b60432015-06-27 13:15:22 -0700575
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700576 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
577 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800578 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700579 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800580
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800581 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700582 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
583 + " to " + filter.receiverList + ": process crashing");
584 skip = true;
585 }
586
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800587 if (skip) {
588 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
589 return;
590 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800591
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800592 // If permissions need a review before any of the app components can run, we drop
593 // the broadcast and if the calling app is in the foreground and the broadcast is
594 // explicit we launch the review UI passing it a pending intent to send the skipped
595 // broadcast.
596 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
597 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
598 filter.owningUserId)) {
599 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
600 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800601 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800602 }
603
604 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
605
606 // If this is not being sent as an ordered broadcast, then we
607 // don't want to touch the fields that keep track of the current
608 // state of ordered broadcasts.
609 if (ordered) {
610 r.receiver = filter.receiverList.receiver.asBinder();
611 r.curFilter = filter;
612 filter.receiverList.curBroadcast = r;
613 r.state = BroadcastRecord.CALL_IN_RECEIVE;
614 if (filter.receiverList.app != null) {
615 // Bump hosting application to no longer be in background
616 // scheduling class. Note that we can't do that if there
617 // isn't an app... but we can only be in that case for
618 // things that directly call the IActivityManager API, which
619 // are already core system stuff so don't matter for this.
620 r.curApp = filter.receiverList.app;
621 filter.receiverList.app.curReceiver = r;
622 mService.updateOomAdjLocked(r.curApp);
623 }
624 }
625 try {
626 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
627 "Delivering to " + filter + " : " + r);
628 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
629 new Intent(r.intent), r.resultCode, r.resultData,
630 r.resultExtras, r.ordered, r.initialSticky, r.userId);
631 if (ordered) {
632 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
633 }
634 } catch (RemoteException e) {
635 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
636 if (ordered) {
637 r.receiver = null;
638 r.curFilter = null;
639 filter.receiverList.curBroadcast = null;
640 if (filter.receiverList.app != null) {
641 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800642 }
643 }
644 }
645 }
646
Svet Ganov9c165d72015-12-01 19:52:26 -0800647 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
648 BroadcastRecord receiverRecord, String receivingPackageName,
649 final int receivingUserId) {
650 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
651 receivingPackageName, receivingUserId)) {
652 return true;
653 }
654
655 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800656 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800657 : true;
658
659 // Show a permission review UI only for explicit broadcast from a foreground app
660 if (callerForeground && receiverRecord.intent.getComponent() != null) {
661 IIntentSender target = mService.getIntentSenderLocked(
662 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
663 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
664 new Intent[]{receiverRecord.intent},
665 new String[]{receiverRecord.intent.resolveType(mService.mContext
666 .getContentResolver())},
667 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
668 | PendingIntent.FLAG_IMMUTABLE, null);
669
670 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
671 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
672 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
673 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
674 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
675
676 if (DEBUG_PERMISSIONS_REVIEW) {
677 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
678 + receivingPackageName);
679 }
680
681 mHandler.post(new Runnable() {
682 @Override
683 public void run() {
684 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
685 }
686 });
687 } else {
688 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
689 + receivingPackageName + " requires a permissions review");
690 }
691
692 return false;
693 }
694
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700695 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700696 if (duration > Integer.MAX_VALUE) {
697 duration = Integer.MAX_VALUE;
698 }
699 // XXX ideally we should pause the broadcast until everything behind this is done,
700 // or else we will likely start dispatching the broadcast before we have opened
701 // access to the app (there is a lot of asynchronicity behind this). It is probably
702 // not that big a deal, however, because the main purpose here is to allow apps
703 // to hold wake locks, and they will be able to acquire their wake lock immediately
704 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700705 StringBuilder b = new StringBuilder();
706 b.append("broadcast:");
707 UserHandle.formatUid(b, r.callingUid);
708 b.append(":");
709 if (r.intent.getAction() != null) {
710 b.append(r.intent.getAction());
711 } else if (r.intent.getComponent() != null) {
712 b.append(r.intent.getComponent().flattenToShortString());
713 } else if (r.intent.getData() != null) {
714 b.append(r.intent.getData());
715 }
716 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
717 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700718 }
719
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800720 final void processNextBroadcast(boolean fromMsg) {
721 synchronized(mService) {
722 BroadcastRecord r;
723
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800724 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800725 + mQueueName + "]: "
726 + mParallelBroadcasts.size() + " broadcasts, "
727 + mOrderedBroadcasts.size() + " ordered broadcasts");
728
729 mService.updateCpuStats();
730
731 if (fromMsg) {
732 mBroadcastsScheduled = false;
733 }
734
735 // First, deliver any non-serialized broadcasts right away.
736 while (mParallelBroadcasts.size() > 0) {
737 r = mParallelBroadcasts.remove(0);
738 r.dispatchTime = SystemClock.uptimeMillis();
739 r.dispatchClockTime = System.currentTimeMillis();
740 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800741 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800742 + mQueueName + "] " + r);
743 for (int i=0; i<N; i++) {
744 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800745 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800746 "Delivering non-ordered on [" + mQueueName + "] to registered "
747 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800748 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800749 }
750 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800751 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800752 + mQueueName + "] " + r);
753 }
754
755 // Now take care of the next serialized one...
756
757 // If we are waiting for a process to come up to handle the next
758 // broadcast, then do nothing at this point. Just in case, we
759 // check that the process we're waiting for still exists.
760 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700761 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
762 "processNextBroadcast [" + mQueueName + "]: waiting for "
763 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800764
765 boolean isDead;
766 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700767 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
768 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800769 }
770 if (!isDead) {
771 // It's still alive, so keep waiting
772 return;
773 } else {
774 Slog.w(TAG, "pending app ["
775 + mQueueName + "]" + mPendingBroadcast.curApp
776 + " died before responding to broadcast");
777 mPendingBroadcast.state = BroadcastRecord.IDLE;
778 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
779 mPendingBroadcast = null;
780 }
781 }
782
783 boolean looped = false;
784
785 do {
786 if (mOrderedBroadcasts.size() == 0) {
787 // No more broadcasts pending, so all done!
788 mService.scheduleAppGcsLocked();
789 if (looped) {
790 // If we had finished the last ordered broadcast, then
791 // make sure all processes have correct oom and sched
792 // adjustments.
793 mService.updateOomAdjLocked();
794 }
795 return;
796 }
797 r = mOrderedBroadcasts.get(0);
798 boolean forceReceive = false;
799
800 // Ensure that even if something goes awry with the timeout
801 // detection, we catch "hung" broadcasts here, discard them,
802 // and continue to make progress.
803 //
804 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
805 // receivers don't get executed with timeouts. They're intended for
806 // one time heavy lifting after system upgrades and can take
807 // significant amounts of time.
808 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
809 if (mService.mProcessesReady && r.dispatchTime > 0) {
810 long now = SystemClock.uptimeMillis();
811 if ((numReceivers > 0) &&
812 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
813 Slog.w(TAG, "Hung broadcast ["
814 + mQueueName + "] discarded after timeout failure:"
815 + " now=" + now
816 + " dispatchTime=" + r.dispatchTime
817 + " startTime=" + r.receiverTime
818 + " intent=" + r.intent
819 + " numReceivers=" + numReceivers
820 + " nextReceiver=" + r.nextReceiver
821 + " state=" + r.state);
822 broadcastTimeoutLocked(false); // forcibly finish this broadcast
823 forceReceive = true;
824 r.state = BroadcastRecord.IDLE;
825 }
826 }
827
828 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800829 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800830 "processNextBroadcast("
831 + mQueueName + ") called when not idle (state="
832 + r.state + ")");
833 return;
834 }
835
836 if (r.receivers == null || r.nextReceiver >= numReceivers
837 || r.resultAbort || forceReceive) {
838 // No more receivers for this broadcast! Send the final
839 // result if requested...
840 if (r.resultTo != null) {
841 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800842 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800843 "Finishing broadcast [" + mQueueName + "] "
844 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800845 performReceiveLocked(r.callerApp, r.resultTo,
846 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700847 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800848 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700849 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800850 r.resultTo = null;
851 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000852 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800853 Slog.w(TAG, "Failure ["
854 + mQueueName + "] sending broadcast result of "
855 + r.intent, e);
856 }
857 }
858
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800859 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800860 cancelBroadcastTimeoutLocked();
861
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700862 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
863 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800864
865 // ... and on to the next...
866 addBroadcastToHistoryLocked(r);
867 mOrderedBroadcasts.remove(0);
868 r = null;
869 looped = true;
870 continue;
871 }
872 } while (r == null);
873
874 // Get the next receiver...
875 int recIdx = r.nextReceiver++;
876
877 // Keep track of when this receiver started, and make sure there
878 // is a timeout message pending to kill it if need be.
879 r.receiverTime = SystemClock.uptimeMillis();
880 if (recIdx == 0) {
881 r.dispatchTime = r.receiverTime;
882 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800883 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800884 + mQueueName + "] " + r);
885 }
886 if (! mPendingBroadcastTimeoutMessage) {
887 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800888 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800889 "Submitting BROADCAST_TIMEOUT_MSG ["
890 + mQueueName + "] for " + r + " at " + timeoutTime);
891 setBroadcastTimeoutLocked(timeoutTime);
892 }
893
Dianne Hackborna750a632015-06-16 17:18:23 -0700894 final BroadcastOptions brOptions = r.options;
895 final Object nextReceiver = r.receivers.get(recIdx);
896
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800897 if (nextReceiver instanceof BroadcastFilter) {
898 // Simple case: this is a registered receiver who gets
899 // a direct call.
900 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800901 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800902 "Delivering ordered ["
903 + mQueueName + "] to registered "
904 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800905 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800906 if (r.receiver == null || !r.ordered) {
907 // The receiver has already finished, so schedule to
908 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800909 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800910 + mQueueName + "]: ordered="
911 + r.ordered + " receiver=" + r.receiver);
912 r.state = BroadcastRecord.IDLE;
913 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700914 } else {
915 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
916 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700917 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700918 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800919 }
920 return;
921 }
922
923 // Hard case: need to instantiate the receiver, possibly
924 // starting its application process to host it.
925
926 ResolveInfo info =
927 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700928 ComponentName component = new ComponentName(
929 info.activityInfo.applicationInfo.packageName,
930 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800931
932 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800933 if (brOptions != null &&
934 (info.activityInfo.applicationInfo.targetSdkVersion
935 < brOptions.getMinManifestReceiverApiLevel() ||
936 info.activityInfo.applicationInfo.targetSdkVersion
937 > brOptions.getMaxManifestReceiverApiLevel())) {
938 skip = true;
939 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800940 int perm = mService.checkComponentPermission(info.activityInfo.permission,
941 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
942 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800943 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800944 if (!info.activityInfo.exported) {
945 Slog.w(TAG, "Permission Denial: broadcasting "
946 + r.intent.toString()
947 + " from " + r.callerPackage + " (pid=" + r.callingPid
948 + ", uid=" + r.callingUid + ")"
949 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700950 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800951 } else {
952 Slog.w(TAG, "Permission Denial: broadcasting "
953 + r.intent.toString()
954 + " from " + r.callerPackage + " (pid=" + r.callingPid
955 + ", uid=" + r.callingUid + ")"
956 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700957 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800958 }
959 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800960 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -0700961 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
962 if (opCode != AppOpsManager.OP_NONE
963 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
964 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
965 Slog.w(TAG, "Appop Denial: broadcasting "
966 + r.intent.toString()
967 + " from " + r.callerPackage + " (pid="
968 + r.callingPid + ", uid=" + r.callingUid + ")"
969 + " requires appop " + AppOpsManager.permissionToOp(
970 info.activityInfo.permission)
971 + " due to registered receiver "
972 + component.flattenToShortString());
973 skip = true;
974 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800975 }
Svet Ganov99b60432015-06-27 13:15:22 -0700976 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700977 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
978 for (int i = 0; i < r.requiredPermissions.length; i++) {
979 String requiredPermission = r.requiredPermissions[i];
980 try {
981 perm = AppGlobals.getPackageManager().
982 checkPermission(requiredPermission,
983 info.activityInfo.applicationInfo.packageName,
984 UserHandle
985 .getUserId(info.activityInfo.applicationInfo.uid));
986 } catch (RemoteException e) {
987 perm = PackageManager.PERMISSION_DENIED;
988 }
989 if (perm != PackageManager.PERMISSION_GRANTED) {
990 Slog.w(TAG, "Permission Denial: receiving "
991 + r.intent + " to "
992 + component.flattenToShortString()
993 + " requires " + requiredPermission
994 + " due to sender " + r.callerPackage
995 + " (uid " + r.callingUid + ")");
996 skip = true;
997 break;
998 }
999 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1000 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1001 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001002 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001003 != AppOpsManager.MODE_ALLOWED) {
1004 Slog.w(TAG, "Appop Denial: receiving "
1005 + r.intent + " to "
1006 + component.flattenToShortString()
1007 + " requires appop " + AppOpsManager.permissionToOp(
1008 requiredPermission)
1009 + " due to sender " + r.callerPackage
1010 + " (uid " + r.callingUid + ")");
1011 skip = true;
1012 break;
1013 }
1014 }
1015 }
1016 if (!skip && r.appOp != AppOpsManager.OP_NONE
1017 && mService.mAppOpsService.noteOperation(r.appOp,
1018 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1019 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001020 Slog.w(TAG, "Appop Denial: receiving "
1021 + r.intent + " to "
1022 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001023 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001024 + " due to sender " + r.callerPackage
1025 + " (uid " + r.callingUid + ")");
1026 skip = true;
1027 }
Ben Gruver49660c72013-08-06 19:54:08 -07001028 if (!skip) {
1029 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1030 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1031 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001032 boolean isSingleton = false;
1033 try {
1034 isSingleton = mService.isSingleton(info.activityInfo.processName,
1035 info.activityInfo.applicationInfo,
1036 info.activityInfo.name, info.activityInfo.flags);
1037 } catch (SecurityException e) {
1038 Slog.w(TAG, e.getMessage());
1039 skip = true;
1040 }
1041 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1042 if (ActivityManager.checkUidPermission(
1043 android.Manifest.permission.INTERACT_ACROSS_USERS,
1044 info.activityInfo.applicationInfo.uid)
1045 != PackageManager.PERMISSION_GRANTED) {
1046 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1047 + " requests FLAG_SINGLE_USER, but app does not hold "
1048 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1049 skip = true;
1050 }
1051 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001052 if (r.curApp != null && r.curApp.crashing) {
1053 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001054 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1055 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001056 skip = true;
1057 }
Christopher Tateba629da2013-11-13 17:42:28 -08001058 if (!skip) {
1059 boolean isAvailable = false;
1060 try {
1061 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1062 info.activityInfo.packageName,
1063 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1064 } catch (Exception e) {
1065 // all such failures mean we skip this receiver
1066 Slog.w(TAG, "Exception getting recipient info for "
1067 + info.activityInfo.packageName, e);
1068 }
1069 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001070 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1071 "Skipping delivery to " + info.activityInfo.packageName + " / "
1072 + info.activityInfo.applicationInfo.uid
1073 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001074 skip = true;
1075 }
1076 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001077
Svet Ganov9c165d72015-12-01 19:52:26 -08001078 // If permissions need a review before any of the app components can run, we drop
1079 // the broadcast and if the calling app is in the foreground and the broadcast is
1080 // explicit we launch the review UI passing it a pending intent to send the skipped
1081 // broadcast.
1082 if (Build.PERMISSIONS_REVIEW_REQUIRED && !skip) {
1083 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1084 info.activityInfo.packageName, UserHandle.getUserId(
1085 info.activityInfo.applicationInfo.uid))) {
1086 skip = true;
1087 }
1088 }
1089
Dianne Hackborn76e80092015-12-09 14:15:34 -08001090 // This is safe to do even if we are skipping the broadcast, and we need
1091 // this information now to evaluate whether it is going to be allowed to run.
1092 final int receiverUid = info.activityInfo.applicationInfo.uid;
1093 // If it's a singleton, it needs to be the same app or a special app
1094 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1095 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1096 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1097 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001098 String targetProcess = info.activityInfo.processName;
1099 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1100 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001101
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001102 if (!skip) {
1103 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001104 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1105 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001106 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1107 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001108 // completely disabled from launches, or it was not explicitly sent
1109 // to it and the app is in a state that should not receive it
1110 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001111 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1112 Slog.w(TAG, "Background execution disabled: receiving "
1113 + r.intent + " to "
1114 + component.flattenToShortString());
1115 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001116 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001117 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001118 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001119 && ((r.intent.getFlags()
1120 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001121 Slog.w(TAG, "Background execution not allowed: receiving "
1122 + r.intent + " to "
1123 + component.flattenToShortString());
1124 skip = true;
1125 }
1126 }
1127 }
1128
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001129 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001130 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001131 "Skipping delivery of ordered [" + mQueueName + "] "
1132 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001133 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001134 r.receiver = null;
1135 r.curFilter = null;
1136 r.state = BroadcastRecord.IDLE;
1137 scheduleBroadcastsLocked();
1138 return;
1139 }
1140
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001141 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001142 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001143 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001144 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001145 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001146 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1147 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1148 + info.activityInfo.applicationInfo.uid);
1149 }
1150
Dianne Hackborna750a632015-06-16 17:18:23 -07001151 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1152 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001153 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001154 }
1155
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001156 // Broadcast is being executed, its package can't be stopped.
1157 try {
1158 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001159 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001160 } catch (RemoteException e) {
1161 } catch (IllegalArgumentException e) {
1162 Slog.w(TAG, "Failed trying to unstop package "
1163 + r.curComponent.getPackageName() + ": " + e);
1164 }
1165
1166 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001167 if (app != null && app.thread != null) {
1168 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001169 app.addPackage(info.activityInfo.packageName,
1170 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001171 processCurBroadcastLocked(r, app);
1172 return;
1173 } catch (RemoteException e) {
1174 Slog.w(TAG, "Exception when sending broadcast to "
1175 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001176 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001177 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001178 + r.curComponent + " with " + r.intent, e);
1179 // If some unexpected exception happened, just skip
1180 // this broadcast. At this point we are not in the call
1181 // from a client, so throwing an exception out from here
1182 // will crash the entire system instead of just whoever
1183 // sent the broadcast.
1184 logBroadcastReceiverDiscardLocked(r);
1185 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001186 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001187 scheduleBroadcastsLocked();
1188 // We need to reset the state if we failed to start the receiver.
1189 r.state = BroadcastRecord.IDLE;
1190 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001191 }
1192
1193 // If a dead object exception was thrown -- fall through to
1194 // restart the application.
1195 }
1196
1197 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001198 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001199 "Need to start app ["
1200 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1201 if ((r.curApp=mService.startProcessLocked(targetProcess,
1202 info.activityInfo.applicationInfo, true,
1203 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1204 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001205 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001206 == null) {
1207 // Ah, this recipient is unavailable. Finish it if necessary,
1208 // and mark the broadcast record as ready for the next.
1209 Slog.w(TAG, "Unable to launch app "
1210 + info.activityInfo.applicationInfo.packageName + "/"
1211 + info.activityInfo.applicationInfo.uid + " for broadcast "
1212 + r.intent + ": process is bad");
1213 logBroadcastReceiverDiscardLocked(r);
1214 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001215 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001216 scheduleBroadcastsLocked();
1217 r.state = BroadcastRecord.IDLE;
1218 return;
1219 }
1220
1221 mPendingBroadcast = r;
1222 mPendingBroadcastRecvIndex = recIdx;
1223 }
1224 }
1225
1226 final void setBroadcastTimeoutLocked(long timeoutTime) {
1227 if (! mPendingBroadcastTimeoutMessage) {
1228 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1229 mHandler.sendMessageAtTime(msg, timeoutTime);
1230 mPendingBroadcastTimeoutMessage = true;
1231 }
1232 }
1233
1234 final void cancelBroadcastTimeoutLocked() {
1235 if (mPendingBroadcastTimeoutMessage) {
1236 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1237 mPendingBroadcastTimeoutMessage = false;
1238 }
1239 }
1240
1241 final void broadcastTimeoutLocked(boolean fromMsg) {
1242 if (fromMsg) {
1243 mPendingBroadcastTimeoutMessage = false;
1244 }
1245
1246 if (mOrderedBroadcasts.size() == 0) {
1247 return;
1248 }
1249
1250 long now = SystemClock.uptimeMillis();
1251 BroadcastRecord r = mOrderedBroadcasts.get(0);
1252 if (fromMsg) {
1253 if (mService.mDidDexOpt) {
1254 // Delay timeouts until dexopt finishes.
1255 mService.mDidDexOpt = false;
1256 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1257 setBroadcastTimeoutLocked(timeoutTime);
1258 return;
1259 }
1260 if (!mService.mProcessesReady) {
1261 // Only process broadcast timeouts if the system is ready. That way
1262 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1263 // to do heavy lifting for system up.
1264 return;
1265 }
1266
1267 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1268 if (timeoutTime > now) {
1269 // We can observe premature timeouts because we do not cancel and reset the
1270 // broadcast timeout message after each receiver finishes. Instead, we set up
1271 // an initial timeout then kick it down the road a little further as needed
1272 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001273 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001274 "Premature timeout ["
1275 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1276 + timeoutTime);
1277 setBroadcastTimeoutLocked(timeoutTime);
1278 return;
1279 }
1280 }
1281
Dianne Hackborn6285a322013-09-18 12:09:47 -07001282 BroadcastRecord br = mOrderedBroadcasts.get(0);
1283 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1284 // In this case the broadcast had already finished, but we had decided to wait
1285 // for started services to finish as well before going on. So if we have actually
1286 // waited long enough time timeout the broadcast, let's give up on the whole thing
1287 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001288 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001289 ? br.curComponent.flattenToShortString() : "(null)"));
1290 br.curComponent = null;
1291 br.state = BroadcastRecord.IDLE;
1292 processNextBroadcast(false);
1293 return;
1294 }
1295
1296 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001297 + ", started " + (now - r.receiverTime) + "ms ago");
1298 r.receiverTime = now;
1299 r.anrCount++;
1300
1301 // Current receiver has passed its expiration date.
1302 if (r.nextReceiver <= 0) {
1303 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1304 return;
1305 }
1306
1307 ProcessRecord app = null;
1308 String anrMessage = null;
1309
1310 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001311 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001312 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1313 logBroadcastReceiverDiscardLocked(r);
1314 if (curReceiver instanceof BroadcastFilter) {
1315 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1316 if (bf.receiverList.pid != 0
1317 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1318 synchronized (mService.mPidsSelfLocked) {
1319 app = mService.mPidsSelfLocked.get(
1320 bf.receiverList.pid);
1321 }
1322 }
1323 } else {
1324 app = r.curApp;
1325 }
1326
1327 if (app != null) {
1328 anrMessage = "Broadcast of " + r.intent.toString();
1329 }
1330
1331 if (mPendingBroadcast == r) {
1332 mPendingBroadcast = null;
1333 }
1334
1335 // Move on to the next receiver.
1336 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001337 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001338 scheduleBroadcastsLocked();
1339
1340 if (anrMessage != null) {
1341 // Post the ANR to the handler since we do not want to process ANRs while
1342 // potentially holding our lock.
1343 mHandler.post(new AppNotResponding(app, anrMessage));
1344 }
1345 }
1346
Christopher Tatef278f122015-04-22 13:12:01 -07001347 private final int ringAdvance(int x, final int increment, final int ringSize) {
1348 x += increment;
1349 if (x < 0) return (ringSize - 1);
1350 else if (x >= ringSize) return 0;
1351 else return x;
1352 }
1353
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001354 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1355 if (r.callingUid < 0) {
1356 // This was from a registerReceiver() call; ignore it.
1357 return;
1358 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001359 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001360
1361 mBroadcastHistory[mHistoryNext] = r;
1362 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1363
1364 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1365 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1366 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1367 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1368 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001369 }
1370
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001371 boolean cleanupDisabledPackageReceiversLocked(
1372 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1373 boolean didSomething = false;
1374 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1375 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1376 packageName, filterByClasses, userId, doit);
1377 if (!doit && didSomething) {
1378 return true;
1379 }
1380 }
1381
1382 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1383 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1384 packageName, filterByClasses, userId, doit);
1385 if (!doit && didSomething) {
1386 return true;
1387 }
1388 }
1389
1390 return didSomething;
1391 }
1392
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001393 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001394 final int logIndex = r.nextReceiver - 1;
1395 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1396 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001397 if (curReceiver instanceof BroadcastFilter) {
1398 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1399 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001400 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001401 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001402 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001403 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001404 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001405 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001406 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001407 }
1408 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001409 if (logIndex < 0) Slog.w(TAG,
1410 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001411 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001412 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001413 r.intent.getAction(),
1414 r.nextReceiver,
1415 "NONE");
1416 }
1417 }
1418
1419 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1420 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001421 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001422 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1423 || mPendingBroadcast != null) {
1424 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001425 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001426 BroadcastRecord br = mParallelBroadcasts.get(i);
1427 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1428 continue;
1429 }
1430 if (!printed) {
1431 if (needSep) {
1432 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001433 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001434 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001435 printed = true;
1436 pw.println(" Active broadcasts [" + mQueueName + "]:");
1437 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001438 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001439 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001440 }
1441 printed = false;
1442 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001443 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001444 BroadcastRecord br = mOrderedBroadcasts.get(i);
1445 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1446 continue;
1447 }
1448 if (!printed) {
1449 if (needSep) {
1450 pw.println();
1451 }
1452 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001453 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001454 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1455 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001456 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001457 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001458 }
1459 if (dumpPackage == null || (mPendingBroadcast != null
1460 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1461 if (needSep) {
1462 pw.println();
1463 }
1464 pw.println(" Pending broadcast [" + mQueueName + "]:");
1465 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001466 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001467 } else {
1468 pw.println(" (null)");
1469 }
1470 needSep = true;
1471 }
1472 }
1473
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001474 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001475 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001476
1477 i = -1;
1478 int lastIndex = mHistoryNext;
1479 int ringIndex = lastIndex;
1480 do {
1481 // increasing index = more recent entry, and we want to print the most
1482 // recent first and work backwards, so we roll through the ring backwards.
1483 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1484 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001485 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001486 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 }
Christopher Tatef278f122015-04-22 13:12:01 -07001488
1489 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001490 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1491 continue;
1492 }
1493 if (!printed) {
1494 if (needSep) {
1495 pw.println();
1496 }
1497 needSep = true;
1498 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1499 printed = true;
1500 }
1501 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001502 pw.print(" Historical Broadcast " + mQueueName + " #");
1503 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001504 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001505 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001506 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1507 pw.print(" ");
1508 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001509 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1510 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1511 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001512 Bundle bundle = r.intent.getExtras();
1513 if (bundle != null) {
1514 pw.print(" extras: "); pw.println(bundle.toString());
1515 }
1516 }
Christopher Tatef278f122015-04-22 13:12:01 -07001517 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001518
1519 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001520 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001521 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001522 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001523 i = -1;
1524 } else {
1525 // roll over the 'i' full dumps that have already been issued
1526 for (int j = i;
1527 j > 0 && ringIndex != lastIndex;) {
1528 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1529 BroadcastRecord r = mBroadcastHistory[ringIndex];
1530 if (r == null) {
1531 continue;
1532 }
1533 j--;
1534 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001535 }
Christopher Tatef278f122015-04-22 13:12:01 -07001536 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1537 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001538 do {
1539 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1540 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001541 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001542 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001543 }
1544 if (!printed) {
1545 if (needSep) {
1546 pw.println();
1547 }
1548 needSep = true;
1549 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1550 printed = true;
1551 }
1552 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001553 pw.println(" ...");
1554 break;
1555 }
Christopher Tatef278f122015-04-22 13:12:01 -07001556 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001557 pw.print(" #"); pw.print(i); pw.print(": ");
1558 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001559 pw.print(" ");
1560 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1561 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1562 pw.print(" dispatch ");
1563 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1564 - mSummaryHistoryDispatchTime[ringIndex], pw);
1565 pw.println(" finish");
1566 pw.print(" enq=");
1567 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1568 pw.print(" disp=");
1569 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1570 pw.print(" fin=");
1571 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001572 Bundle bundle = intent.getExtras();
1573 if (bundle != null) {
1574 pw.print(" extras: "); pw.println(bundle.toString());
1575 }
Christopher Tatef278f122015-04-22 13:12:01 -07001576 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001577 }
1578
1579 return needSep;
1580 }
1581}