blob: b1609819403ab1941a5dcd88cfabde133f7e5885 [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;
Svet Ganov9c165d72015-12-01 19:52:26 -080053import com.android.server.LocalServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080054
Wale Ogunwaled57969f2014-11-15 19:37:29 -080055import static com.android.server.am.ActivityManagerDebugConfig.*;
56
Dianne Hackborn40c8db52012-02-10 18:59:48 -080057/**
58 * BROADCASTS
59 *
60 * We keep two broadcast queues and associated bookkeeping, one for those at
61 * foreground priority, and one for normal (background-priority) broadcasts.
62 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070063public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070064 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080065 private static final String TAG_MU = TAG + POSTFIX_MU;
66 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080067
Dianne Hackborn4c51de42013-10-16 23:34:35 -070068 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070069 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070070 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080071
72 final ActivityManagerService mService;
73
74 /**
75 * Recognizable moniker for this queue
76 */
77 final String mQueueName;
78
79 /**
80 * Timeout period for this queue's broadcasts
81 */
82 final long mTimeoutPeriod;
83
84 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070085 * If true, we can delay broadcasts while waiting services to finish in the previous
86 * receiver's process.
87 */
88 final boolean mDelayBehindServices;
89
90 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080091 * Lists of all active broadcasts that are to be executed immediately
92 * (without waiting for another broadcast to finish). Currently this only
93 * contains broadcasts to registered receivers, to avoid spinning up
94 * a bunch of processes to execute IntentReceiver components. Background-
95 * and foreground-priority broadcasts are queued separately.
96 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070097 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070098
Dianne Hackborn40c8db52012-02-10 18:59:48 -080099 /**
100 * List of all active broadcasts that are to be executed one at a time.
101 * The object at the top of the list is the currently activity broadcasts;
102 * those after it are waiting for the top to finish. As with parallel
103 * broadcasts, separate background- and foreground-priority queues are
104 * maintained.
105 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700106 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800107
108 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700109 * Historical data of past broadcasts, for debugging. This is a ring buffer
110 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800111 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700112 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700113 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800114
115 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700116 * Summary of historical data of past broadcasts, for debugging. This is a
117 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700118 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700119 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700120 int mSummaryHistoryNext = 0;
121
122 /**
123 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
124 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
125 * clock time, not elapsed.
126 */
127 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
128 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
129 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700130
131 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800132 * Set when we current have a BROADCAST_INTENT_MSG in flight.
133 */
134 boolean mBroadcastsScheduled = false;
135
136 /**
137 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
138 */
139 boolean mPendingBroadcastTimeoutMessage;
140
141 /**
142 * Intent broadcasts that we have tried to start, but are
143 * waiting for the application's process to be created. We only
144 * need one per scheduling class (instead of a list) because we always
145 * process broadcasts one at a time, so no others can be started while
146 * waiting for this one.
147 */
148 BroadcastRecord mPendingBroadcast = null;
149
150 /**
151 * The receiver index that is pending, to restart the broadcast if needed.
152 */
153 int mPendingBroadcastRecvIndex;
154
155 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
156 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700157 static final int SCHEDULE_TEMP_WHITELIST_MSG
158 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800159
Jeff Brown6f357d32014-01-15 20:40:55 -0800160 final BroadcastHandler mHandler;
161
162 private final class BroadcastHandler extends Handler {
163 public BroadcastHandler(Looper looper) {
164 super(looper, null, true);
165 }
166
167 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800168 public void handleMessage(Message msg) {
169 switch (msg.what) {
170 case BROADCAST_INTENT_MSG: {
171 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800172 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800173 processNextBroadcast(true);
174 } break;
175 case BROADCAST_TIMEOUT_MSG: {
176 synchronized (mService) {
177 broadcastTimeoutLocked(true);
178 }
179 } break;
Dianne Hackborna750a632015-06-16 17:18:23 -0700180 case SCHEDULE_TEMP_WHITELIST_MSG: {
181 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
182 if (dic != null) {
183 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700184 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700185 }
186 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800187 }
188 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800189 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800190
191 private final class AppNotResponding implements Runnable {
192 private final ProcessRecord mApp;
193 private final String mAnnotation;
194
195 public AppNotResponding(ProcessRecord app, String annotation) {
196 mApp = app;
197 mAnnotation = annotation;
198 }
199
200 @Override
201 public void run() {
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700202 mService.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800203 }
204 }
205
Jeff Brown6f357d32014-01-15 20:40:55 -0800206 BroadcastQueue(ActivityManagerService service, Handler handler,
207 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800208 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800209 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800210 mQueueName = name;
211 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700212 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800213 }
214
215 public boolean isPendingBroadcastProcessLocked(int pid) {
216 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
217 }
218
219 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
220 mParallelBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700221 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800222 }
223
224 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
225 mOrderedBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700226 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800227 }
228
229 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700230 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800231 if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800232 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800233 "***** DROPPING PARALLEL ["
234 + mQueueName + "]: " + r.intent);
235 mParallelBroadcasts.set(i, r);
236 return true;
237 }
238 }
239 return false;
240 }
241
242 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700243 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800244 if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800245 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800246 "***** DROPPING ORDERED ["
247 + mQueueName + "]: " + r.intent);
248 mOrderedBroadcasts.set(i, r);
249 return true;
250 }
251 }
252 return false;
253 }
254
255 private final void processCurBroadcastLocked(BroadcastRecord r,
256 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800257 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800258 "Process cur broadcast " + r + " for app " + app);
259 if (app.thread == null) {
260 throw new RemoteException();
261 }
262 r.receiver = app.thread.asBinder();
263 r.curApp = app;
264 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700265 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700266 mService.updateLruProcessLocked(app, false, null);
267 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800268
269 // Tell the application to launch this receiver.
270 r.intent.setComponent(r.curComponent);
271
272 boolean started = false;
273 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800274 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275 "Delivering to component " + r.curComponent
276 + ": " + r);
Nicolas Geoffray27c07372015-11-05 16:54:09 +0000277 mService.notifyPackageUse(r.intent.getComponent().getPackageName());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800278 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
279 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700280 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
281 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800282 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800283 "Process cur broadcast " + r + " DELIVERED for app " + app);
284 started = true;
285 } finally {
286 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800287 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800288 "Process cur broadcast " + r + ": NOT STARTED!");
289 r.receiver = null;
290 r.curApp = null;
291 app.curReceiver = null;
292 }
293 }
294 }
295
296 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
297 boolean didSomething = false;
298 final BroadcastRecord br = mPendingBroadcast;
299 if (br != null && br.curApp.pid == app.pid) {
300 try {
301 mPendingBroadcast = null;
302 processCurBroadcastLocked(br, app);
303 didSomething = true;
304 } catch (Exception e) {
305 Slog.w(TAG, "Exception in new application when starting receiver "
306 + br.curComponent.flattenToShortString(), e);
307 logBroadcastReceiverDiscardLocked(br);
308 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700309 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800310 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700311 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800312 br.state = BroadcastRecord.IDLE;
313 throw new RuntimeException(e.getMessage());
314 }
315 }
316 return didSomething;
317 }
318
319 public void skipPendingBroadcastLocked(int pid) {
320 final BroadcastRecord br = mPendingBroadcast;
321 if (br != null && br.curApp.pid == pid) {
322 br.state = BroadcastRecord.IDLE;
323 br.nextReceiver = mPendingBroadcastRecvIndex;
324 mPendingBroadcast = null;
325 scheduleBroadcastsLocked();
326 }
327 }
328
329 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700330 BroadcastRecord r = null;
331 if (mOrderedBroadcasts.size() > 0) {
332 BroadcastRecord br = mOrderedBroadcasts.get(0);
333 if (br.curApp == app) {
334 r = br;
335 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800336 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800337 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800338 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800339 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800340 r = mPendingBroadcast;
341 }
342
343 if (r != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800344 logBroadcastReceiverDiscardLocked(r);
345 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700346 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800347 scheduleBroadcastsLocked();
348 }
349 }
350
351 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800352 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800353 + mQueueName + "]: current="
354 + mBroadcastsScheduled);
355
356 if (mBroadcastsScheduled) {
357 return;
358 }
359 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
360 mBroadcastsScheduled = true;
361 }
362
363 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
364 if (mOrderedBroadcasts.size() > 0) {
365 final BroadcastRecord r = mOrderedBroadcasts.get(0);
366 if (r != null && r.receiver == receiver) {
367 return r;
368 }
369 }
370 return null;
371 }
372
373 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700374 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
375 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700376 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800377 r.state = BroadcastRecord.IDLE;
378 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700379 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800380 }
381 r.receiver = null;
382 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800383 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800384 r.curApp.curReceiver = null;
385 }
386 if (r.curFilter != null) {
387 r.curFilter.receiverList.curBroadcast = null;
388 }
389 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800390 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700391 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800392 mPendingBroadcast = null;
393
394 r.resultCode = resultCode;
395 r.resultData = resultData;
396 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700397 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
398 r.resultAbort = resultAbort;
399 } else {
400 r.resultAbort = false;
401 }
402
403 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
404 && r.queue.mOrderedBroadcasts.size() > 0
405 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700406 ActivityInfo nextReceiver;
407 if (r.nextReceiver < r.receivers.size()) {
408 Object obj = r.receivers.get(r.nextReceiver);
409 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
410 } else {
411 nextReceiver = null;
412 }
413 // Don't do this if the next receive is in the same process as the current one.
414 if (receiver == null || nextReceiver == null
415 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
416 || !receiver.processName.equals(nextReceiver.processName)) {
417 // In this case, we are ready to process the next receiver for the current broadcast,
418 // but are on a queue that would like to wait for services to finish before moving
419 // on. If there are background services currently starting, then we will go into a
420 // special state where we hold off on continuing this broadcast until they are done.
421 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800422 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700423 r.state = BroadcastRecord.WAITING_SERVICES;
424 return false;
425 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700426 }
427 }
428
429 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800430
431 // We will process the next receiver right now if this is finishing
432 // an app receiver (which is always asynchronous) or after we have
433 // come back from calling a receiver.
434 return state == BroadcastRecord.APP_RECEIVE
435 || state == BroadcastRecord.CALL_DONE_RECEIVE;
436 }
437
Dianne Hackborn6285a322013-09-18 12:09:47 -0700438 public void backgroundServicesFinishedLocked(int userId) {
439 if (mOrderedBroadcasts.size() > 0) {
440 BroadcastRecord br = mOrderedBroadcasts.get(0);
441 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800442 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700443 br.curComponent = null;
444 br.state = BroadcastRecord.IDLE;
445 processNextBroadcast(false);
446 }
447 }
448 }
449
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800450 private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
451 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700452 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800453 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000454 if (app != null) {
455 if (app.thread != null) {
456 // If we have an app thread, do the call through that so it is
457 // correctly ordered with other one-way calls.
458 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
459 data, extras, ordered, sticky, sendingUser, app.repProcState);
460 } else {
461 // Application has died. Receiver doesn't exist.
462 throw new RemoteException("app.thread must not be null");
463 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800464 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700465 receiver.performReceive(intent, resultCode, data, extras, ordered,
466 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800467 }
468 }
469
Svet Ganov99b60432015-06-27 13:15:22 -0700470 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800471 BroadcastFilter filter, boolean ordered) {
472 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700473 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800474 int perm = mService.checkComponentPermission(filter.requiredPermission,
475 r.callingPid, r.callingUid, -1, true);
476 if (perm != PackageManager.PERMISSION_GRANTED) {
477 Slog.w(TAG, "Permission Denial: broadcasting "
478 + r.intent.toString()
479 + " from " + r.callerPackage + " (pid="
480 + r.callingPid + ", uid=" + r.callingUid + ")"
481 + " requires " + filter.requiredPermission
482 + " due to registered receiver " + filter);
483 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700484 } else {
485 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
486 if (opCode != AppOpsManager.OP_NONE
487 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
488 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
489 Slog.w(TAG, "Appop Denial: broadcasting "
490 + r.intent.toString()
491 + " from " + r.callerPackage + " (pid="
492 + r.callingPid + ", uid=" + r.callingUid + ")"
493 + " requires appop " + AppOpsManager.permissionToOp(
494 filter.requiredPermission)
495 + " due to registered receiver " + filter);
496 skip = true;
497 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800498 }
499 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700500 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
501 for (int i = 0; i < r.requiredPermissions.length; i++) {
502 String requiredPermission = r.requiredPermissions[i];
503 int perm = mService.checkComponentPermission(requiredPermission,
504 filter.receiverList.pid, filter.receiverList.uid, -1, true);
505 if (perm != PackageManager.PERMISSION_GRANTED) {
506 Slog.w(TAG, "Permission Denial: receiving "
507 + r.intent.toString()
508 + " to " + filter.receiverList.app
509 + " (pid=" + filter.receiverList.pid
510 + ", uid=" + filter.receiverList.uid + ")"
511 + " requires " + requiredPermission
512 + " due to sender " + r.callerPackage
513 + " (uid " + r.callingUid + ")");
514 skip = true;
515 break;
516 }
517 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700518 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700519 && mService.mAppOpsService.noteOperation(appOp,
520 filter.receiverList.uid, filter.packageName)
521 != AppOpsManager.MODE_ALLOWED) {
522 Slog.w(TAG, "Appop Denial: receiving "
523 + r.intent.toString()
524 + " to " + filter.receiverList.app
525 + " (pid=" + filter.receiverList.pid
526 + ", uid=" + filter.receiverList.uid + ")"
527 + " requires appop " + AppOpsManager.permissionToOp(
528 requiredPermission)
529 + " due to sender " + r.callerPackage
530 + " (uid " + r.callingUid + ")");
531 skip = true;
532 break;
533 }
534 }
535 }
536 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
537 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000538 filter.receiverList.pid, filter.receiverList.uid, -1, true);
539 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700540 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000541 + r.intent.toString()
542 + " to " + filter.receiverList.app
543 + " (pid=" + filter.receiverList.pid
544 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000545 + " due to sender " + r.callerPackage
546 + " (uid " + r.callingUid + ")");
547 skip = true;
548 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700549 }
550 if (!skip && r.appOp != AppOpsManager.OP_NONE
551 && mService.mAppOpsService.noteOperation(r.appOp,
552 filter.receiverList.uid, filter.packageName)
553 != AppOpsManager.MODE_ALLOWED) {
554 Slog.w(TAG, "Appop Denial: receiving "
555 + r.intent.toString()
556 + " to " + filter.receiverList.app
557 + " (pid=" + filter.receiverList.pid
558 + ", uid=" + filter.receiverList.uid + ")"
559 + " requires appop " + AppOpsManager.opToName(r.appOp)
560 + " due to sender " + r.callerPackage
561 + " (uid " + r.callingUid + ")");
562 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700563 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700564 if (!skip) {
565 if (!mService.checkAllowBackgroundLocked(filter.receiverList.uid, filter.packageName,
566 -1)) {
567 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)) {
578 return;
Ben Gruver49660c72013-08-06 19:54:08 -0700579 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800580
Dianne Hackborn9357b112013-10-03 18:27:48 -0700581 if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
582 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
583 + " to " + filter.receiverList + ": process crashing");
584 skip = true;
585 }
586
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800587 if (!skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -0800588 // If permissions need a review before any of the app components can run, we drop
589 // the broadcast and if the calling app is in the foreground and the broadcast is
590 // explicit we launch the review UI passing it a pending intent to send the skipped
591 // broadcast.
592 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
593 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
594 filter.owningUserId)) {
595 return;
596 }
597 }
598
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800599 // If this is not being sent as an ordered broadcast, then we
600 // don't want to touch the fields that keep track of the current
601 // state of ordered broadcasts.
602 if (ordered) {
603 r.receiver = filter.receiverList.receiver.asBinder();
604 r.curFilter = filter;
605 filter.receiverList.curBroadcast = r;
606 r.state = BroadcastRecord.CALL_IN_RECEIVE;
607 if (filter.receiverList.app != null) {
608 // Bump hosting application to no longer be in background
609 // scheduling class. Note that we can't do that if there
610 // isn't an app... but we can only be in that case for
611 // things that directly call the IActivityManager API, which
612 // are already core system stuff so don't matter for this.
613 r.curApp = filter.receiverList.app;
614 filter.receiverList.app.curReceiver = r;
Dianne Hackborn684bf342014-04-29 17:56:57 -0700615 mService.updateOomAdjLocked(r.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800616 }
617 }
618 try {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700619 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
620 "Delivering to " + filter + " : " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800621 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700622 new Intent(r.intent), r.resultCode, r.resultData,
623 r.resultExtras, r.ordered, r.initialSticky, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800624 if (ordered) {
625 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
626 }
627 } catch (RemoteException e) {
628 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
629 if (ordered) {
630 r.receiver = null;
631 r.curFilter = null;
632 filter.receiverList.curBroadcast = null;
633 if (filter.receiverList.app != null) {
634 filter.receiverList.app.curReceiver = null;
635 }
636 }
637 }
638 }
639 }
640
Svet Ganov9c165d72015-12-01 19:52:26 -0800641 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
642 BroadcastRecord receiverRecord, String receivingPackageName,
643 final int receivingUserId) {
644 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
645 receivingPackageName, receivingUserId)) {
646 return true;
647 }
648
649 final boolean callerForeground = receiverRecord.callerApp != null
650 ? receiverRecord.callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE
651 : true;
652
653 // Show a permission review UI only for explicit broadcast from a foreground app
654 if (callerForeground && receiverRecord.intent.getComponent() != null) {
655 IIntentSender target = mService.getIntentSenderLocked(
656 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
657 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
658 new Intent[]{receiverRecord.intent},
659 new String[]{receiverRecord.intent.resolveType(mService.mContext
660 .getContentResolver())},
661 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
662 | PendingIntent.FLAG_IMMUTABLE, null);
663
664 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
665 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
666 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
667 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
668 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
669
670 if (DEBUG_PERMISSIONS_REVIEW) {
671 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
672 + receivingPackageName);
673 }
674
675 mHandler.post(new Runnable() {
676 @Override
677 public void run() {
678 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
679 }
680 });
681 } else {
682 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
683 + receivingPackageName + " requires a permissions review");
684 }
685
686 return false;
687 }
688
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700689 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700690 if (duration > Integer.MAX_VALUE) {
691 duration = Integer.MAX_VALUE;
692 }
693 // XXX ideally we should pause the broadcast until everything behind this is done,
694 // or else we will likely start dispatching the broadcast before we have opened
695 // access to the app (there is a lot of asynchronicity behind this). It is probably
696 // not that big a deal, however, because the main purpose here is to allow apps
697 // to hold wake locks, and they will be able to acquire their wake lock immediately
698 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700699 StringBuilder b = new StringBuilder();
700 b.append("broadcast:");
701 UserHandle.formatUid(b, r.callingUid);
702 b.append(":");
703 if (r.intent.getAction() != null) {
704 b.append(r.intent.getAction());
705 } else if (r.intent.getComponent() != null) {
706 b.append(r.intent.getComponent().flattenToShortString());
707 } else if (r.intent.getData() != null) {
708 b.append(r.intent.getData());
709 }
710 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
711 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700712 }
713
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800714 final void processNextBroadcast(boolean fromMsg) {
715 synchronized(mService) {
716 BroadcastRecord r;
717
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800718 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800719 + mQueueName + "]: "
720 + mParallelBroadcasts.size() + " broadcasts, "
721 + mOrderedBroadcasts.size() + " ordered broadcasts");
722
723 mService.updateCpuStats();
724
725 if (fromMsg) {
726 mBroadcastsScheduled = false;
727 }
728
729 // First, deliver any non-serialized broadcasts right away.
730 while (mParallelBroadcasts.size() > 0) {
731 r = mParallelBroadcasts.remove(0);
732 r.dispatchTime = SystemClock.uptimeMillis();
733 r.dispatchClockTime = System.currentTimeMillis();
734 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800735 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800736 + mQueueName + "] " + r);
737 for (int i=0; i<N; i++) {
738 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800739 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800740 "Delivering non-ordered on [" + mQueueName + "] to registered "
741 + target + ": " + r);
742 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
743 }
744 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800745 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800746 + mQueueName + "] " + r);
747 }
748
749 // Now take care of the next serialized one...
750
751 // If we are waiting for a process to come up to handle the next
752 // broadcast, then do nothing at this point. Just in case, we
753 // check that the process we're waiting for still exists.
754 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700755 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
756 "processNextBroadcast [" + mQueueName + "]: waiting for "
757 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800758
759 boolean isDead;
760 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700761 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
762 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800763 }
764 if (!isDead) {
765 // It's still alive, so keep waiting
766 return;
767 } else {
768 Slog.w(TAG, "pending app ["
769 + mQueueName + "]" + mPendingBroadcast.curApp
770 + " died before responding to broadcast");
771 mPendingBroadcast.state = BroadcastRecord.IDLE;
772 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
773 mPendingBroadcast = null;
774 }
775 }
776
777 boolean looped = false;
778
779 do {
780 if (mOrderedBroadcasts.size() == 0) {
781 // No more broadcasts pending, so all done!
782 mService.scheduleAppGcsLocked();
783 if (looped) {
784 // If we had finished the last ordered broadcast, then
785 // make sure all processes have correct oom and sched
786 // adjustments.
787 mService.updateOomAdjLocked();
788 }
789 return;
790 }
791 r = mOrderedBroadcasts.get(0);
792 boolean forceReceive = false;
793
794 // Ensure that even if something goes awry with the timeout
795 // detection, we catch "hung" broadcasts here, discard them,
796 // and continue to make progress.
797 //
798 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
799 // receivers don't get executed with timeouts. They're intended for
800 // one time heavy lifting after system upgrades and can take
801 // significant amounts of time.
802 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
803 if (mService.mProcessesReady && r.dispatchTime > 0) {
804 long now = SystemClock.uptimeMillis();
805 if ((numReceivers > 0) &&
806 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
807 Slog.w(TAG, "Hung broadcast ["
808 + mQueueName + "] discarded after timeout failure:"
809 + " now=" + now
810 + " dispatchTime=" + r.dispatchTime
811 + " startTime=" + r.receiverTime
812 + " intent=" + r.intent
813 + " numReceivers=" + numReceivers
814 + " nextReceiver=" + r.nextReceiver
815 + " state=" + r.state);
816 broadcastTimeoutLocked(false); // forcibly finish this broadcast
817 forceReceive = true;
818 r.state = BroadcastRecord.IDLE;
819 }
820 }
821
822 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800823 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800824 "processNextBroadcast("
825 + mQueueName + ") called when not idle (state="
826 + r.state + ")");
827 return;
828 }
829
830 if (r.receivers == null || r.nextReceiver >= numReceivers
831 || r.resultAbort || forceReceive) {
832 // No more receivers for this broadcast! Send the final
833 // result if requested...
834 if (r.resultTo != null) {
835 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800836 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800837 "Finishing broadcast [" + mQueueName + "] "
838 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800839 performReceiveLocked(r.callerApp, r.resultTo,
840 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700841 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800842 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700843 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800844 r.resultTo = null;
845 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000846 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800847 Slog.w(TAG, "Failure ["
848 + mQueueName + "] sending broadcast result of "
849 + r.intent, e);
850 }
851 }
852
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800853 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800854 cancelBroadcastTimeoutLocked();
855
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700856 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
857 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800858
859 // ... and on to the next...
860 addBroadcastToHistoryLocked(r);
861 mOrderedBroadcasts.remove(0);
862 r = null;
863 looped = true;
864 continue;
865 }
866 } while (r == null);
867
868 // Get the next receiver...
869 int recIdx = r.nextReceiver++;
870
871 // Keep track of when this receiver started, and make sure there
872 // is a timeout message pending to kill it if need be.
873 r.receiverTime = SystemClock.uptimeMillis();
874 if (recIdx == 0) {
875 r.dispatchTime = r.receiverTime;
876 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800877 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800878 + mQueueName + "] " + r);
879 }
880 if (! mPendingBroadcastTimeoutMessage) {
881 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800882 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800883 "Submitting BROADCAST_TIMEOUT_MSG ["
884 + mQueueName + "] for " + r + " at " + timeoutTime);
885 setBroadcastTimeoutLocked(timeoutTime);
886 }
887
Dianne Hackborna750a632015-06-16 17:18:23 -0700888 final BroadcastOptions brOptions = r.options;
889 final Object nextReceiver = r.receivers.get(recIdx);
890
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800891 if (nextReceiver instanceof BroadcastFilter) {
892 // Simple case: this is a registered receiver who gets
893 // a direct call.
894 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800895 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800896 "Delivering ordered ["
897 + mQueueName + "] to registered "
898 + filter + ": " + r);
899 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
900 if (r.receiver == null || !r.ordered) {
901 // The receiver has already finished, so schedule to
902 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800903 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800904 + mQueueName + "]: ordered="
905 + r.ordered + " receiver=" + r.receiver);
906 r.state = BroadcastRecord.IDLE;
907 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700908 } else {
909 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
910 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700911 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700912 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800913 }
914 return;
915 }
916
917 // Hard case: need to instantiate the receiver, possibly
918 // starting its application process to host it.
919
920 ResolveInfo info =
921 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700922 ComponentName component = new ComponentName(
923 info.activityInfo.applicationInfo.packageName,
924 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800925
926 boolean skip = false;
927 int perm = mService.checkComponentPermission(info.activityInfo.permission,
928 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
929 info.activityInfo.exported);
930 if (perm != PackageManager.PERMISSION_GRANTED) {
931 if (!info.activityInfo.exported) {
932 Slog.w(TAG, "Permission Denial: broadcasting "
933 + r.intent.toString()
934 + " from " + r.callerPackage + " (pid=" + r.callingPid
935 + ", uid=" + r.callingUid + ")"
936 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700937 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800938 } else {
939 Slog.w(TAG, "Permission Denial: broadcasting "
940 + r.intent.toString()
941 + " from " + r.callerPackage + " (pid=" + r.callingPid
942 + ", uid=" + r.callingUid + ")"
943 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700944 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800945 }
946 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700947 } else if (info.activityInfo.permission != null) {
948 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
949 if (opCode != AppOpsManager.OP_NONE
950 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
951 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
952 Slog.w(TAG, "Appop Denial: broadcasting "
953 + r.intent.toString()
954 + " from " + r.callerPackage + " (pid="
955 + r.callingPid + ", uid=" + r.callingUid + ")"
956 + " requires appop " + AppOpsManager.permissionToOp(
957 info.activityInfo.permission)
958 + " due to registered receiver "
959 + component.flattenToShortString());
960 skip = true;
961 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800962 }
Svet Ganov99b60432015-06-27 13:15:22 -0700963 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700964 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
965 for (int i = 0; i < r.requiredPermissions.length; i++) {
966 String requiredPermission = r.requiredPermissions[i];
967 try {
968 perm = AppGlobals.getPackageManager().
969 checkPermission(requiredPermission,
970 info.activityInfo.applicationInfo.packageName,
971 UserHandle
972 .getUserId(info.activityInfo.applicationInfo.uid));
973 } catch (RemoteException e) {
974 perm = PackageManager.PERMISSION_DENIED;
975 }
976 if (perm != PackageManager.PERMISSION_GRANTED) {
977 Slog.w(TAG, "Permission Denial: receiving "
978 + r.intent + " to "
979 + component.flattenToShortString()
980 + " requires " + requiredPermission
981 + " due to sender " + r.callerPackage
982 + " (uid " + r.callingUid + ")");
983 skip = true;
984 break;
985 }
986 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
987 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
988 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000989 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700990 != AppOpsManager.MODE_ALLOWED) {
991 Slog.w(TAG, "Appop Denial: receiving "
992 + r.intent + " to "
993 + component.flattenToShortString()
994 + " requires appop " + AppOpsManager.permissionToOp(
995 requiredPermission)
996 + " due to sender " + r.callerPackage
997 + " (uid " + r.callingUid + ")");
998 skip = true;
999 break;
1000 }
1001 }
1002 }
1003 if (!skip && r.appOp != AppOpsManager.OP_NONE
1004 && mService.mAppOpsService.noteOperation(r.appOp,
1005 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1006 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001007 Slog.w(TAG, "Appop Denial: receiving "
1008 + r.intent + " to "
1009 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001010 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001011 + " due to sender " + r.callerPackage
1012 + " (uid " + r.callingUid + ")");
1013 skip = true;
1014 }
Ben Gruver49660c72013-08-06 19:54:08 -07001015 if (!skip) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001016 if (!mService.checkAllowBackgroundLocked(info.activityInfo.applicationInfo.uid,
1017 info.activityInfo.packageName, -1)) {
1018 Slog.w(TAG, "Background execution not allowed: receiving "
1019 + r.intent + " to "
1020 + component.flattenToShortString());
1021 skip = true;
1022 }
1023 }
1024 if (!skip) {
Ben Gruver49660c72013-08-06 19:54:08 -07001025 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1026 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1027 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001028 boolean isSingleton = false;
1029 try {
1030 isSingleton = mService.isSingleton(info.activityInfo.processName,
1031 info.activityInfo.applicationInfo,
1032 info.activityInfo.name, info.activityInfo.flags);
1033 } catch (SecurityException e) {
1034 Slog.w(TAG, e.getMessage());
1035 skip = true;
1036 }
1037 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1038 if (ActivityManager.checkUidPermission(
1039 android.Manifest.permission.INTERACT_ACROSS_USERS,
1040 info.activityInfo.applicationInfo.uid)
1041 != PackageManager.PERMISSION_GRANTED) {
1042 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1043 + " requests FLAG_SINGLE_USER, but app does not hold "
1044 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1045 skip = true;
1046 }
1047 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001048 if (r.curApp != null && r.curApp.crashing) {
1049 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001050 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1051 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001052 skip = true;
1053 }
Christopher Tateba629da2013-11-13 17:42:28 -08001054 if (!skip) {
1055 boolean isAvailable = false;
1056 try {
1057 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1058 info.activityInfo.packageName,
1059 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1060 } catch (Exception e) {
1061 // all such failures mean we skip this receiver
1062 Slog.w(TAG, "Exception getting recipient info for "
1063 + info.activityInfo.packageName, e);
1064 }
1065 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001066 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1067 "Skipping delivery to " + info.activityInfo.packageName + " / "
1068 + info.activityInfo.applicationInfo.uid
1069 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001070 skip = true;
1071 }
1072 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001073
Svet Ganov9c165d72015-12-01 19:52:26 -08001074 // If permissions need a review before any of the app components can run, we drop
1075 // the broadcast and if the calling app is in the foreground and the broadcast is
1076 // explicit we launch the review UI passing it a pending intent to send the skipped
1077 // broadcast.
1078 if (Build.PERMISSIONS_REVIEW_REQUIRED && !skip) {
1079 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1080 info.activityInfo.packageName, UserHandle.getUserId(
1081 info.activityInfo.applicationInfo.uid))) {
1082 skip = true;
1083 }
1084 }
1085
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001086 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001087 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001088 "Skipping delivery of ordered [" + mQueueName + "] "
1089 + r + " for whatever reason");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001090 r.receiver = null;
1091 r.curFilter = null;
1092 r.state = BroadcastRecord.IDLE;
1093 scheduleBroadcastsLocked();
1094 return;
1095 }
1096
1097 r.state = BroadcastRecord.APP_RECEIVE;
1098 String targetProcess = info.activityInfo.processName;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001099 r.curComponent = component;
Amith Yamasani4b9d79c2014-05-21 19:14:21 -07001100 final int receiverUid = info.activityInfo.applicationInfo.uid;
1101 // If it's a singleton, it needs to be the same app or a special app
1102 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1103 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001104 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001105 }
1106 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001107 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001108 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1109 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1110 + info.activityInfo.applicationInfo.uid);
1111 }
1112
Dianne Hackborna750a632015-06-16 17:18:23 -07001113 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1114 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001115 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001116 }
1117
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001118 // Broadcast is being executed, its package can't be stopped.
1119 try {
1120 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001121 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001122 } catch (RemoteException e) {
1123 } catch (IllegalArgumentException e) {
1124 Slog.w(TAG, "Failed trying to unstop package "
1125 + r.curComponent.getPackageName() + ": " + e);
1126 }
1127
1128 // Is this receiver's application already running?
1129 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001130 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001131 if (app != null && app.thread != null) {
1132 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001133 app.addPackage(info.activityInfo.packageName,
1134 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001135 processCurBroadcastLocked(r, app);
1136 return;
1137 } catch (RemoteException e) {
1138 Slog.w(TAG, "Exception when sending broadcast to "
1139 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001140 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001141 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001142 + r.curComponent + " with " + r.intent, e);
1143 // If some unexpected exception happened, just skip
1144 // this broadcast. At this point we are not in the call
1145 // from a client, so throwing an exception out from here
1146 // will crash the entire system instead of just whoever
1147 // sent the broadcast.
1148 logBroadcastReceiverDiscardLocked(r);
1149 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001150 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001151 scheduleBroadcastsLocked();
1152 // We need to reset the state if we failed to start the receiver.
1153 r.state = BroadcastRecord.IDLE;
1154 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001155 }
1156
1157 // If a dead object exception was thrown -- fall through to
1158 // restart the application.
1159 }
1160
1161 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001162 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001163 "Need to start app ["
1164 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1165 if ((r.curApp=mService.startProcessLocked(targetProcess,
1166 info.activityInfo.applicationInfo, true,
1167 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1168 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001169 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001170 == null) {
1171 // Ah, this recipient is unavailable. Finish it if necessary,
1172 // and mark the broadcast record as ready for the next.
1173 Slog.w(TAG, "Unable to launch app "
1174 + info.activityInfo.applicationInfo.packageName + "/"
1175 + info.activityInfo.applicationInfo.uid + " for broadcast "
1176 + r.intent + ": process is bad");
1177 logBroadcastReceiverDiscardLocked(r);
1178 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001179 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001180 scheduleBroadcastsLocked();
1181 r.state = BroadcastRecord.IDLE;
1182 return;
1183 }
1184
1185 mPendingBroadcast = r;
1186 mPendingBroadcastRecvIndex = recIdx;
1187 }
1188 }
1189
1190 final void setBroadcastTimeoutLocked(long timeoutTime) {
1191 if (! mPendingBroadcastTimeoutMessage) {
1192 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1193 mHandler.sendMessageAtTime(msg, timeoutTime);
1194 mPendingBroadcastTimeoutMessage = true;
1195 }
1196 }
1197
1198 final void cancelBroadcastTimeoutLocked() {
1199 if (mPendingBroadcastTimeoutMessage) {
1200 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1201 mPendingBroadcastTimeoutMessage = false;
1202 }
1203 }
1204
1205 final void broadcastTimeoutLocked(boolean fromMsg) {
1206 if (fromMsg) {
1207 mPendingBroadcastTimeoutMessage = false;
1208 }
1209
1210 if (mOrderedBroadcasts.size() == 0) {
1211 return;
1212 }
1213
1214 long now = SystemClock.uptimeMillis();
1215 BroadcastRecord r = mOrderedBroadcasts.get(0);
1216 if (fromMsg) {
1217 if (mService.mDidDexOpt) {
1218 // Delay timeouts until dexopt finishes.
1219 mService.mDidDexOpt = false;
1220 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1221 setBroadcastTimeoutLocked(timeoutTime);
1222 return;
1223 }
1224 if (!mService.mProcessesReady) {
1225 // Only process broadcast timeouts if the system is ready. That way
1226 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1227 // to do heavy lifting for system up.
1228 return;
1229 }
1230
1231 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1232 if (timeoutTime > now) {
1233 // We can observe premature timeouts because we do not cancel and reset the
1234 // broadcast timeout message after each receiver finishes. Instead, we set up
1235 // an initial timeout then kick it down the road a little further as needed
1236 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001237 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001238 "Premature timeout ["
1239 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1240 + timeoutTime);
1241 setBroadcastTimeoutLocked(timeoutTime);
1242 return;
1243 }
1244 }
1245
Dianne Hackborn6285a322013-09-18 12:09:47 -07001246 BroadcastRecord br = mOrderedBroadcasts.get(0);
1247 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1248 // In this case the broadcast had already finished, but we had decided to wait
1249 // for started services to finish as well before going on. So if we have actually
1250 // waited long enough time timeout the broadcast, let's give up on the whole thing
1251 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001252 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001253 ? br.curComponent.flattenToShortString() : "(null)"));
1254 br.curComponent = null;
1255 br.state = BroadcastRecord.IDLE;
1256 processNextBroadcast(false);
1257 return;
1258 }
1259
1260 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001261 + ", started " + (now - r.receiverTime) + "ms ago");
1262 r.receiverTime = now;
1263 r.anrCount++;
1264
1265 // Current receiver has passed its expiration date.
1266 if (r.nextReceiver <= 0) {
1267 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1268 return;
1269 }
1270
1271 ProcessRecord app = null;
1272 String anrMessage = null;
1273
1274 Object curReceiver = r.receivers.get(r.nextReceiver-1);
1275 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1276 logBroadcastReceiverDiscardLocked(r);
1277 if (curReceiver instanceof BroadcastFilter) {
1278 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1279 if (bf.receiverList.pid != 0
1280 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1281 synchronized (mService.mPidsSelfLocked) {
1282 app = mService.mPidsSelfLocked.get(
1283 bf.receiverList.pid);
1284 }
1285 }
1286 } else {
1287 app = r.curApp;
1288 }
1289
1290 if (app != null) {
1291 anrMessage = "Broadcast of " + r.intent.toString();
1292 }
1293
1294 if (mPendingBroadcast == r) {
1295 mPendingBroadcast = null;
1296 }
1297
1298 // Move on to the next receiver.
1299 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001300 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001301 scheduleBroadcastsLocked();
1302
1303 if (anrMessage != null) {
1304 // Post the ANR to the handler since we do not want to process ANRs while
1305 // potentially holding our lock.
1306 mHandler.post(new AppNotResponding(app, anrMessage));
1307 }
1308 }
1309
Christopher Tatef278f122015-04-22 13:12:01 -07001310 private final int ringAdvance(int x, final int increment, final int ringSize) {
1311 x += increment;
1312 if (x < 0) return (ringSize - 1);
1313 else if (x >= ringSize) return 0;
1314 else return x;
1315 }
1316
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001317 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1318 if (r.callingUid < 0) {
1319 // This was from a registerReceiver() call; ignore it.
1320 return;
1321 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001322 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001323
1324 mBroadcastHistory[mHistoryNext] = r;
1325 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1326
1327 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1328 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1329 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1330 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1331 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001332 }
1333
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001334 boolean cleanupDisabledPackageReceiversLocked(
1335 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1336 boolean didSomething = false;
1337 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1338 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1339 packageName, filterByClasses, userId, doit);
1340 if (!doit && didSomething) {
1341 return true;
1342 }
1343 }
1344
1345 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1346 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1347 packageName, filterByClasses, userId, doit);
1348 if (!doit && didSomething) {
1349 return true;
1350 }
1351 }
1352
1353 return didSomething;
1354 }
1355
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001356 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001357 final int logIndex = r.nextReceiver - 1;
1358 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1359 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001360 if (curReceiver instanceof BroadcastFilter) {
1361 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1362 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001363 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001364 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001365 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001366 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001367 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001368 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001369 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001370 }
1371 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001372 if (logIndex < 0) Slog.w(TAG,
1373 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001374 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001375 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001376 r.intent.getAction(),
1377 r.nextReceiver,
1378 "NONE");
1379 }
1380 }
1381
1382 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1383 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001384 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001385 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1386 || mPendingBroadcast != null) {
1387 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001388 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001389 BroadcastRecord br = mParallelBroadcasts.get(i);
1390 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1391 continue;
1392 }
1393 if (!printed) {
1394 if (needSep) {
1395 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001396 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001397 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001398 printed = true;
1399 pw.println(" Active broadcasts [" + mQueueName + "]:");
1400 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001401 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001402 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001403 }
1404 printed = false;
1405 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001406 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001407 BroadcastRecord br = mOrderedBroadcasts.get(i);
1408 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1409 continue;
1410 }
1411 if (!printed) {
1412 if (needSep) {
1413 pw.println();
1414 }
1415 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001416 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001417 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1418 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001419 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001420 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001421 }
1422 if (dumpPackage == null || (mPendingBroadcast != null
1423 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1424 if (needSep) {
1425 pw.println();
1426 }
1427 pw.println(" Pending broadcast [" + mQueueName + "]:");
1428 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001429 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001430 } else {
1431 pw.println(" (null)");
1432 }
1433 needSep = true;
1434 }
1435 }
1436
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001437 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001438 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001439
1440 i = -1;
1441 int lastIndex = mHistoryNext;
1442 int ringIndex = lastIndex;
1443 do {
1444 // increasing index = more recent entry, and we want to print the most
1445 // recent first and work backwards, so we roll through the ring backwards.
1446 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1447 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001448 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001449 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001450 }
Christopher Tatef278f122015-04-22 13:12:01 -07001451
1452 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001453 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1454 continue;
1455 }
1456 if (!printed) {
1457 if (needSep) {
1458 pw.println();
1459 }
1460 needSep = true;
1461 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1462 printed = true;
1463 }
1464 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001465 pw.print(" Historical Broadcast " + mQueueName + " #");
1466 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001467 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001468 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001469 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1470 pw.print(" ");
1471 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001472 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1473 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1474 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001475 Bundle bundle = r.intent.getExtras();
1476 if (bundle != null) {
1477 pw.print(" extras: "); pw.println(bundle.toString());
1478 }
1479 }
Christopher Tatef278f122015-04-22 13:12:01 -07001480 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001481
1482 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001483 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001484 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001485 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001486 i = -1;
1487 } else {
1488 // roll over the 'i' full dumps that have already been issued
1489 for (int j = i;
1490 j > 0 && ringIndex != lastIndex;) {
1491 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1492 BroadcastRecord r = mBroadcastHistory[ringIndex];
1493 if (r == null) {
1494 continue;
1495 }
1496 j--;
1497 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001498 }
Christopher Tatef278f122015-04-22 13:12:01 -07001499 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1500 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001501 do {
1502 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1503 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001504 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001505 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001506 }
1507 if (!printed) {
1508 if (needSep) {
1509 pw.println();
1510 }
1511 needSep = true;
1512 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1513 printed = true;
1514 }
1515 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001516 pw.println(" ...");
1517 break;
1518 }
Christopher Tatef278f122015-04-22 13:12:01 -07001519 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001520 pw.print(" #"); pw.print(i); pw.print(": ");
1521 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001522 pw.print(" ");
1523 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1524 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1525 pw.print(" dispatch ");
1526 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1527 - mSummaryHistoryDispatchTime[ringIndex], pw);
1528 pw.println(" finish");
1529 pw.print(" enq=");
1530 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1531 pw.print(" disp=");
1532 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1533 pw.print(" fin=");
1534 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001535 Bundle bundle = intent.getExtras();
1536 if (bundle != null) {
1537 pw.print(" extras: "); pw.println(bundle.toString());
1538 }
Christopher Tatef278f122015-04-22 13:12:01 -07001539 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001540 }
1541
1542 return needSep;
1543 }
1544}