blob: efb1c445925f7442ae4fa4049cca3cb2e8e55959 [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
Ng Zhi An1eb7d382018-08-24 13:27:54 -070019import static com.android.server.am.ActivityManagerDebugConfig.*;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080020
Dianne Hackborn7d19e022012-08-07 19:12:33 -070021import android.app.ActivityManager;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080022import android.app.AppGlobals;
Dianne Hackbornf51f6122013-02-04 18:23:34 -080023import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070024import android.app.BroadcastOptions;
Svet Ganov9c165d72015-12-01 19:52:26 -080025import android.app.PendingIntent;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080026import android.content.ComponentName;
Christopher Tate2f558d22019-01-17 16:58:31 -080027import android.content.ContentResolver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080028import android.content.IIntentReceiver;
Svet Ganov9c165d72015-12-01 19:52:26 -080029import android.content.IIntentSender;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080030import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080031import android.content.IntentSender;
Dianne Hackborn7d19e022012-08-07 19:12:33 -070032import android.content.pm.ActivityInfo;
Ng Zhi An1eb7d382018-08-24 13:27:54 -070033import android.content.pm.IPackageManager;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080034import android.content.pm.PackageManager;
Ng Zhi An1eb7d382018-08-24 13:27:54 -070035import android.content.pm.PermissionInfo;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080036import android.content.pm.ResolveInfo;
37import android.os.Bundle;
38import android.os.Handler;
39import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080040import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080041import android.os.Message;
42import android.os.Process;
43import android.os.RemoteException;
44import android.os.SystemClock;
Ng Zhi An1eb7d382018-08-24 13:27:54 -070045import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080047import android.util.EventLog;
48import android.util.Slog;
Christopher Tate2f558d22019-01-17 16:58:31 -080049import android.util.SparseIntArray;
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -080050import android.util.StatsLog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070051import android.util.TimeUtils;
Yi Jin129fc6c2017-09-28 15:48:38 -070052import android.util.proto.ProtoOutputStream;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080053
Ng Zhi An1eb7d382018-08-24 13:27:54 -070054import java.io.FileDescriptor;
55import java.io.PrintWriter;
56import java.text.SimpleDateFormat;
57import java.util.ArrayList;
58import java.util.Date;
59import java.util.Set;
Wale Ogunwaled57969f2014-11-15 19:37:29 -080060
Dianne Hackborn40c8db52012-02-10 18:59:48 -080061/**
62 * BROADCASTS
63 *
Ng Zhi An458e0d32018-11-16 14:43:06 -080064 * We keep three broadcast queues and associated bookkeeping, one for those at
65 * foreground priority, and one for normal (background-priority) broadcasts, and one to
66 * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
Dianne Hackborn40c8db52012-02-10 18:59:48 -080067 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070068public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070069 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080070 private static final String TAG_MU = TAG + POSTFIX_MU;
71 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080072
Dianne Hackborn4c51de42013-10-16 23:34:35 -070073 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070074 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070075 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080076
77 final ActivityManagerService mService;
78
79 /**
Christopher Tate2f558d22019-01-17 16:58:31 -080080 * Behavioral parameters such as timeouts and deferral policy, tracking Settings
81 * for runtime configurability
82 */
83 final BroadcastConstants mConstants;
84
85 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080086 * Recognizable moniker for this queue
87 */
88 final String mQueueName;
89
90 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070091 * If true, we can delay broadcasts while waiting services to finish in the previous
92 * receiver's process.
93 */
94 final boolean mDelayBehindServices;
95
96 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080097 * Lists of all active broadcasts that are to be executed immediately
98 * (without waiting for another broadcast to finish). Currently this only
99 * contains broadcasts to registered receivers, to avoid spinning up
100 * a bunch of processes to execute IntentReceiver components. Background-
101 * and foreground-priority broadcasts are queued separately.
102 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700103 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -0700104
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800105 /**
Christopher Tate2f558d22019-01-17 16:58:31 -0800106 * Tracking of the ordered broadcast queue, including deferral policy and alarm
107 * prioritization.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800108 */
Christopher Tate2f558d22019-01-17 16:58:31 -0800109 final BroadcastDispatcher mDispatcher;
110
111 /**
112 * Refcounting for completion callbacks of split/deferred broadcasts. The key
113 * is an opaque integer token assigned lazily when a broadcast is first split
114 * into multiple BroadcastRecord objects.
115 */
116 final SparseIntArray mSplitRefcounts = new SparseIntArray();
117 private int mNextToken = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800118
119 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700120 * Historical data of past broadcasts, for debugging. This is a ring buffer
121 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800122 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700123 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700124 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800125
126 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700127 * Summary of historical data of past broadcasts, for debugging. This is a
128 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700129 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700130 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700131 int mSummaryHistoryNext = 0;
132
133 /**
134 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
135 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
136 * clock time, not elapsed.
137 */
138 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
139 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
140 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700141
142 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800143 * Set when we current have a BROADCAST_INTENT_MSG in flight.
144 */
145 boolean mBroadcastsScheduled = false;
146
147 /**
148 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
149 */
150 boolean mPendingBroadcastTimeoutMessage;
151
152 /**
153 * Intent broadcasts that we have tried to start, but are
154 * waiting for the application's process to be created. We only
155 * need one per scheduling class (instead of a list) because we always
156 * process broadcasts one at a time, so no others can be started while
157 * waiting for this one.
158 */
159 BroadcastRecord mPendingBroadcast = null;
160
161 /**
162 * The receiver index that is pending, to restart the broadcast if needed.
163 */
164 int mPendingBroadcastRecvIndex;
165
166 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
167 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
168
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -0800169 // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
170 boolean mLogLatencyMetrics = true;
171
Jeff Brown6f357d32014-01-15 20:40:55 -0800172 final BroadcastHandler mHandler;
173
174 private final class BroadcastHandler extends Handler {
175 public BroadcastHandler(Looper looper) {
176 super(looper, null, true);
177 }
178
179 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800180 public void handleMessage(Message msg) {
181 switch (msg.what) {
182 case BROADCAST_INTENT_MSG: {
183 if (DEBUG_BROADCAST) Slog.v(
Christopher Tate2f558d22019-01-17 16:58:31 -0800184 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
185 + mQueueName + "]");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800186 processNextBroadcast(true);
187 } break;
188 case BROADCAST_TIMEOUT_MSG: {
189 synchronized (mService) {
190 broadcastTimeoutLocked(true);
191 }
192 } break;
193 }
194 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800195 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800196
197 private final class AppNotResponding implements Runnable {
198 private final ProcessRecord mApp;
199 private final String mAnnotation;
200
201 public AppNotResponding(ProcessRecord app, String annotation) {
202 mApp = app;
203 mAnnotation = annotation;
204 }
205
206 @Override
207 public void run() {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700208 mApp.appNotResponding(null, null, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800209 }
210 }
211
Jeff Brown6f357d32014-01-15 20:40:55 -0800212 BroadcastQueue(ActivityManagerService service, Handler handler,
Christopher Tate2f558d22019-01-17 16:58:31 -0800213 String name, BroadcastConstants constants, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800214 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800215 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800216 mQueueName = name;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700217 mDelayBehindServices = allowDelayBehindServices;
Christopher Tate2f558d22019-01-17 16:58:31 -0800218
219 mConstants = constants;
220 mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
221 }
222
223 void start(ContentResolver resolver) {
224 mDispatcher.start();
225 mConstants.startObserving(mHandler, resolver);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800226 }
227
Jeff Sharkeyfd658132017-05-03 11:38:01 -0600228 @Override
229 public String toString() {
230 return mQueueName;
231 }
232
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800233 public boolean isPendingBroadcastProcessLocked(int pid) {
234 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
235 }
236
237 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
238 mParallelBroadcasts.add(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800239 enqueueBroadcastHelper(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800240 }
241
242 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800243 mDispatcher.enqueueOrderedBroadcastLocked(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800244 enqueueBroadcastHelper(r);
245 }
246
247 /**
248 * Don't call this method directly; call enqueueParallelBroadcastLocked or
249 * enqueueOrderedBroadcastLocked.
250 */
251 private void enqueueBroadcastHelper(BroadcastRecord r) {
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700252 r.enqueueClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -0800253
254 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
255 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
256 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
257 System.identityHashCode(r));
258 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800259 }
260
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800261 /**
262 * Find the same intent from queued parallel broadcast, replace with a new one and return
263 * the old one.
264 */
265 public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
266 return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800267 }
268
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800269 /**
270 * Find the same intent from queued ordered broadcast, replace with a new one and return
271 * the old one.
272 */
273 public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800274 return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800275 }
276
277 private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
278 BroadcastRecord r, String typeForLogging) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700279 final Intent intent = r.intent;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800280 for (int i = queue.size() - 1; i > 0; i--) {
281 final BroadcastRecord old = queue.get(i);
282 if (old.userId == r.userId && intent.filterEquals(old.intent)) {
283 if (DEBUG_BROADCAST) {
284 Slog.v(TAG_BROADCAST, "***** DROPPING "
285 + typeForLogging + " [" + mQueueName + "]: " + intent);
286 }
287 queue.set(i, r);
288 return old;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800289 }
290 }
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800291 return null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800292 }
293
294 private final void processCurBroadcastLocked(BroadcastRecord r,
Amith Yamasani4e820542018-05-09 13:37:20 -0700295 ProcessRecord app, boolean skipOomAdj) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800296 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800297 "Process cur broadcast " + r + " for app " + app);
298 if (app.thread == null) {
299 throw new RemoteException();
300 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700301 if (app.inFullBackup) {
302 skipReceiverLocked(r);
303 return;
304 }
305
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800306 r.receiver = app.thread.asBinder();
307 r.curApp = app;
yangzhenyud509bc92016-08-31 18:26:46 +0800308 app.curReceivers.add(r);
Dianne Hackborna413dc02013-07-12 12:02:55 -0700309 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Amith Yamasani98a00922018-08-21 12:50:30 -0400310 mService.mProcessList.updateLruProcessLocked(app, false, null);
Amith Yamasani4e820542018-05-09 13:37:20 -0700311 if (!skipOomAdj) {
312 mService.updateOomAdjLocked();
313 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800314
315 // Tell the application to launch this receiver.
316 r.intent.setComponent(r.curComponent);
317
318 boolean started = false;
319 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800320 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800321 "Delivering to component " + r.curComponent
322 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700323 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
324 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800325 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
Wale Ogunwale53783742018-09-16 10:21:51 -0700326 mService.compatibilityInfoForPackage(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700327 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700328 app.getReportedProcState());
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800329 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800330 "Process cur broadcast " + r + " DELIVERED for app " + app);
331 started = true;
332 } finally {
333 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800334 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800335 "Process cur broadcast " + r + ": NOT STARTED!");
336 r.receiver = null;
337 r.curApp = null;
yangzhenyud509bc92016-08-31 18:26:46 +0800338 app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800339 }
340 }
341 }
342
343 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
344 boolean didSomething = false;
345 final BroadcastRecord br = mPendingBroadcast;
Sudheer Shankaf6690102017-10-16 10:20:32 -0700346 if (br != null && br.curApp.pid > 0 && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700347 if (br.curApp != app) {
348 Slog.e(TAG, "App mismatch when sending pending broadcast to "
349 + app.processName + ", intended target is " + br.curApp.processName);
350 return false;
351 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800352 try {
353 mPendingBroadcast = null;
Amith Yamasani4e820542018-05-09 13:37:20 -0700354 processCurBroadcastLocked(br, app, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800355 didSomething = true;
356 } catch (Exception e) {
357 Slog.w(TAG, "Exception in new application when starting receiver "
358 + br.curComponent.flattenToShortString(), e);
359 logBroadcastReceiverDiscardLocked(br);
360 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700361 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800362 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700363 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800364 br.state = BroadcastRecord.IDLE;
365 throw new RuntimeException(e.getMessage());
366 }
367 }
368 return didSomething;
369 }
370
371 public void skipPendingBroadcastLocked(int pid) {
372 final BroadcastRecord br = mPendingBroadcast;
373 if (br != null && br.curApp.pid == pid) {
374 br.state = BroadcastRecord.IDLE;
375 br.nextReceiver = mPendingBroadcastRecvIndex;
376 mPendingBroadcast = null;
377 scheduleBroadcastsLocked();
378 }
379 }
380
Christopher Tate2f558d22019-01-17 16:58:31 -0800381 // Skip the current receiver, if any, that is in flight to the given process
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800382 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700383 BroadcastRecord r = null;
Christopher Tate2f558d22019-01-17 16:58:31 -0800384 final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
385 if (curActive != null && curActive.curApp == app) {
386 // confirmed: the current active broadcast is to the given app
387 r = curActive;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800388 }
Christopher Tate2f558d22019-01-17 16:58:31 -0800389
390 // If the current active broadcast isn't this BUT we're waiting for
391 // mPendingBroadcast to spin up the target app, that's what we use.
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800392 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800393 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800394 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800395 r = mPendingBroadcast;
396 }
397
398 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700399 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800400 }
401 }
402
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700403 private void skipReceiverLocked(BroadcastRecord r) {
404 logBroadcastReceiverDiscardLocked(r);
405 finishReceiverLocked(r, r.resultCode, r.resultData,
406 r.resultExtras, r.resultAbort, false);
407 scheduleBroadcastsLocked();
408 }
409
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800410 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800411 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800412 + mQueueName + "]: current="
413 + mBroadcastsScheduled);
414
415 if (mBroadcastsScheduled) {
416 return;
417 }
418 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
419 mBroadcastsScheduled = true;
420 }
421
422 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800423 BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
424 if (br != null && br.receiver == receiver) {
425 return br;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800426 }
427 return null;
428 }
429
Christopher Tate2f558d22019-01-17 16:58:31 -0800430 // > 0 only, no worry about "eventual" recycling
431 private int nextSplitTokenLocked() {
432 int next = mNextToken + 1;
433 if (next <= 0) {
434 next = 1;
435 }
436 mNextToken = next;
437 return next;
438 }
439
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800440 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700441 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
442 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700443 final ActivityInfo receiver = r.curReceiver;
Ng Zhi An1eb7d382018-08-24 13:27:54 -0700444 final long finishTime = SystemClock.uptimeMillis();
Christopher Tate2f558d22019-01-17 16:58:31 -0800445 final long elapsed = finishTime - r.receiverTime;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800446 r.state = BroadcastRecord.IDLE;
447 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700448 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800449 }
Christopher Tate200029a2019-01-29 16:37:44 -0800450 if (r.allowBackgroundActivityStarts && r.curApp != null) {
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000451 if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
452 // if the receiver has run for more than allowed bg activity start timeout,
453 // just remove the token for this process now and we're done
454 r.curApp.removeAllowBackgroundActivityStartsToken(r);
455 } else {
456 // the receiver had run for less than allowed bg activity start timeout,
457 // so allow the process to still start activities from bg for some more time
458 String msgToken = (r.curApp.toShortString() + r.toString()).intern();
459 // first, if there exists a past scheduled request to remove this token, drop
460 // that request - we don't want the token to be swept from under our feet...
461 mHandler.removeCallbacksAndMessages(msgToken);
462 // ...then schedule the removal of the token after the extended timeout
463 mHandler.postAtTime(() -> {
464 if (r.curApp != null) {
465 r.curApp.removeAllowBackgroundActivityStartsToken(r);
466 }
467 }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
468 }
469 }
Christopher Tatec7aa3292018-08-31 19:13:03 -0700470 // If we're abandoning this broadcast before any receivers were actually spun up,
471 // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
472 if (r.nextReceiver > 0) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800473 r.duration[r.nextReceiver - 1] = elapsed;
Christopher Tatec7aa3292018-08-31 19:13:03 -0700474 }
Christopher Tate2f558d22019-01-17 16:58:31 -0800475
476 // if this receiver was slow, impose deferral policy on the app. This will kick in
477 // when processNextBroadcastLocked() next finds this uid as a receiver identity.
Christopher Tate1b72ca32019-01-30 16:25:53 -0800478 if (!r.timeoutExempt) {
479 if (mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
480 if (DEBUG_BROADCAST_DEFERRAL) {
481 Slog.i(TAG, "Broadcast receiver was slow: " + receiver + " br=" + r);
482 }
483 if (r.curApp != null) {
484 mDispatcher.startDeferring(r.curApp.uid);
485 } else {
486 Slog.d(TAG, "finish receiver curApp is null? " + r);
487 }
Christopher Tate2f558d22019-01-17 16:58:31 -0800488 }
Christopher Tate1b72ca32019-01-30 16:25:53 -0800489 } else {
490 if (DEBUG_BROADCAST_DEFERRAL) {
491 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
492 + " is exempt from deferral policy");
Christopher Tate2f558d22019-01-17 16:58:31 -0800493 }
494 }
495
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800496 r.receiver = null;
497 r.intent.setComponent(null);
yangzhenyud509bc92016-08-31 18:26:46 +0800498 if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
499 r.curApp.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800500 }
501 if (r.curFilter != null) {
502 r.curFilter.receiverList.curBroadcast = null;
503 }
504 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800505 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700506 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800507 mPendingBroadcast = null;
508
509 r.resultCode = resultCode;
510 r.resultData = resultData;
511 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700512 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
513 r.resultAbort = resultAbort;
514 } else {
515 r.resultAbort = false;
516 }
517
Christopher Tate2f558d22019-01-17 16:58:31 -0800518 // If we want to wait behind services *AND* we're finishing the head/
519 // active broadcast on its queue
Dianne Hackborn6285a322013-09-18 12:09:47 -0700520 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
Christopher Tate2f558d22019-01-17 16:58:31 -0800521 && r.queue.mDispatcher.getActiveBroadcastLocked() == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700522 ActivityInfo nextReceiver;
523 if (r.nextReceiver < r.receivers.size()) {
524 Object obj = r.receivers.get(r.nextReceiver);
525 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
526 } else {
527 nextReceiver = null;
528 }
529 // Don't do this if the next receive is in the same process as the current one.
530 if (receiver == null || nextReceiver == null
531 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
532 || !receiver.processName.equals(nextReceiver.processName)) {
533 // In this case, we are ready to process the next receiver for the current broadcast,
534 // but are on a queue that would like to wait for services to finish before moving
535 // on. If there are background services currently starting, then we will go into a
536 // special state where we hold off on continuing this broadcast until they are done.
Dianne Hackbornad51be92016-08-16 16:27:36 -0700537 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800538 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700539 r.state = BroadcastRecord.WAITING_SERVICES;
540 return false;
541 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700542 }
543 }
544
545 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800546
547 // We will process the next receiver right now if this is finishing
548 // an app receiver (which is always asynchronous) or after we have
549 // come back from calling a receiver.
550 return state == BroadcastRecord.APP_RECEIVE
551 || state == BroadcastRecord.CALL_DONE_RECEIVE;
552 }
553
Dianne Hackborn6285a322013-09-18 12:09:47 -0700554 public void backgroundServicesFinishedLocked(int userId) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800555 BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
556 if (br != null) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700557 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800558 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700559 br.curComponent = null;
560 br.state = BroadcastRecord.IDLE;
561 processNextBroadcast(false);
562 }
563 }
564 }
565
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700566 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800567 Intent intent, int resultCode, String data, Bundle extras,
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000568 boolean ordered, boolean sticky, int sendingUser)
Michal Karpinski9cbb20b2019-02-05 17:31:50 +0000569 throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800570 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000571 if (app != null) {
572 if (app.thread != null) {
573 // If we have an app thread, do the call through that so it is
574 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700575 try {
576 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700577 data, extras, ordered, sticky, sendingUser, app.getReportedProcState());
Joe Onorato5869d1c2016-04-20 15:38:07 -0700578 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
579 // DeadObjectException when the process isn't actually dead.
580 //} catch (DeadObjectException ex) {
581 // Failed to call into the process. It's dying so just let it die and move on.
582 // throw ex;
583 } catch (RemoteException ex) {
584 // Failed to call into the process. It's either dying or wedged. Kill it gently.
585 synchronized (mService) {
586 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
587 + " (pid " + app.pid + "). Crashing it.");
588 app.scheduleCrash("can't deliver broadcast");
589 }
590 throw ex;
591 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000592 } else {
593 // Application has died. Receiver doesn't exist.
594 throw new RemoteException("app.thread must not be null");
595 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800596 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700597 receiver.performReceive(intent, resultCode, data, extras, ordered,
598 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800599 }
600 }
601
Svet Ganov99b60432015-06-27 13:15:22 -0700602 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800603 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800604 boolean skip = false;
Dianne Hackborn769b2e72018-12-05 08:51:20 -0800605 if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
606 filter.packageName, filter.owningUid)) {
607 Slog.w(TAG, "Association not allowed: broadcasting "
608 + r.intent.toString()
609 + " from " + r.callerPackage + " (pid=" + r.callingPid
610 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
611 + filter);
612 skip = true;
613 }
614 if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
615 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
616 Slog.w(TAG, "Firewall blocked: broadcasting "
617 + r.intent.toString()
618 + " from " + r.callerPackage + " (pid=" + r.callingPid
619 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
620 + filter);
621 skip = true;
622 }
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700623 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800624 int perm = mService.checkComponentPermission(filter.requiredPermission,
625 r.callingPid, r.callingUid, -1, true);
626 if (perm != PackageManager.PERMISSION_GRANTED) {
627 Slog.w(TAG, "Permission Denial: broadcasting "
628 + r.intent.toString()
629 + " from " + r.callerPackage + " (pid="
630 + r.callingPid + ", uid=" + r.callingUid + ")"
631 + " requires " + filter.requiredPermission
632 + " due to registered receiver " + filter);
633 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700634 } else {
635 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
636 if (opCode != AppOpsManager.OP_NONE
637 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
638 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
639 Slog.w(TAG, "Appop Denial: broadcasting "
640 + r.intent.toString()
641 + " from " + r.callerPackage + " (pid="
642 + r.callingPid + ", uid=" + r.callingUid + ")"
643 + " requires appop " + AppOpsManager.permissionToOp(
644 filter.requiredPermission)
645 + " due to registered receiver " + filter);
646 skip = true;
647 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800648 }
649 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700650 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
651 for (int i = 0; i < r.requiredPermissions.length; i++) {
652 String requiredPermission = r.requiredPermissions[i];
653 int perm = mService.checkComponentPermission(requiredPermission,
654 filter.receiverList.pid, filter.receiverList.uid, -1, true);
655 if (perm != PackageManager.PERMISSION_GRANTED) {
656 Slog.w(TAG, "Permission Denial: receiving "
657 + r.intent.toString()
658 + " to " + filter.receiverList.app
659 + " (pid=" + filter.receiverList.pid
660 + ", uid=" + filter.receiverList.uid + ")"
661 + " requires " + requiredPermission
662 + " due to sender " + r.callerPackage
663 + " (uid " + r.callingUid + ")");
664 skip = true;
665 break;
666 }
667 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700668 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700669 && mService.mAppOpsService.noteOperation(appOp,
670 filter.receiverList.uid, filter.packageName)
671 != AppOpsManager.MODE_ALLOWED) {
672 Slog.w(TAG, "Appop Denial: receiving "
673 + r.intent.toString()
674 + " to " + filter.receiverList.app
675 + " (pid=" + filter.receiverList.pid
676 + ", uid=" + filter.receiverList.uid + ")"
677 + " requires appop " + AppOpsManager.permissionToOp(
678 requiredPermission)
679 + " due to sender " + r.callerPackage
680 + " (uid " + r.callingUid + ")");
681 skip = true;
682 break;
683 }
684 }
685 }
686 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
687 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000688 filter.receiverList.pid, filter.receiverList.uid, -1, true);
689 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700690 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000691 + r.intent.toString()
692 + " to " + filter.receiverList.app
693 + " (pid=" + filter.receiverList.pid
694 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000695 + " due to sender " + r.callerPackage
696 + " (uid " + r.callingUid + ")");
697 skip = true;
698 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700699 }
700 if (!skip && r.appOp != AppOpsManager.OP_NONE
701 && mService.mAppOpsService.noteOperation(r.appOp,
702 filter.receiverList.uid, filter.packageName)
703 != AppOpsManager.MODE_ALLOWED) {
704 Slog.w(TAG, "Appop Denial: receiving "
705 + r.intent.toString()
706 + " to " + filter.receiverList.app
707 + " (pid=" + filter.receiverList.pid
708 + ", uid=" + filter.receiverList.uid + ")"
709 + " requires appop " + AppOpsManager.opToName(r.appOp)
710 + " due to sender " + r.callerPackage
711 + " (uid " + r.callingUid + ")");
712 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700713 }
Svet Ganov99b60432015-06-27 13:15:22 -0700714
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700715 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.killed
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700716 || filter.receiverList.app.isCrashing())) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700717 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700718 + " to " + filter.receiverList + ": process gone or crashing");
Dianne Hackborn9357b112013-10-03 18:27:48 -0700719 skip = true;
720 }
721
Chad Brubakerb7e34d52017-02-22 12:36:06 -0800722 // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
723 // visible to Instant Apps.
724 final boolean visibleToInstantApps =
725 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
726
727 if (!skip && !visibleToInstantApps && filter.instantApp
728 && filter.receiverList.uid != r.callingUid) {
729 Slog.w(TAG, "Instant App Denial: receiving "
730 + r.intent.toString()
731 + " to " + filter.receiverList.app
732 + " (pid=" + filter.receiverList.pid
733 + ", uid=" + filter.receiverList.uid + ")"
734 + " due to sender " + r.callerPackage
735 + " (uid " + r.callingUid + ")"
736 + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
737 skip = true;
738 }
739
Chad Brubaker816c83b2017-03-02 10:27:59 -0800740 if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
741 && filter.receiverList.uid != r.callingUid) {
742 Slog.w(TAG, "Instant App Denial: receiving "
743 + r.intent.toString()
744 + " to " + filter.receiverList.app
745 + " (pid=" + filter.receiverList.pid
746 + ", uid=" + filter.receiverList.uid + ")"
747 + " requires receiver be visible to instant apps"
748 + " due to sender " + r.callerPackage
749 + " (uid " + r.callingUid + ")");
750 skip = true;
751 }
752
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800753 if (skip) {
754 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
755 return;
756 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800757
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800758 // If permissions need a review before any of the app components can run, we drop
759 // the broadcast and if the calling app is in the foreground and the broadcast is
760 // explicit we launch the review UI passing it a pending intent to send the skipped
761 // broadcast.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700762 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
763 filter.owningUserId)) {
764 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
765 return;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800766 }
767
768 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
769
770 // If this is not being sent as an ordered broadcast, then we
771 // don't want to touch the fields that keep track of the current
772 // state of ordered broadcasts.
773 if (ordered) {
774 r.receiver = filter.receiverList.receiver.asBinder();
775 r.curFilter = filter;
776 filter.receiverList.curBroadcast = r;
777 r.state = BroadcastRecord.CALL_IN_RECEIVE;
778 if (filter.receiverList.app != null) {
779 // Bump hosting application to no longer be in background
780 // scheduling class. Note that we can't do that if there
781 // isn't an app... but we can only be in that case for
782 // things that directly call the IActivityManager API, which
783 // are already core system stuff so don't matter for this.
784 r.curApp = filter.receiverList.app;
yangzhenyud509bc92016-08-31 18:26:46 +0800785 filter.receiverList.app.curReceivers.add(r);
Amith Yamasani385c3ad2017-05-04 14:27:11 -0700786 mService.updateOomAdjLocked(r.curApp, true);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800787 }
788 }
789 try {
790 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
791 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700792 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
793 // Skip delivery if full backup in progress
794 // If it's an ordered broadcast, we need to continue to the next receiver.
795 if (ordered) {
796 skipReceiverLocked(r);
797 }
798 } else {
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000799 if (r.receiverTime == 0) {
800 r.receiverTime = SystemClock.uptimeMillis();
801 }
802 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700803 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
804 new Intent(r.intent), r.resultCode, r.resultData,
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000805 r.resultExtras, r.ordered, r.initialSticky, r.userId);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700806 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800807 if (ordered) {
808 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
809 }
810 } catch (RemoteException e) {
811 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
812 if (ordered) {
813 r.receiver = null;
814 r.curFilter = null;
815 filter.receiverList.curBroadcast = null;
816 if (filter.receiverList.app != null) {
yangzhenyud509bc92016-08-31 18:26:46 +0800817 filter.receiverList.app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800818 }
819 }
820 }
821 }
822
Svet Ganov9c165d72015-12-01 19:52:26 -0800823 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
824 BroadcastRecord receiverRecord, String receivingPackageName,
825 final int receivingUserId) {
826 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
827 receivingPackageName, receivingUserId)) {
828 return true;
829 }
830
831 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800832 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800833 : true;
834
835 // Show a permission review UI only for explicit broadcast from a foreground app
836 if (callerForeground && receiverRecord.intent.getComponent() != null) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700837 IIntentSender target = mService.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800838 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
839 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
840 new Intent[]{receiverRecord.intent},
841 new String[]{receiverRecord.intent.resolveType(mService.mContext
842 .getContentResolver())},
843 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
844 | PendingIntent.FLAG_IMMUTABLE, null);
845
846 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
847 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800848 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800849 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
850 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
851 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
852
853 if (DEBUG_PERMISSIONS_REVIEW) {
854 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
855 + receivingPackageName);
856 }
857
858 mHandler.post(new Runnable() {
859 @Override
860 public void run() {
861 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
862 }
863 });
864 } else {
865 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
866 + receivingPackageName + " requires a permissions review");
867 }
868
869 return false;
870 }
871
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700872 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700873 if (duration > Integer.MAX_VALUE) {
874 duration = Integer.MAX_VALUE;
875 }
876 // XXX ideally we should pause the broadcast until everything behind this is done,
877 // or else we will likely start dispatching the broadcast before we have opened
878 // access to the app (there is a lot of asynchronicity behind this). It is probably
879 // not that big a deal, however, because the main purpose here is to allow apps
880 // to hold wake locks, and they will be able to acquire their wake lock immediately
881 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700882 StringBuilder b = new StringBuilder();
883 b.append("broadcast:");
884 UserHandle.formatUid(b, r.callingUid);
885 b.append(":");
886 if (r.intent.getAction() != null) {
887 b.append(r.intent.getAction());
888 } else if (r.intent.getComponent() != null) {
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700889 r.intent.getComponent().appendShortString(b);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700890 } else if (r.intent.getData() != null) {
891 b.append(r.intent.getData());
892 }
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700893 mService.tempWhitelistUidLocked(uid, duration, b.toString());
Dianne Hackborna750a632015-06-16 17:18:23 -0700894 }
895
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700896 /**
897 * Return true if all given permissions are signature-only perms.
898 */
899 final boolean isSignaturePerm(String[] perms) {
900 if (perms == null) {
901 return false;
902 }
903 IPackageManager pm = AppGlobals.getPackageManager();
904 for (int i = perms.length-1; i >= 0; i--) {
905 try {
Svetoslav Ganovadb8c522017-07-28 05:46:53 +0000906 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
Christopher Tatecfa39d12019-02-08 18:20:07 -0800907 if (pi == null) {
908 // a required permission that no package has actually
909 // defined cannot be signature-required.
910 return false;
911 }
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700912 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
913 | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
914 != PermissionInfo.PROTECTION_SIGNATURE) {
915 // If this a signature permission and NOT allowed for privileged apps, it
916 // is okay... otherwise, nope!
917 return false;
918 }
919 } catch (RemoteException e) {
920 return false;
921 }
922 }
923 return true;
924 }
925
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800926 final void processNextBroadcast(boolean fromMsg) {
Amith Yamasani4e820542018-05-09 13:37:20 -0700927 synchronized (mService) {
928 processNextBroadcastLocked(fromMsg, false);
929 }
930 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800931
Amith Yamasani4e820542018-05-09 13:37:20 -0700932 final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
933 BroadcastRecord r;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800934
Amith Yamasani4e820542018-05-09 13:37:20 -0700935 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
936 + mQueueName + "]: "
Christopher Tateb486f412019-02-12 18:05:17 -0800937 + mParallelBroadcasts.size() + " parallel broadcasts; "
938 + mDispatcher.describeStateLocked());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800939
Amith Yamasani4e820542018-05-09 13:37:20 -0700940 mService.updateCpuStats();
941
942 if (fromMsg) {
943 mBroadcastsScheduled = false;
944 }
945
946 // First, deliver any non-serialized broadcasts right away.
947 while (mParallelBroadcasts.size() > 0) {
948 r = mParallelBroadcasts.remove(0);
949 r.dispatchTime = SystemClock.uptimeMillis();
950 r.dispatchClockTime = System.currentTimeMillis();
951
952 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
953 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
954 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
955 System.identityHashCode(r));
956 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
957 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
958 System.identityHashCode(r));
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800959 }
960
Amith Yamasani4e820542018-05-09 13:37:20 -0700961 final int N = r.receivers.size();
962 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
963 + mQueueName + "] " + r);
964 for (int i=0; i<N; i++) {
965 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800966 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Amith Yamasani4e820542018-05-09 13:37:20 -0700967 "Delivering non-ordered on [" + mQueueName + "] to registered "
968 + target + ": " + r);
969 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
970 }
971 addBroadcastToHistoryLocked(r);
972 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
973 + mQueueName + "] " + r);
974 }
975
976 // Now take care of the next serialized one...
977
978 // If we are waiting for a process to come up to handle the next
979 // broadcast, then do nothing at this point. Just in case, we
980 // check that the process we're waiting for still exists.
981 if (mPendingBroadcast != null) {
982 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
983 "processNextBroadcast [" + mQueueName + "]: waiting for "
984 + mPendingBroadcast.curApp);
985
986 boolean isDead;
987 if (mPendingBroadcast.curApp.pid > 0) {
988 synchronized (mService.mPidsSelfLocked) {
989 ProcessRecord proc = mService.mPidsSelfLocked.get(
990 mPendingBroadcast.curApp.pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700991 isDead = proc == null || proc.isCrashing();
Amith Yamasani4e820542018-05-09 13:37:20 -0700992 }
993 } else {
Amith Yamasani98a00922018-08-21 12:50:30 -0400994 final ProcessRecord proc = mService.mProcessList.mProcessNames.get(
Amith Yamasani4e820542018-05-09 13:37:20 -0700995 mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
996 isDead = proc == null || !proc.pendingStart;
997 }
998 if (!isDead) {
999 // It's still alive, so keep waiting
1000 return;
1001 } else {
1002 Slog.w(TAG, "pending app ["
1003 + mQueueName + "]" + mPendingBroadcast.curApp
1004 + " died before responding to broadcast");
1005 mPendingBroadcast.state = BroadcastRecord.IDLE;
1006 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1007 mPendingBroadcast = null;
1008 }
1009 }
1010
1011 boolean looped = false;
1012
1013 do {
Christopher Tate2f558d22019-01-17 16:58:31 -08001014 final long now = SystemClock.uptimeMillis();
1015 r = mDispatcher.getNextBroadcastLocked(now);
1016
1017 if (r == null) {
1018 // No more broadcasts are deliverable right now, so all done!
1019 mDispatcher.scheduleDeferralCheckLocked(false);
Amith Yamasani4e820542018-05-09 13:37:20 -07001020 mService.scheduleAppGcsLocked();
1021 if (looped) {
1022 // If we had finished the last ordered broadcast, then
1023 // make sure all processes have correct oom and sched
1024 // adjustments.
1025 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001026 }
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -08001027
1028 // when we have no more ordered broadcast on this queue, stop logging
1029 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1030 mLogLatencyMetrics = false;
1031 }
1032
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001033 return;
1034 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001035
Amith Yamasani4e820542018-05-09 13:37:20 -07001036 boolean forceReceive = false;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001037
Amith Yamasani4e820542018-05-09 13:37:20 -07001038 // Ensure that even if something goes awry with the timeout
1039 // detection, we catch "hung" broadcasts here, discard them,
1040 // and continue to make progress.
1041 //
Christopher Tate1b72ca32019-01-30 16:25:53 -08001042 // This is only done if the system is ready so that early-stage receivers
1043 // don't get executed with timeouts; and of course other timeout-
1044 // exempt broadcasts are ignored.
Amith Yamasani4e820542018-05-09 13:37:20 -07001045 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Christopher Tate1b72ca32019-01-30 16:25:53 -08001046 if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001047 if ((numReceivers > 0) &&
Christopher Tate2f558d22019-01-17 16:58:31 -08001048 (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001049 Slog.w(TAG, "Hung broadcast ["
1050 + mQueueName + "] discarded after timeout failure:"
1051 + " now=" + now
1052 + " dispatchTime=" + r.dispatchTime
1053 + " startTime=" + r.receiverTime
1054 + " intent=" + r.intent
1055 + " numReceivers=" + numReceivers
1056 + " nextReceiver=" + r.nextReceiver
1057 + " state=" + r.state);
1058 broadcastTimeoutLocked(false); // forcibly finish this broadcast
1059 forceReceive = true;
1060 r.state = BroadcastRecord.IDLE;
1061 }
1062 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001063
Amith Yamasani4e820542018-05-09 13:37:20 -07001064 if (r.state != BroadcastRecord.IDLE) {
1065 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1066 "processNextBroadcast("
1067 + mQueueName + ") called when not idle (state="
1068 + r.state + ")");
1069 return;
1070 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001071
Christopher Tate2f558d22019-01-17 16:58:31 -08001072 // Is the current broadcast is done for any reason?
Amith Yamasani4e820542018-05-09 13:37:20 -07001073 if (r.receivers == null || r.nextReceiver >= numReceivers
1074 || r.resultAbort || forceReceive) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001075 // Send the final result if requested
Amith Yamasani4e820542018-05-09 13:37:20 -07001076 if (r.resultTo != null) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001077 boolean sendResult = true;
Amith Yamasani4e820542018-05-09 13:37:20 -07001078
Christopher Tate2f558d22019-01-17 16:58:31 -08001079 // if this was part of a split/deferral complex, update the refcount and only
1080 // send the completion when we clear all of them
1081 if (r.splitToken != 0) {
1082 int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1083 if (newCount == 0) {
1084 // done! clear out this record's bookkeeping and deliver
1085 if (DEBUG_BROADCAST_DEFERRAL) {
1086 Slog.i(TAG, "Sending broadcast completion for split token "
1087 + r.splitToken);
1088 }
1089 mSplitRefcounts.delete(r.splitToken);
1090 } else {
1091 // still have some split broadcast records in flight; update refcount
1092 // and hold off on the callback
1093 if (DEBUG_BROADCAST_DEFERRAL) {
1094 Slog.i(TAG, "Result refcount " + newCount + " for split token "
1095 + r.splitToken + " - not sending completion yet");
1096 }
1097 sendResult = false;
1098 mSplitRefcounts.put(r.splitToken, newCount);
1099 }
1100 }
1101 if (sendResult) {
1102 try {
1103 if (DEBUG_BROADCAST) {
1104 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1105 + r.intent.getAction() + " app=" + r.callerApp);
1106 }
1107 performReceiveLocked(r.callerApp, r.resultTo,
1108 new Intent(r.intent), r.resultCode,
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001109 r.resultData, r.resultExtras, false, false, r.userId);
Christopher Tate2f558d22019-01-17 16:58:31 -08001110 // Set this to null so that the reference
1111 // (local and remote) isn't kept in the mBroadcastHistory.
1112 r.resultTo = null;
1113 } catch (RemoteException e) {
1114 r.resultTo = null;
1115 Slog.w(TAG, "Failure ["
1116 + mQueueName + "] sending broadcast result of "
1117 + r.intent, e);
1118 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001119 }
1120 }
1121
1122 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1123 cancelBroadcastTimeoutLocked();
1124
1125 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1126 "Finished with ordered broadcast " + r);
1127
1128 // ... and on to the next...
1129 addBroadcastToHistoryLocked(r);
1130 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1131 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1132 // This was an implicit broadcast... let's record it for posterity.
1133 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1134 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1135 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001136 mDispatcher.retireBroadcastLocked(r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001137 r = null;
1138 looped = true;
1139 continue;
1140 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001141
1142 // Check whether the next receiver is under deferral policy, and handle that
1143 // accordingly. If the current broadcast was already part of deferred-delivery
1144 // tracking, we know that it must now be deliverable as-is without re-deferral.
1145 if (!r.deferred) {
1146 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1147 if (mDispatcher.isDeferringLocked(receiverUid)) {
1148 if (DEBUG_BROADCAST_DEFERRAL) {
1149 Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1150 + " at " + r.nextReceiver + " is under deferral");
1151 }
1152 // If this is the only (remaining) receiver in the broadcast, "splitting"
1153 // doesn't make sense -- just defer it as-is and retire it as the
1154 // currently active outgoing broadcast.
1155 BroadcastRecord defer;
1156 if (r.nextReceiver + 1 == numReceivers) {
1157 if (DEBUG_BROADCAST_DEFERRAL) {
1158 Slog.i(TAG, "Sole receiver of " + r
1159 + " is under deferral; setting aside and proceeding");
1160 }
1161 defer = r;
1162 mDispatcher.retireBroadcastLocked(r);
1163 } else {
1164 // Nontrivial case; split out 'uid's receivers to a new broadcast record
1165 // and defer that, then loop and pick up continuing delivery of the current
1166 // record (now absent those receivers).
1167
1168 // The split operation is guaranteed to match at least at 'nextReceiver'
1169 defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1170 if (DEBUG_BROADCAST_DEFERRAL) {
1171 Slog.i(TAG_BROADCAST, "Post split:");
1172 Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1173 for (int i = 0; i < r.receivers.size(); i++) {
1174 Slog.i(TAG_BROADCAST, " " + r.receivers.get(i));
1175 }
1176 Slog.i(TAG_BROADCAST, "Split receivers:");
1177 for (int i = 0; i < defer.receivers.size(); i++) {
1178 Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i));
1179 }
1180 }
1181 // Track completion refcount as well if relevant
1182 if (r.resultTo != null) {
1183 int token = r.splitToken;
1184 if (token == 0) {
1185 // first split of this record; refcount for 'r' and 'deferred'
1186 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1187 mSplitRefcounts.put(r.splitToken, 2);
1188 } else {
1189 // new split from an already-refcounted situation; increment count
1190 final int curCount = mSplitRefcounts.get(token);
1191 if (DEBUG_BROADCAST_DEFERRAL) {
1192 if (curCount == 0) {
1193 Slog.wtf(TAG, "Split refcount is zero with token for " + r);
1194 }
1195 }
1196 mSplitRefcounts.put(token, curCount + 1);
1197 }
1198 }
1199 }
1200 mDispatcher.addDeferredBroadcast(receiverUid, defer);
1201 r = null;
1202 looped = true;
1203 continue;
1204 }
1205 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001206 } while (r == null);
1207
1208 // Get the next receiver...
1209 int recIdx = r.nextReceiver++;
1210
1211 // Keep track of when this receiver started, and make sure there
1212 // is a timeout message pending to kill it if need be.
1213 r.receiverTime = SystemClock.uptimeMillis();
1214 if (recIdx == 0) {
1215 r.dispatchTime = r.receiverTime;
1216 r.dispatchClockTime = System.currentTimeMillis();
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -08001217
1218 if (mLogLatencyMetrics) {
1219 StatsLog.write(
1220 StatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1221 r.dispatchClockTime - r.enqueueClockTime);
1222 }
1223
Amith Yamasani4e820542018-05-09 13:37:20 -07001224 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1225 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1226 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1227 System.identityHashCode(r));
1228 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1229 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1230 System.identityHashCode(r));
1231 }
1232 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1233 + mQueueName + "] " + r);
1234 }
1235 if (! mPendingBroadcastTimeoutMessage) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001236 long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
Amith Yamasani4e820542018-05-09 13:37:20 -07001237 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1238 "Submitting BROADCAST_TIMEOUT_MSG ["
1239 + mQueueName + "] for " + r + " at " + timeoutTime);
1240 setBroadcastTimeoutLocked(timeoutTime);
1241 }
1242
1243 final BroadcastOptions brOptions = r.options;
1244 final Object nextReceiver = r.receivers.get(recIdx);
1245
1246 if (nextReceiver instanceof BroadcastFilter) {
1247 // Simple case: this is a registered receiver who gets
1248 // a direct call.
1249 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1250 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1251 "Delivering ordered ["
1252 + mQueueName + "] to registered "
1253 + filter + ": " + r);
1254 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1255 if (r.receiver == null || !r.ordered) {
1256 // The receiver has already finished, so schedule to
1257 // process the next one.
1258 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1259 + mQueueName + "]: ordered="
1260 + r.ordered + " receiver=" + r.receiver);
1261 r.state = BroadcastRecord.IDLE;
1262 scheduleBroadcastsLocked();
1263 } else {
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001264 if (filter.receiverList != null) {
1265 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
1266 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001267 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1268 scheduleTempWhitelistLocked(filter.owningUid,
1269 brOptions.getTemporaryAppWhitelistDuration(), r);
1270 }
1271 }
1272 return;
1273 }
1274
1275 // Hard case: need to instantiate the receiver, possibly
1276 // starting its application process to host it.
1277
1278 ResolveInfo info =
1279 (ResolveInfo)nextReceiver;
1280 ComponentName component = new ComponentName(
1281 info.activityInfo.applicationInfo.packageName,
1282 info.activityInfo.name);
1283
1284 boolean skip = false;
1285 if (brOptions != null &&
1286 (info.activityInfo.applicationInfo.targetSdkVersion
1287 < brOptions.getMinManifestReceiverApiLevel() ||
1288 info.activityInfo.applicationInfo.targetSdkVersion
1289 > brOptions.getMaxManifestReceiverApiLevel())) {
1290 skip = true;
1291 }
Dianne Hackborn769b2e72018-12-05 08:51:20 -08001292 if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
1293 component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
1294 Slog.w(TAG, "Association not allowed: broadcasting "
1295 + r.intent.toString()
1296 + " from " + r.callerPackage + " (pid=" + r.callingPid
1297 + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1298 skip = true;
1299 }
1300 if (!skip) {
1301 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1302 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1303 if (skip) {
1304 Slog.w(TAG, "Firewall blocked: broadcasting "
1305 + r.intent.toString()
1306 + " from " + r.callerPackage + " (pid=" + r.callingPid
1307 + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1308 }
1309 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001310 int perm = mService.checkComponentPermission(info.activityInfo.permission,
1311 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1312 info.activityInfo.exported);
1313 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
1314 if (!info.activityInfo.exported) {
1315 Slog.w(TAG, "Permission Denial: broadcasting "
1316 + r.intent.toString()
1317 + " from " + r.callerPackage + " (pid=" + r.callingPid
1318 + ", uid=" + r.callingUid + ")"
1319 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
1320 + " due to receiver " + component.flattenToShortString());
1321 } else {
1322 Slog.w(TAG, "Permission Denial: broadcasting "
1323 + r.intent.toString()
1324 + " from " + r.callerPackage + " (pid=" + r.callingPid
1325 + ", uid=" + r.callingUid + ")"
1326 + " requires " + info.activityInfo.permission
1327 + " due to receiver " + component.flattenToShortString());
1328 }
1329 skip = true;
1330 } else if (!skip && info.activityInfo.permission != null) {
1331 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1332 if (opCode != AppOpsManager.OP_NONE
1333 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1334 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1335 Slog.w(TAG, "Appop Denial: broadcasting "
1336 + r.intent.toString()
1337 + " from " + r.callerPackage + " (pid="
1338 + r.callingPid + ", uid=" + r.callingUid + ")"
1339 + " requires appop " + AppOpsManager.permissionToOp(
1340 info.activityInfo.permission)
1341 + " due to registered receiver "
1342 + component.flattenToShortString());
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001343 skip = true;
1344 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001345 }
1346 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
1347 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1348 for (int i = 0; i < r.requiredPermissions.length; i++) {
1349 String requiredPermission = r.requiredPermissions[i];
1350 try {
1351 perm = AppGlobals.getPackageManager().
1352 checkPermission(requiredPermission,
1353 info.activityInfo.applicationInfo.packageName,
1354 UserHandle
1355 .getUserId(info.activityInfo.applicationInfo.uid));
1356 } catch (RemoteException e) {
1357 perm = PackageManager.PERMISSION_DENIED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001358 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001359 if (perm != PackageManager.PERMISSION_GRANTED) {
1360 Slog.w(TAG, "Permission Denial: receiving "
1361 + r.intent + " to "
1362 + component.flattenToShortString()
1363 + " requires " + requiredPermission
1364 + " due to sender " + r.callerPackage
1365 + " (uid " + r.callingUid + ")");
1366 skip = true;
1367 break;
1368 }
1369 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1370 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1371 && mService.mAppOpsService.noteOperation(appOp,
1372 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1373 != AppOpsManager.MODE_ALLOWED) {
1374 Slog.w(TAG, "Appop Denial: receiving "
1375 + r.intent + " to "
1376 + component.flattenToShortString()
Svet Ganov99b60432015-06-27 13:15:22 -07001377 + " requires appop " + AppOpsManager.permissionToOp(
Amith Yamasani4e820542018-05-09 13:37:20 -07001378 requiredPermission)
1379 + " due to sender " + r.callerPackage
1380 + " (uid " + r.callingUid + ")");
1381 skip = true;
1382 break;
1383 }
1384 }
1385 }
1386 if (!skip && r.appOp != AppOpsManager.OP_NONE
1387 && mService.mAppOpsService.noteOperation(r.appOp,
1388 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1389 != AppOpsManager.MODE_ALLOWED) {
1390 Slog.w(TAG, "Appop Denial: receiving "
1391 + r.intent + " to "
1392 + component.flattenToShortString()
1393 + " requires appop " + AppOpsManager.opToName(r.appOp)
1394 + " due to sender " + r.callerPackage
1395 + " (uid " + r.callingUid + ")");
1396 skip = true;
1397 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001398 boolean isSingleton = false;
1399 try {
1400 isSingleton = mService.isSingleton(info.activityInfo.processName,
1401 info.activityInfo.applicationInfo,
1402 info.activityInfo.name, info.activityInfo.flags);
1403 } catch (SecurityException e) {
1404 Slog.w(TAG, e.getMessage());
1405 skip = true;
1406 }
1407 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1408 if (ActivityManager.checkUidPermission(
1409 android.Manifest.permission.INTERACT_ACROSS_USERS,
1410 info.activityInfo.applicationInfo.uid)
1411 != PackageManager.PERMISSION_GRANTED) {
1412 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1413 + " requests FLAG_SINGLE_USER, but app does not hold "
1414 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1415 skip = true;
1416 }
1417 }
1418 if (!skip && info.activityInfo.applicationInfo.isInstantApp()
1419 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1420 Slog.w(TAG, "Instant App Denial: receiving "
1421 + r.intent
1422 + " to " + component.flattenToShortString()
1423 + " due to sender " + r.callerPackage
1424 + " (uid " + r.callingUid + ")"
1425 + " Instant Apps do not support manifest receivers");
1426 skip = true;
1427 }
1428 if (!skip && r.callerInstantApp
1429 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
1430 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1431 Slog.w(TAG, "Instant App Denial: receiving "
1432 + r.intent
1433 + " to " + component.flattenToShortString()
1434 + " requires receiver have visibleToInstantApps set"
1435 + " due to sender " + r.callerPackage
1436 + " (uid " + r.callingUid + ")");
1437 skip = true;
1438 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001439 if (r.curApp != null && r.curApp.isCrashing()) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001440 // If the target process is crashing, just skip it.
1441 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1442 + " to " + r.curApp + ": process crashing");
1443 skip = true;
1444 }
1445 if (!skip) {
1446 boolean isAvailable = false;
1447 try {
1448 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1449 info.activityInfo.packageName,
1450 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1451 } catch (Exception e) {
1452 // all such failures mean we skip this receiver
1453 Slog.w(TAG, "Exception getting recipient info for "
1454 + info.activityInfo.packageName, e);
1455 }
1456 if (!isAvailable) {
1457 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1458 "Skipping delivery to " + info.activityInfo.packageName + " / "
1459 + info.activityInfo.applicationInfo.uid
1460 + " : package no longer available");
1461 skip = true;
1462 }
1463 }
1464
1465 // If permissions need a review before any of the app components can run, we drop
1466 // the broadcast and if the calling app is in the foreground and the broadcast is
1467 // explicit we launch the review UI passing it a pending intent to send the skipped
1468 // broadcast.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001469 if (!skip) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001470 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1471 info.activityInfo.packageName, UserHandle.getUserId(
1472 info.activityInfo.applicationInfo.uid))) {
1473 skip = true;
1474 }
1475 }
1476
1477 // This is safe to do even if we are skipping the broadcast, and we need
1478 // this information now to evaluate whether it is going to be allowed to run.
1479 final int receiverUid = info.activityInfo.applicationInfo.uid;
1480 // If it's a singleton, it needs to be the same app or a special app
1481 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1482 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1483 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1484 }
1485 String targetProcess = info.activityInfo.processName;
1486 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1487 info.activityInfo.applicationInfo.uid, false);
1488
1489 if (!skip) {
1490 final int allowed = mService.getAppStartModeLocked(
1491 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1492 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
1493 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1494 // We won't allow this receiver to be launched if the app has been
1495 // completely disabled from launches, or it was not explicitly sent
1496 // to it and the app is in a state that should not receive it
1497 // (depending on how getAppStartModeLocked has determined that).
1498 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1499 Slog.w(TAG, "Background execution disabled: receiving "
1500 + r.intent + " to "
1501 + component.flattenToShortString());
1502 skip = true;
1503 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
1504 || (r.intent.getComponent() == null
1505 && r.intent.getPackage() == null
1506 && ((r.intent.getFlags()
1507 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1508 && !isSignaturePerm(r.requiredPermissions))) {
1509 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1510 component.getPackageName());
1511 Slog.w(TAG, "Background execution not allowed: receiving "
1512 + r.intent + " to "
Svet Ganov99b60432015-06-27 13:15:22 -07001513 + component.flattenToShortString());
1514 skip = true;
1515 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001516 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001517 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001518
Amith Yamasani4e820542018-05-09 13:37:20 -07001519 if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1520 && !mService.mUserController
1521 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1522 0 /* flags */)) {
1523 skip = true;
1524 Slog.w(TAG,
1525 "Skipping delivery to " + info.activityInfo.packageName + " / "
1526 + info.activityInfo.applicationInfo.uid + " : user is not running");
1527 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001528
Amith Yamasani4e820542018-05-09 13:37:20 -07001529 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001530 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Amith Yamasani4e820542018-05-09 13:37:20 -07001531 "Skipping delivery of ordered [" + mQueueName + "] "
1532 + r + " for whatever reason");
1533 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1534 r.receiver = null;
1535 r.curFilter = null;
1536 r.state = BroadcastRecord.IDLE;
1537 r.manifestSkipCount++;
1538 scheduleBroadcastsLocked();
1539 return;
1540 }
1541 r.manifestCount++;
1542
1543 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1544 r.state = BroadcastRecord.APP_RECEIVE;
1545 r.curComponent = component;
1546 r.curReceiver = info.activityInfo;
1547 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1548 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1549 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1550 + receiverUid);
1551 }
1552
1553 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1554 scheduleTempWhitelistLocked(receiverUid,
1555 brOptions.getTemporaryAppWhitelistDuration(), r);
1556 }
1557
1558 // Broadcast is being executed, its package can't be stopped.
1559 try {
1560 AppGlobals.getPackageManager().setPackageStoppedState(
Christopher Tatea3a455d2018-12-07 17:22:46 -08001561 r.curComponent.getPackageName(), false, r.userId);
Amith Yamasani4e820542018-05-09 13:37:20 -07001562 } catch (RemoteException e) {
1563 } catch (IllegalArgumentException e) {
1564 Slog.w(TAG, "Failed trying to unstop package "
1565 + r.curComponent.getPackageName() + ": " + e);
1566 }
1567
1568 // Is this receiver's application already running?
1569 if (app != null && app.thread != null && !app.killed) {
1570 try {
1571 app.addPackage(info.activityInfo.packageName,
1572 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001573 maybeAddAllowBackgroundActivityStartsToken(app, r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001574 processCurBroadcastLocked(r, app, skipOomAdj);
1575 return;
1576 } catch (RemoteException e) {
1577 Slog.w(TAG, "Exception when sending broadcast to "
1578 + r.curComponent, e);
1579 } catch (RuntimeException e) {
1580 Slog.wtf(TAG, "Failed sending broadcast to "
1581 + r.curComponent + " with " + r.intent, e);
1582 // If some unexpected exception happened, just skip
1583 // this broadcast. At this point we are not in the call
1584 // from a client, so throwing an exception out from here
1585 // will crash the entire system instead of just whoever
1586 // sent the broadcast.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001587 logBroadcastReceiverDiscardLocked(r);
1588 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001589 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001590 scheduleBroadcastsLocked();
Amith Yamasani4e820542018-05-09 13:37:20 -07001591 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001592 r.state = BroadcastRecord.IDLE;
1593 return;
1594 }
1595
Amith Yamasani4e820542018-05-09 13:37:20 -07001596 // If a dead object exception was thrown -- fall through to
1597 // restart the application.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001598 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001599
1600 // Not running -- get it started, to be executed when the app comes up.
1601 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1602 "Need to start app ["
1603 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1604 if ((r.curApp=mService.startProcessLocked(targetProcess,
1605 info.activityInfo.applicationInfo, true,
1606 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1607 "broadcast", r.curComponent,
1608 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1609 == null) {
1610 // Ah, this recipient is unavailable. Finish it if necessary,
1611 // and mark the broadcast record as ready for the next.
1612 Slog.w(TAG, "Unable to launch app "
1613 + info.activityInfo.applicationInfo.packageName + "/"
1614 + receiverUid + " for broadcast "
1615 + r.intent + ": process is bad");
1616 logBroadcastReceiverDiscardLocked(r);
1617 finishReceiverLocked(r, r.resultCode, r.resultData,
1618 r.resultExtras, r.resultAbort, false);
1619 scheduleBroadcastsLocked();
1620 r.state = BroadcastRecord.IDLE;
1621 return;
1622 }
1623
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001624 maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001625 mPendingBroadcast = r;
1626 mPendingBroadcastRecvIndex = recIdx;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001627 }
1628
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001629 private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
1630 if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
1631 return;
1632 }
1633 String msgToken = (proc.toShortString() + r.toString()).intern();
1634 // first, if there exists a past scheduled request to remove this token, drop
1635 // that request - we don't want the token to be swept from under our feet...
1636 mHandler.removeCallbacksAndMessages(msgToken);
1637 // ...then add the token
1638 proc.addAllowBackgroundActivityStartsToken(r);
1639 }
1640
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001641 final void setBroadcastTimeoutLocked(long timeoutTime) {
1642 if (! mPendingBroadcastTimeoutMessage) {
1643 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1644 mHandler.sendMessageAtTime(msg, timeoutTime);
1645 mPendingBroadcastTimeoutMessage = true;
1646 }
1647 }
1648
1649 final void cancelBroadcastTimeoutLocked() {
1650 if (mPendingBroadcastTimeoutMessage) {
1651 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1652 mPendingBroadcastTimeoutMessage = false;
1653 }
1654 }
1655
1656 final void broadcastTimeoutLocked(boolean fromMsg) {
1657 if (fromMsg) {
1658 mPendingBroadcastTimeoutMessage = false;
1659 }
1660
Christopher Tate2f558d22019-01-17 16:58:31 -08001661 if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001662 return;
1663 }
1664
1665 long now = SystemClock.uptimeMillis();
Christopher Tate2f558d22019-01-17 16:58:31 -08001666 BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001667 if (fromMsg) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001668 if (!mService.mProcessesReady) {
Christopher Tate1b72ca32019-01-30 16:25:53 -08001669 // Only process broadcast timeouts if the system is ready; some early
1670 // broadcasts do heavy work setting up system facilities
1671 return;
1672 }
1673
1674 // If the broadcast is generally exempt from timeout tracking, we're done
1675 if (r.timeoutExempt) {
1676 if (DEBUG_BROADCAST) {
1677 Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1678 + r.intent.getAction());
1679 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001680 return;
1681 }
1682
Christopher Tate2f558d22019-01-17 16:58:31 -08001683 long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001684 if (timeoutTime > now) {
1685 // We can observe premature timeouts because we do not cancel and reset the
1686 // broadcast timeout message after each receiver finishes. Instead, we set up
1687 // an initial timeout then kick it down the road a little further as needed
1688 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001689 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001690 "Premature timeout ["
1691 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1692 + timeoutTime);
1693 setBroadcastTimeoutLocked(timeoutTime);
1694 return;
1695 }
1696 }
1697
Christopher Tate2f558d22019-01-17 16:58:31 -08001698 if (r.state == BroadcastRecord.WAITING_SERVICES) {
Dianne Hackborn6285a322013-09-18 12:09:47 -07001699 // In this case the broadcast had already finished, but we had decided to wait
1700 // for started services to finish as well before going on. So if we have actually
1701 // waited long enough time timeout the broadcast, let's give up on the whole thing
1702 // and just move on to the next.
Christopher Tate2f558d22019-01-17 16:58:31 -08001703 Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1704 ? r.curComponent.flattenToShortString() : "(null)"));
1705 r.curComponent = null;
1706 r.state = BroadcastRecord.IDLE;
Dianne Hackborn6285a322013-09-18 12:09:47 -07001707 processNextBroadcast(false);
1708 return;
1709 }
1710
Christopher Tatef2370162018-03-16 16:26:23 -07001711 // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1712 // tidying up and moving on to the next broadcast without crashing or ANRing this
1713 // app just because it's stopped at a breakpoint.
Wale Ogunwale906f9c62018-07-23 11:23:44 -07001714 final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
Christopher Tatef2370162018-03-16 16:26:23 -07001715
1716 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001717 + ", started " + (now - r.receiverTime) + "ms ago");
1718 r.receiverTime = now;
Christopher Tatef2370162018-03-16 16:26:23 -07001719 if (!debugging) {
1720 r.anrCount++;
1721 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001722
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001723 ProcessRecord app = null;
1724 String anrMessage = null;
1725
Christopher Tatea6b2c882017-09-01 11:41:39 -07001726 Object curReceiver;
1727 if (r.nextReceiver > 0) {
1728 curReceiver = r.receivers.get(r.nextReceiver-1);
1729 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1730 } else {
1731 curReceiver = r.curReceiver;
1732 }
1733 Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001734 logBroadcastReceiverDiscardLocked(r);
Christopher Tatea6b2c882017-09-01 11:41:39 -07001735 if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001736 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1737 if (bf.receiverList.pid != 0
1738 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1739 synchronized (mService.mPidsSelfLocked) {
1740 app = mService.mPidsSelfLocked.get(
1741 bf.receiverList.pid);
1742 }
1743 }
1744 } else {
1745 app = r.curApp;
1746 }
1747
1748 if (app != null) {
1749 anrMessage = "Broadcast of " + r.intent.toString();
1750 }
1751
1752 if (mPendingBroadcast == r) {
1753 mPendingBroadcast = null;
1754 }
1755
1756 // Move on to the next receiver.
1757 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001758 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001759 scheduleBroadcastsLocked();
1760
Christopher Tatef2370162018-03-16 16:26:23 -07001761 if (!debugging && anrMessage != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001762 // Post the ANR to the handler since we do not want to process ANRs while
1763 // potentially holding our lock.
1764 mHandler.post(new AppNotResponding(app, anrMessage));
1765 }
1766 }
1767
Christopher Tatef278f122015-04-22 13:12:01 -07001768 private final int ringAdvance(int x, final int increment, final int ringSize) {
1769 x += increment;
1770 if (x < 0) return (ringSize - 1);
1771 else if (x >= ringSize) return 0;
1772 else return x;
1773 }
1774
Makoto Onuki97f82f22017-05-31 16:20:21 -07001775 private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1776 if (original.callingUid < 0) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001777 // This was from a registerReceiver() call; ignore it.
1778 return;
1779 }
Makoto Onuki97f82f22017-05-31 16:20:21 -07001780 original.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001781
Carmen Jacksona68e3452017-01-17 14:01:33 -08001782 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1783 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Makoto Onuki97f82f22017-05-31 16:20:21 -07001784 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1785 System.identityHashCode(original));
Carmen Jacksona68e3452017-01-17 14:01:33 -08001786 }
1787
Makoto Onuki97f82f22017-05-31 16:20:21 -07001788 // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1789 // So don't change the incoming record directly.
1790 final BroadcastRecord historyRecord = original.maybeStripForHistory();
1791
1792 mBroadcastHistory[mHistoryNext] = historyRecord;
Christopher Tatef278f122015-04-22 13:12:01 -07001793 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1794
Makoto Onuki97f82f22017-05-31 16:20:21 -07001795 mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1796 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1797 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
Christopher Tatef278f122015-04-22 13:12:01 -07001798 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1799 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001800 }
1801
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001802 boolean cleanupDisabledPackageReceiversLocked(
1803 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1804 boolean didSomething = false;
1805 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1806 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1807 packageName, filterByClasses, userId, doit);
1808 if (!doit && didSomething) {
1809 return true;
1810 }
1811 }
1812
Christopher Tate2f558d22019-01-17 16:58:31 -08001813 didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1814 filterByClasses, userId, doit);
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001815
1816 return didSomething;
1817 }
1818
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001819 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001820 final int logIndex = r.nextReceiver - 1;
1821 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1822 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001823 if (curReceiver instanceof BroadcastFilter) {
1824 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1825 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001826 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001827 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001828 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001829 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001830 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001831 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001832 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001833 }
1834 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001835 if (logIndex < 0) Slog.w(TAG,
1836 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001837 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001838 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001839 r.intent.getAction(),
1840 r.nextReceiver,
1841 "NONE");
1842 }
1843 }
1844
Carmen Jacksona68e3452017-01-17 14:01:33 -08001845 private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1846 return String.format("Broadcast %s from %s (%s) %s",
1847 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1848 record.callerPackage == null ? "" : record.callerPackage,
1849 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1850 record.intent == null ? "" : record.intent.getAction());
1851 }
1852
Christopher Tateb486f412019-02-12 18:05:17 -08001853 boolean isIdle() {
Christopher Tate2f558d22019-01-17 16:58:31 -08001854 return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
Jeff Sharkeyfd658132017-05-03 11:38:01 -06001855 && (mPendingBroadcast == null);
1856 }
1857
Christopher Tateb486f412019-02-12 18:05:17 -08001858 // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1859 // be immediately deliverable.
1860 void cancelDeferrals() {
1861 mDispatcher.cancelDeferrals();
1862 }
1863
1864 String describeState() {
1865 synchronized (mService) {
1866 return mParallelBroadcasts.size() + " parallel; "
1867 + mDispatcher.describeStateLocked();
1868 }
1869 }
1870
Yi Jin129fc6c2017-09-28 15:48:38 -07001871 void writeToProto(ProtoOutputStream proto, long fieldId) {
1872 long token = proto.start(fieldId);
1873 proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1874 int N;
1875 N = mParallelBroadcasts.size();
1876 for (int i = N - 1; i >= 0; i--) {
1877 mParallelBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1878 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001879 mDispatcher.writeToProto(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
Yi Jin129fc6c2017-09-28 15:48:38 -07001880 if (mPendingBroadcast != null) {
1881 mPendingBroadcast.writeToProto(proto, BroadcastQueueProto.PENDING_BROADCAST);
1882 }
1883
1884 int lastIndex = mHistoryNext;
1885 int ringIndex = lastIndex;
1886 do {
1887 // increasing index = more recent entry, and we want to print the most
1888 // recent first and work backwards, so we roll through the ring backwards.
1889 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1890 BroadcastRecord r = mBroadcastHistory[ringIndex];
1891 if (r != null) {
1892 r.writeToProto(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1893 }
1894 } while (ringIndex != lastIndex);
1895
1896 lastIndex = ringIndex = mSummaryHistoryNext;
1897 do {
1898 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1899 Intent intent = mBroadcastSummaryHistory[ringIndex];
1900 if (intent == null) {
1901 continue;
1902 }
1903 long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1904 intent.writeToProto(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1905 false, true, true, false);
1906 proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1907 mSummaryHistoryEnqueueTime[ringIndex]);
1908 proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1909 mSummaryHistoryDispatchTime[ringIndex]);
1910 proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1911 mSummaryHistoryFinishTime[ringIndex]);
1912 proto.end(summaryToken);
1913 } while (ringIndex != lastIndex);
1914 proto.end(token);
1915 }
1916
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001917 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1918 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Ng Zhi Ana7f50d42018-09-18 10:51:34 -07001919 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tate2f558d22019-01-17 16:58:31 -08001920 if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001921 || mPendingBroadcast != null) {
1922 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001923 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001924 BroadcastRecord br = mParallelBroadcasts.get(i);
1925 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1926 continue;
1927 }
1928 if (!printed) {
1929 if (needSep) {
1930 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001931 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001932 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001933 printed = true;
1934 pw.println(" Active broadcasts [" + mQueueName + "]:");
1935 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001936 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001937 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001938 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001939
1940 mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1941
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001942 if (dumpPackage == null || (mPendingBroadcast != null
1943 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001944 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001945 pw.println(" Pending broadcast [" + mQueueName + "]:");
1946 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001947 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001948 } else {
1949 pw.println(" (null)");
1950 }
1951 needSep = true;
1952 }
1953 }
1954
Christopher Tate2f558d22019-01-17 16:58:31 -08001955 mConstants.dump(pw);
1956
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001957 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001958 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001959
1960 i = -1;
1961 int lastIndex = mHistoryNext;
1962 int ringIndex = lastIndex;
1963 do {
1964 // increasing index = more recent entry, and we want to print the most
1965 // recent first and work backwards, so we roll through the ring backwards.
1966 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1967 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001968 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001969 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001970 }
Christopher Tatef278f122015-04-22 13:12:01 -07001971
1972 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001973 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1974 continue;
1975 }
1976 if (!printed) {
1977 if (needSep) {
1978 pw.println();
1979 }
1980 needSep = true;
1981 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1982 printed = true;
1983 }
1984 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001985 pw.print(" Historical Broadcast " + mQueueName + " #");
1986 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001987 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001988 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001989 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1990 pw.print(" ");
1991 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001992 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1993 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1994 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001995 Bundle bundle = r.intent.getExtras();
1996 if (bundle != null) {
1997 pw.print(" extras: "); pw.println(bundle.toString());
1998 }
1999 }
Christopher Tatef278f122015-04-22 13:12:01 -07002000 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002001
2002 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07002003 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002004 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002005 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07002006 i = -1;
2007 } else {
2008 // roll over the 'i' full dumps that have already been issued
2009 for (int j = i;
2010 j > 0 && ringIndex != lastIndex;) {
2011 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2012 BroadcastRecord r = mBroadcastHistory[ringIndex];
2013 if (r == null) {
2014 continue;
2015 }
2016 j--;
2017 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002018 }
Christopher Tatef278f122015-04-22 13:12:01 -07002019 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
2020 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07002021 do {
2022 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2023 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002024 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07002025 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002026 }
2027 if (!printed) {
2028 if (needSep) {
2029 pw.println();
2030 }
2031 needSep = true;
2032 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
2033 printed = true;
2034 }
2035 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002036 pw.println(" ...");
2037 break;
2038 }
Christopher Tatef278f122015-04-22 13:12:01 -07002039 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002040 pw.print(" #"); pw.print(i); pw.print(": ");
2041 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07002042 pw.print(" ");
2043 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
2044 - mSummaryHistoryEnqueueTime[ringIndex], pw);
2045 pw.print(" dispatch ");
2046 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
2047 - mSummaryHistoryDispatchTime[ringIndex], pw);
2048 pw.println(" finish");
2049 pw.print(" enq=");
2050 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
2051 pw.print(" disp=");
2052 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
2053 pw.print(" fin=");
2054 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002055 Bundle bundle = intent.getExtras();
2056 if (bundle != null) {
2057 pw.print(" extras: "); pw.println(bundle.toString());
2058 }
Christopher Tatef278f122015-04-22 13:12:01 -07002059 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002060 }
2061
2062 return needSep;
2063 }
2064}