blob: 746c250308de5afa7d906ef8f49c11a60c587a04 [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) {
Amith Yamasanid2775cd2019-04-12 15:47:54 -0700312 mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
Amith Yamasani4e820542018-05-09 13:37:20 -0700313 }
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
Christopher Tate6ac39802019-05-01 16:46:46 -0700440 private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
441 // the receiver had run for less than allowed bg activity start timeout,
442 // so allow the process to still start activities from bg for some more time
443 String msgToken = (app.toShortString() + r.toString()).intern();
444 // first, if there exists a past scheduled request to remove this token, drop
445 // that request - we don't want the token to be swept from under our feet...
446 mHandler.removeCallbacksAndMessages(msgToken);
447 // ...then schedule the removal of the token after the extended timeout
448 mHandler.postAtTime(() -> {
449 app.removeAllowBackgroundActivityStartsToken(r);
450 }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
451 }
452
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800453 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700454 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
455 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700456 final ActivityInfo receiver = r.curReceiver;
Ng Zhi An1eb7d382018-08-24 13:27:54 -0700457 final long finishTime = SystemClock.uptimeMillis();
Christopher Tate2f558d22019-01-17 16:58:31 -0800458 final long elapsed = finishTime - r.receiverTime;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800459 r.state = BroadcastRecord.IDLE;
460 if (state == BroadcastRecord.IDLE) {
Christopher Tate41c56912019-03-01 18:56:58 -0800461 Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800462 }
Christopher Tate200029a2019-01-29 16:37:44 -0800463 if (r.allowBackgroundActivityStarts && r.curApp != null) {
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000464 if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
465 // if the receiver has run for more than allowed bg activity start timeout,
466 // just remove the token for this process now and we're done
467 r.curApp.removeAllowBackgroundActivityStartsToken(r);
468 } else {
Christopher Tate6ac39802019-05-01 16:46:46 -0700469 // It gets more time; post the removal to happen at the appropriate moment
470 postActivityStartTokenRemoval(r.curApp, r);
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000471 }
472 }
Christopher Tatec7aa3292018-08-31 19:13:03 -0700473 // If we're abandoning this broadcast before any receivers were actually spun up,
474 // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
475 if (r.nextReceiver > 0) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800476 r.duration[r.nextReceiver - 1] = elapsed;
Christopher Tatec7aa3292018-08-31 19:13:03 -0700477 }
Christopher Tate2f558d22019-01-17 16:58:31 -0800478
479 // if this receiver was slow, impose deferral policy on the app. This will kick in
480 // when processNextBroadcastLocked() next finds this uid as a receiver identity.
Christopher Tate1b72ca32019-01-30 16:25:53 -0800481 if (!r.timeoutExempt) {
482 if (mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
Christopher Tateaf807112019-03-08 16:23:06 -0800483 // Core system packages are exempt from deferral policy
484 if (!UserHandle.isCore(r.curApp.uid)) {
485 if (DEBUG_BROADCAST_DEFERRAL) {
486 Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
487 + " was slow: " + receiver + " br=" + r);
488 }
489 if (r.curApp != null) {
490 mDispatcher.startDeferring(r.curApp.uid);
491 } else {
492 Slog.d(TAG_BROADCAST, "finish receiver curApp is null? " + r);
493 }
Christopher Tate1b72ca32019-01-30 16:25:53 -0800494 } else {
Christopher Tateaf807112019-03-08 16:23:06 -0800495 if (DEBUG_BROADCAST_DEFERRAL) {
496 Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
497 + " receiver was slow but not deferring: " + receiver + " br=" + r);
498 }
Christopher Tate1b72ca32019-01-30 16:25:53 -0800499 }
Christopher Tate2f558d22019-01-17 16:58:31 -0800500 }
Christopher Tate1b72ca32019-01-30 16:25:53 -0800501 } else {
502 if (DEBUG_BROADCAST_DEFERRAL) {
503 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
504 + " is exempt from deferral policy");
Christopher Tate2f558d22019-01-17 16:58:31 -0800505 }
506 }
507
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800508 r.receiver = null;
509 r.intent.setComponent(null);
yangzhenyud509bc92016-08-31 18:26:46 +0800510 if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
511 r.curApp.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800512 }
513 if (r.curFilter != null) {
514 r.curFilter.receiverList.curBroadcast = null;
515 }
516 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800517 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700518 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800519 mPendingBroadcast = null;
520
521 r.resultCode = resultCode;
522 r.resultData = resultData;
523 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700524 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
525 r.resultAbort = resultAbort;
526 } else {
527 r.resultAbort = false;
528 }
529
Christopher Tate2f558d22019-01-17 16:58:31 -0800530 // If we want to wait behind services *AND* we're finishing the head/
531 // active broadcast on its queue
Dianne Hackborn6285a322013-09-18 12:09:47 -0700532 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
Christopher Tate2f558d22019-01-17 16:58:31 -0800533 && r.queue.mDispatcher.getActiveBroadcastLocked() == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700534 ActivityInfo nextReceiver;
535 if (r.nextReceiver < r.receivers.size()) {
536 Object obj = r.receivers.get(r.nextReceiver);
537 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
538 } else {
539 nextReceiver = null;
540 }
541 // Don't do this if the next receive is in the same process as the current one.
542 if (receiver == null || nextReceiver == null
543 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
544 || !receiver.processName.equals(nextReceiver.processName)) {
545 // In this case, we are ready to process the next receiver for the current broadcast,
546 // but are on a queue that would like to wait for services to finish before moving
547 // on. If there are background services currently starting, then we will go into a
548 // special state where we hold off on continuing this broadcast until they are done.
Dianne Hackbornad51be92016-08-16 16:27:36 -0700549 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800550 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700551 r.state = BroadcastRecord.WAITING_SERVICES;
552 return false;
553 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700554 }
555 }
556
557 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800558
559 // We will process the next receiver right now if this is finishing
560 // an app receiver (which is always asynchronous) or after we have
561 // come back from calling a receiver.
562 return state == BroadcastRecord.APP_RECEIVE
563 || state == BroadcastRecord.CALL_DONE_RECEIVE;
564 }
565
Dianne Hackborn6285a322013-09-18 12:09:47 -0700566 public void backgroundServicesFinishedLocked(int userId) {
Christopher Tate2f558d22019-01-17 16:58:31 -0800567 BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
568 if (br != null) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700569 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800570 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700571 br.curComponent = null;
572 br.state = BroadcastRecord.IDLE;
573 processNextBroadcast(false);
574 }
575 }
576 }
577
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700578 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800579 Intent intent, int resultCode, String data, Bundle extras,
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000580 boolean ordered, boolean sticky, int sendingUser)
Michal Karpinski9cbb20b2019-02-05 17:31:50 +0000581 throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800582 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000583 if (app != null) {
584 if (app.thread != null) {
585 // If we have an app thread, do the call through that so it is
586 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700587 try {
588 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700589 data, extras, ordered, sticky, sendingUser, app.getReportedProcState());
Joe Onorato5869d1c2016-04-20 15:38:07 -0700590 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
591 // DeadObjectException when the process isn't actually dead.
592 //} catch (DeadObjectException ex) {
593 // Failed to call into the process. It's dying so just let it die and move on.
594 // throw ex;
595 } catch (RemoteException ex) {
596 // Failed to call into the process. It's either dying or wedged. Kill it gently.
597 synchronized (mService) {
598 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
599 + " (pid " + app.pid + "). Crashing it.");
600 app.scheduleCrash("can't deliver broadcast");
601 }
602 throw ex;
603 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000604 } else {
605 // Application has died. Receiver doesn't exist.
606 throw new RemoteException("app.thread must not be null");
607 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800608 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700609 receiver.performReceive(intent, resultCode, data, extras, ordered,
610 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800611 }
612 }
613
Svet Ganov99b60432015-06-27 13:15:22 -0700614 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800615 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800616 boolean skip = false;
Dianne Hackborn769b2e72018-12-05 08:51:20 -0800617 if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
618 filter.packageName, filter.owningUid)) {
619 Slog.w(TAG, "Association not allowed: broadcasting "
620 + r.intent.toString()
621 + " from " + r.callerPackage + " (pid=" + r.callingPid
622 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
623 + filter);
624 skip = true;
625 }
626 if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
627 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
628 Slog.w(TAG, "Firewall blocked: broadcasting "
629 + r.intent.toString()
630 + " from " + r.callerPackage + " (pid=" + r.callingPid
631 + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
632 + filter);
633 skip = true;
634 }
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700635 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800636 int perm = mService.checkComponentPermission(filter.requiredPermission,
637 r.callingPid, r.callingUid, -1, true);
638 if (perm != PackageManager.PERMISSION_GRANTED) {
639 Slog.w(TAG, "Permission Denial: broadcasting "
640 + r.intent.toString()
641 + " from " + r.callerPackage + " (pid="
642 + r.callingPid + ", uid=" + r.callingUid + ")"
643 + " requires " + filter.requiredPermission
644 + " due to registered receiver " + filter);
645 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700646 } else {
647 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
648 if (opCode != AppOpsManager.OP_NONE
649 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
650 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
651 Slog.w(TAG, "Appop Denial: broadcasting "
652 + r.intent.toString()
653 + " from " + r.callerPackage + " (pid="
654 + r.callingPid + ", uid=" + r.callingUid + ")"
655 + " requires appop " + AppOpsManager.permissionToOp(
656 filter.requiredPermission)
657 + " due to registered receiver " + filter);
658 skip = true;
659 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800660 }
661 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700662 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
663 for (int i = 0; i < r.requiredPermissions.length; i++) {
664 String requiredPermission = r.requiredPermissions[i];
665 int perm = mService.checkComponentPermission(requiredPermission,
666 filter.receiverList.pid, filter.receiverList.uid, -1, true);
667 if (perm != PackageManager.PERMISSION_GRANTED) {
668 Slog.w(TAG, "Permission Denial: receiving "
669 + r.intent.toString()
670 + " to " + filter.receiverList.app
671 + " (pid=" + filter.receiverList.pid
672 + ", uid=" + filter.receiverList.uid + ")"
673 + " requires " + requiredPermission
674 + " due to sender " + r.callerPackage
675 + " (uid " + r.callingUid + ")");
676 skip = true;
677 break;
678 }
679 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700680 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700681 && mService.mAppOpsService.noteOperation(appOp,
682 filter.receiverList.uid, filter.packageName)
683 != AppOpsManager.MODE_ALLOWED) {
684 Slog.w(TAG, "Appop Denial: receiving "
685 + r.intent.toString()
686 + " to " + filter.receiverList.app
687 + " (pid=" + filter.receiverList.pid
688 + ", uid=" + filter.receiverList.uid + ")"
689 + " requires appop " + AppOpsManager.permissionToOp(
690 requiredPermission)
691 + " due to sender " + r.callerPackage
692 + " (uid " + r.callingUid + ")");
693 skip = true;
694 break;
695 }
696 }
697 }
698 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
699 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000700 filter.receiverList.pid, filter.receiverList.uid, -1, true);
701 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700702 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000703 + r.intent.toString()
704 + " to " + filter.receiverList.app
705 + " (pid=" + filter.receiverList.pid
706 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000707 + " due to sender " + r.callerPackage
708 + " (uid " + r.callingUid + ")");
709 skip = true;
710 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700711 }
712 if (!skip && r.appOp != AppOpsManager.OP_NONE
713 && mService.mAppOpsService.noteOperation(r.appOp,
714 filter.receiverList.uid, filter.packageName)
715 != AppOpsManager.MODE_ALLOWED) {
716 Slog.w(TAG, "Appop Denial: receiving "
717 + r.intent.toString()
718 + " to " + filter.receiverList.app
719 + " (pid=" + filter.receiverList.pid
720 + ", uid=" + filter.receiverList.uid + ")"
721 + " requires appop " + AppOpsManager.opToName(r.appOp)
722 + " due to sender " + r.callerPackage
723 + " (uid " + r.callingUid + ")");
724 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700725 }
Svet Ganov99b60432015-06-27 13:15:22 -0700726
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700727 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.killed
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700728 || filter.receiverList.app.isCrashing())) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700729 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700730 + " to " + filter.receiverList + ": process gone or crashing");
Dianne Hackborn9357b112013-10-03 18:27:48 -0700731 skip = true;
732 }
733
Chad Brubakerb7e34d52017-02-22 12:36:06 -0800734 // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
735 // visible to Instant Apps.
736 final boolean visibleToInstantApps =
737 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
738
739 if (!skip && !visibleToInstantApps && filter.instantApp
740 && filter.receiverList.uid != r.callingUid) {
741 Slog.w(TAG, "Instant App Denial: receiving "
742 + r.intent.toString()
743 + " to " + filter.receiverList.app
744 + " (pid=" + filter.receiverList.pid
745 + ", uid=" + filter.receiverList.uid + ")"
746 + " due to sender " + r.callerPackage
747 + " (uid " + r.callingUid + ")"
748 + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
749 skip = true;
750 }
751
Chad Brubaker816c83b2017-03-02 10:27:59 -0800752 if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
753 && filter.receiverList.uid != r.callingUid) {
754 Slog.w(TAG, "Instant App Denial: receiving "
755 + r.intent.toString()
756 + " to " + filter.receiverList.app
757 + " (pid=" + filter.receiverList.pid
758 + ", uid=" + filter.receiverList.uid + ")"
759 + " requires receiver be visible to instant apps"
760 + " due to sender " + r.callerPackage
761 + " (uid " + r.callingUid + ")");
762 skip = true;
763 }
764
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800765 if (skip) {
766 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
767 return;
768 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800769
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800770 // If permissions need a review before any of the app components can run, we drop
771 // the broadcast and if the calling app is in the foreground and the broadcast is
772 // explicit we launch the review UI passing it a pending intent to send the skipped
773 // broadcast.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700774 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
775 filter.owningUserId)) {
776 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
777 return;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800778 }
779
780 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
781
782 // If this is not being sent as an ordered broadcast, then we
783 // don't want to touch the fields that keep track of the current
784 // state of ordered broadcasts.
785 if (ordered) {
786 r.receiver = filter.receiverList.receiver.asBinder();
787 r.curFilter = filter;
788 filter.receiverList.curBroadcast = r;
789 r.state = BroadcastRecord.CALL_IN_RECEIVE;
790 if (filter.receiverList.app != null) {
791 // Bump hosting application to no longer be in background
792 // scheduling class. Note that we can't do that if there
793 // isn't an app... but we can only be in that case for
794 // things that directly call the IActivityManager API, which
795 // are already core system stuff so don't matter for this.
796 r.curApp = filter.receiverList.app;
yangzhenyud509bc92016-08-31 18:26:46 +0800797 filter.receiverList.app.curReceivers.add(r);
Amith Yamasanid2775cd2019-04-12 15:47:54 -0700798 mService.updateOomAdjLocked(r.curApp, true,
799 OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800800 }
801 }
802 try {
803 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
804 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700805 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
806 // Skip delivery if full backup in progress
807 // If it's an ordered broadcast, we need to continue to the next receiver.
808 if (ordered) {
809 skipReceiverLocked(r);
810 }
811 } else {
Christopher Tate41c56912019-03-01 18:56:58 -0800812 r.receiverTime = SystemClock.uptimeMillis();
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000813 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700814 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
815 new Intent(r.intent), r.resultCode, r.resultData,
Michal Karpinski4b8aef22019-02-21 14:56:51 +0000816 r.resultExtras, r.ordered, r.initialSticky, r.userId);
Christopher Tate6ac39802019-05-01 16:46:46 -0700817 // parallel broadcasts are fire-and-forget, not bookended by a call to
818 // finishReceiverLocked(), so we manage their activity-start token here
819 if (r.allowBackgroundActivityStarts && !r.ordered) {
820 postActivityStartTokenRemoval(filter.receiverList.app, r);
821 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700822 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800823 if (ordered) {
824 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
825 }
826 } catch (RemoteException e) {
827 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
Christopher Tate6ac39802019-05-01 16:46:46 -0700828 // Clean up ProcessRecord state related to this broadcast attempt
829 if (filter.receiverList.app != null) {
830 filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
831 if (ordered) {
832 filter.receiverList.app.curReceivers.remove(r);
833 }
834 }
835 // And BroadcastRecord state related to ordered delivery, if appropriate
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800836 if (ordered) {
837 r.receiver = null;
838 r.curFilter = null;
839 filter.receiverList.curBroadcast = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800840 }
841 }
842 }
843
Svet Ganov9c165d72015-12-01 19:52:26 -0800844 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
845 BroadcastRecord receiverRecord, String receivingPackageName,
846 final int receivingUserId) {
847 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
848 receivingPackageName, receivingUserId)) {
849 return true;
850 }
851
852 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800853 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800854 : true;
855
856 // Show a permission review UI only for explicit broadcast from a foreground app
857 if (callerForeground && receiverRecord.intent.getComponent() != null) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700858 IIntentSender target = mService.mPendingIntentController.getIntentSender(
Svet Ganov9c165d72015-12-01 19:52:26 -0800859 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
860 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
861 new Intent[]{receiverRecord.intent},
862 new String[]{receiverRecord.intent.resolveType(mService.mContext
863 .getContentResolver())},
864 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
865 | PendingIntent.FLAG_IMMUTABLE, null);
866
867 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
868 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
Philip P. Moltmann751e46ca2019-01-24 13:56:47 -0800869 | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
Svet Ganov9c165d72015-12-01 19:52:26 -0800870 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
871 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
872 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
873
874 if (DEBUG_PERMISSIONS_REVIEW) {
875 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
876 + receivingPackageName);
877 }
878
879 mHandler.post(new Runnable() {
880 @Override
881 public void run() {
882 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
883 }
884 });
885 } else {
886 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
887 + receivingPackageName + " requires a permissions review");
888 }
889
890 return false;
891 }
892
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700893 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700894 if (duration > Integer.MAX_VALUE) {
895 duration = Integer.MAX_VALUE;
896 }
897 // XXX ideally we should pause the broadcast until everything behind this is done,
898 // or else we will likely start dispatching the broadcast before we have opened
899 // access to the app (there is a lot of asynchronicity behind this). It is probably
900 // not that big a deal, however, because the main purpose here is to allow apps
901 // to hold wake locks, and they will be able to acquire their wake lock immediately
902 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700903 StringBuilder b = new StringBuilder();
904 b.append("broadcast:");
905 UserHandle.formatUid(b, r.callingUid);
906 b.append(":");
907 if (r.intent.getAction() != null) {
908 b.append(r.intent.getAction());
909 } else if (r.intent.getComponent() != null) {
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700910 r.intent.getComponent().appendShortString(b);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700911 } else if (r.intent.getData() != null) {
912 b.append(r.intent.getData());
913 }
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700914 mService.tempWhitelistUidLocked(uid, duration, b.toString());
Dianne Hackborna750a632015-06-16 17:18:23 -0700915 }
916
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700917 /**
918 * Return true if all given permissions are signature-only perms.
919 */
920 final boolean isSignaturePerm(String[] perms) {
921 if (perms == null) {
922 return false;
923 }
924 IPackageManager pm = AppGlobals.getPackageManager();
925 for (int i = perms.length-1; i >= 0; i--) {
926 try {
Svetoslav Ganovadb8c522017-07-28 05:46:53 +0000927 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
Christopher Tatecfa39d12019-02-08 18:20:07 -0800928 if (pi == null) {
929 // a required permission that no package has actually
930 // defined cannot be signature-required.
931 return false;
932 }
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700933 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
934 | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
935 != PermissionInfo.PROTECTION_SIGNATURE) {
936 // If this a signature permission and NOT allowed for privileged apps, it
937 // is okay... otherwise, nope!
938 return false;
939 }
940 } catch (RemoteException e) {
941 return false;
942 }
943 }
944 return true;
945 }
946
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800947 final void processNextBroadcast(boolean fromMsg) {
Amith Yamasani4e820542018-05-09 13:37:20 -0700948 synchronized (mService) {
949 processNextBroadcastLocked(fromMsg, false);
950 }
951 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800952
Amith Yamasani4e820542018-05-09 13:37:20 -0700953 final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
954 BroadcastRecord r;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800955
Amith Yamasani4e820542018-05-09 13:37:20 -0700956 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
957 + mQueueName + "]: "
Christopher Tateb486f412019-02-12 18:05:17 -0800958 + mParallelBroadcasts.size() + " parallel broadcasts; "
959 + mDispatcher.describeStateLocked());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800960
Amith Yamasani4e820542018-05-09 13:37:20 -0700961 mService.updateCpuStats();
962
963 if (fromMsg) {
964 mBroadcastsScheduled = false;
965 }
966
967 // First, deliver any non-serialized broadcasts right away.
968 while (mParallelBroadcasts.size() > 0) {
969 r = mParallelBroadcasts.remove(0);
970 r.dispatchTime = SystemClock.uptimeMillis();
971 r.dispatchClockTime = System.currentTimeMillis();
972
973 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
974 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
975 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
976 System.identityHashCode(r));
977 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
978 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
979 System.identityHashCode(r));
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800980 }
981
Amith Yamasani4e820542018-05-09 13:37:20 -0700982 final int N = r.receivers.size();
983 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
984 + mQueueName + "] " + r);
985 for (int i=0; i<N; i++) {
986 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800987 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Amith Yamasani4e820542018-05-09 13:37:20 -0700988 "Delivering non-ordered on [" + mQueueName + "] to registered "
989 + target + ": " + r);
990 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
991 }
992 addBroadcastToHistoryLocked(r);
993 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
994 + mQueueName + "] " + r);
995 }
996
997 // Now take care of the next serialized one...
998
999 // If we are waiting for a process to come up to handle the next
1000 // broadcast, then do nothing at this point. Just in case, we
1001 // check that the process we're waiting for still exists.
1002 if (mPendingBroadcast != null) {
1003 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1004 "processNextBroadcast [" + mQueueName + "]: waiting for "
1005 + mPendingBroadcast.curApp);
1006
1007 boolean isDead;
1008 if (mPendingBroadcast.curApp.pid > 0) {
1009 synchronized (mService.mPidsSelfLocked) {
1010 ProcessRecord proc = mService.mPidsSelfLocked.get(
1011 mPendingBroadcast.curApp.pid);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001012 isDead = proc == null || proc.isCrashing();
Amith Yamasani4e820542018-05-09 13:37:20 -07001013 }
1014 } else {
Amith Yamasani98a00922018-08-21 12:50:30 -04001015 final ProcessRecord proc = mService.mProcessList.mProcessNames.get(
Amith Yamasani4e820542018-05-09 13:37:20 -07001016 mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
1017 isDead = proc == null || !proc.pendingStart;
1018 }
1019 if (!isDead) {
1020 // It's still alive, so keep waiting
1021 return;
1022 } else {
1023 Slog.w(TAG, "pending app ["
1024 + mQueueName + "]" + mPendingBroadcast.curApp
1025 + " died before responding to broadcast");
1026 mPendingBroadcast.state = BroadcastRecord.IDLE;
1027 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1028 mPendingBroadcast = null;
1029 }
1030 }
1031
1032 boolean looped = false;
1033
1034 do {
Christopher Tate2f558d22019-01-17 16:58:31 -08001035 final long now = SystemClock.uptimeMillis();
1036 r = mDispatcher.getNextBroadcastLocked(now);
1037
1038 if (r == null) {
1039 // No more broadcasts are deliverable right now, so all done!
1040 mDispatcher.scheduleDeferralCheckLocked(false);
Amith Yamasani4e820542018-05-09 13:37:20 -07001041 mService.scheduleAppGcsLocked();
1042 if (looped) {
1043 // If we had finished the last ordered broadcast, then
1044 // make sure all processes have correct oom and sched
1045 // adjustments.
Amith Yamasanid2775cd2019-04-12 15:47:54 -07001046 mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001047 }
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -08001048
1049 // when we have no more ordered broadcast on this queue, stop logging
1050 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1051 mLogLatencyMetrics = false;
1052 }
1053
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001054 return;
1055 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001056
Amith Yamasani4e820542018-05-09 13:37:20 -07001057 boolean forceReceive = false;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001058
Amith Yamasani4e820542018-05-09 13:37:20 -07001059 // Ensure that even if something goes awry with the timeout
1060 // detection, we catch "hung" broadcasts here, discard them,
1061 // and continue to make progress.
1062 //
Christopher Tate1b72ca32019-01-30 16:25:53 -08001063 // This is only done if the system is ready so that early-stage receivers
1064 // don't get executed with timeouts; and of course other timeout-
1065 // exempt broadcasts are ignored.
Amith Yamasani4e820542018-05-09 13:37:20 -07001066 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
Christopher Tate1b72ca32019-01-30 16:25:53 -08001067 if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001068 if ((numReceivers > 0) &&
Christopher Tate2f558d22019-01-17 16:58:31 -08001069 (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001070 Slog.w(TAG, "Hung broadcast ["
1071 + mQueueName + "] discarded after timeout failure:"
1072 + " now=" + now
1073 + " dispatchTime=" + r.dispatchTime
1074 + " startTime=" + r.receiverTime
1075 + " intent=" + r.intent
1076 + " numReceivers=" + numReceivers
1077 + " nextReceiver=" + r.nextReceiver
1078 + " state=" + r.state);
1079 broadcastTimeoutLocked(false); // forcibly finish this broadcast
1080 forceReceive = true;
1081 r.state = BroadcastRecord.IDLE;
1082 }
1083 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001084
Amith Yamasani4e820542018-05-09 13:37:20 -07001085 if (r.state != BroadcastRecord.IDLE) {
1086 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1087 "processNextBroadcast("
1088 + mQueueName + ") called when not idle (state="
1089 + r.state + ")");
1090 return;
1091 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001092
Christopher Tate2f558d22019-01-17 16:58:31 -08001093 // Is the current broadcast is done for any reason?
Amith Yamasani4e820542018-05-09 13:37:20 -07001094 if (r.receivers == null || r.nextReceiver >= numReceivers
1095 || r.resultAbort || forceReceive) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001096 // Send the final result if requested
Amith Yamasani4e820542018-05-09 13:37:20 -07001097 if (r.resultTo != null) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001098 boolean sendResult = true;
Amith Yamasani4e820542018-05-09 13:37:20 -07001099
Christopher Tate2f558d22019-01-17 16:58:31 -08001100 // if this was part of a split/deferral complex, update the refcount and only
1101 // send the completion when we clear all of them
1102 if (r.splitToken != 0) {
1103 int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1104 if (newCount == 0) {
1105 // done! clear out this record's bookkeeping and deliver
1106 if (DEBUG_BROADCAST_DEFERRAL) {
Christopher Tate41c56912019-03-01 18:56:58 -08001107 Slog.i(TAG_BROADCAST,
1108 "Sending broadcast completion for split token "
1109 + r.splitToken + " : " + r.intent.getAction());
Christopher Tate2f558d22019-01-17 16:58:31 -08001110 }
1111 mSplitRefcounts.delete(r.splitToken);
1112 } else {
1113 // still have some split broadcast records in flight; update refcount
1114 // and hold off on the callback
1115 if (DEBUG_BROADCAST_DEFERRAL) {
Christopher Tate41c56912019-03-01 18:56:58 -08001116 Slog.i(TAG_BROADCAST,
1117 "Result refcount now " + newCount + " for split token "
1118 + r.splitToken + " : " + r.intent.getAction()
1119 + " - not sending completion yet");
Christopher Tate2f558d22019-01-17 16:58:31 -08001120 }
1121 sendResult = false;
1122 mSplitRefcounts.put(r.splitToken, newCount);
1123 }
1124 }
1125 if (sendResult) {
1126 try {
1127 if (DEBUG_BROADCAST) {
1128 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1129 + r.intent.getAction() + " app=" + r.callerApp);
1130 }
1131 performReceiveLocked(r.callerApp, r.resultTo,
1132 new Intent(r.intent), r.resultCode,
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001133 r.resultData, r.resultExtras, false, false, r.userId);
Christopher Tate2f558d22019-01-17 16:58:31 -08001134 // Set this to null so that the reference
1135 // (local and remote) isn't kept in the mBroadcastHistory.
1136 r.resultTo = null;
1137 } catch (RemoteException e) {
1138 r.resultTo = null;
1139 Slog.w(TAG, "Failure ["
1140 + mQueueName + "] sending broadcast result of "
1141 + r.intent, e);
1142 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001143 }
1144 }
1145
1146 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1147 cancelBroadcastTimeoutLocked();
1148
1149 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1150 "Finished with ordered broadcast " + r);
1151
1152 // ... and on to the next...
1153 addBroadcastToHistoryLocked(r);
1154 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1155 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1156 // This was an implicit broadcast... let's record it for posterity.
1157 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1158 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1159 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001160 mDispatcher.retireBroadcastLocked(r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001161 r = null;
1162 looped = true;
1163 continue;
1164 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001165
1166 // Check whether the next receiver is under deferral policy, and handle that
1167 // accordingly. If the current broadcast was already part of deferred-delivery
1168 // tracking, we know that it must now be deliverable as-is without re-deferral.
1169 if (!r.deferred) {
1170 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1171 if (mDispatcher.isDeferringLocked(receiverUid)) {
1172 if (DEBUG_BROADCAST_DEFERRAL) {
1173 Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1174 + " at " + r.nextReceiver + " is under deferral");
1175 }
1176 // If this is the only (remaining) receiver in the broadcast, "splitting"
1177 // doesn't make sense -- just defer it as-is and retire it as the
1178 // currently active outgoing broadcast.
1179 BroadcastRecord defer;
1180 if (r.nextReceiver + 1 == numReceivers) {
1181 if (DEBUG_BROADCAST_DEFERRAL) {
Christopher Tate41c56912019-03-01 18:56:58 -08001182 Slog.i(TAG_BROADCAST, "Sole receiver of " + r
Christopher Tate2f558d22019-01-17 16:58:31 -08001183 + " is under deferral; setting aside and proceeding");
1184 }
1185 defer = r;
1186 mDispatcher.retireBroadcastLocked(r);
1187 } else {
1188 // Nontrivial case; split out 'uid's receivers to a new broadcast record
1189 // and defer that, then loop and pick up continuing delivery of the current
1190 // record (now absent those receivers).
1191
1192 // The split operation is guaranteed to match at least at 'nextReceiver'
1193 defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1194 if (DEBUG_BROADCAST_DEFERRAL) {
1195 Slog.i(TAG_BROADCAST, "Post split:");
1196 Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1197 for (int i = 0; i < r.receivers.size(); i++) {
1198 Slog.i(TAG_BROADCAST, " " + r.receivers.get(i));
1199 }
1200 Slog.i(TAG_BROADCAST, "Split receivers:");
1201 for (int i = 0; i < defer.receivers.size(); i++) {
1202 Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i));
1203 }
1204 }
1205 // Track completion refcount as well if relevant
1206 if (r.resultTo != null) {
1207 int token = r.splitToken;
1208 if (token == 0) {
1209 // first split of this record; refcount for 'r' and 'deferred'
1210 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1211 mSplitRefcounts.put(r.splitToken, 2);
Christopher Tate41c56912019-03-01 18:56:58 -08001212 if (DEBUG_BROADCAST_DEFERRAL) {
1213 Slog.i(TAG_BROADCAST,
1214 "Broadcast needs split refcount; using new token "
1215 + r.splitToken);
1216 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001217 } else {
1218 // new split from an already-refcounted situation; increment count
1219 final int curCount = mSplitRefcounts.get(token);
1220 if (DEBUG_BROADCAST_DEFERRAL) {
1221 if (curCount == 0) {
Christopher Tate41c56912019-03-01 18:56:58 -08001222 Slog.wtf(TAG_BROADCAST,
1223 "Split refcount is zero with token for " + r);
Christopher Tate2f558d22019-01-17 16:58:31 -08001224 }
1225 }
1226 mSplitRefcounts.put(token, curCount + 1);
Christopher Tate41c56912019-03-01 18:56:58 -08001227 if (DEBUG_BROADCAST_DEFERRAL) {
1228 Slog.i(TAG_BROADCAST, "New split count for token " + token
1229 + " is " + (curCount + 1));
1230 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001231 }
1232 }
1233 }
1234 mDispatcher.addDeferredBroadcast(receiverUid, defer);
1235 r = null;
1236 looped = true;
1237 continue;
1238 }
1239 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001240 } while (r == null);
1241
1242 // Get the next receiver...
1243 int recIdx = r.nextReceiver++;
1244
1245 // Keep track of when this receiver started, and make sure there
1246 // is a timeout message pending to kill it if need be.
1247 r.receiverTime = SystemClock.uptimeMillis();
1248 if (recIdx == 0) {
1249 r.dispatchTime = r.receiverTime;
1250 r.dispatchClockTime = System.currentTimeMillis();
Ng Zhi An7ff7fdb2019-01-16 15:35:51 -08001251
1252 if (mLogLatencyMetrics) {
1253 StatsLog.write(
1254 StatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1255 r.dispatchClockTime - r.enqueueClockTime);
1256 }
1257
Amith Yamasani4e820542018-05-09 13:37:20 -07001258 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1259 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1260 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1261 System.identityHashCode(r));
1262 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1263 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1264 System.identityHashCode(r));
1265 }
1266 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1267 + mQueueName + "] " + r);
1268 }
1269 if (! mPendingBroadcastTimeoutMessage) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001270 long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
Amith Yamasani4e820542018-05-09 13:37:20 -07001271 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1272 "Submitting BROADCAST_TIMEOUT_MSG ["
1273 + mQueueName + "] for " + r + " at " + timeoutTime);
1274 setBroadcastTimeoutLocked(timeoutTime);
1275 }
1276
1277 final BroadcastOptions brOptions = r.options;
1278 final Object nextReceiver = r.receivers.get(recIdx);
1279
1280 if (nextReceiver instanceof BroadcastFilter) {
1281 // Simple case: this is a registered receiver who gets
1282 // a direct call.
1283 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1284 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1285 "Delivering ordered ["
1286 + mQueueName + "] to registered "
1287 + filter + ": " + r);
1288 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1289 if (r.receiver == null || !r.ordered) {
1290 // The receiver has already finished, so schedule to
1291 // process the next one.
1292 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1293 + mQueueName + "]: ordered="
1294 + r.ordered + " receiver=" + r.receiver);
1295 r.state = BroadcastRecord.IDLE;
1296 scheduleBroadcastsLocked();
1297 } else {
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001298 if (filter.receiverList != null) {
1299 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
Christopher Tate6ac39802019-05-01 16:46:46 -07001300 // r is guaranteed ordered at this point, so we know finishReceiverLocked()
1301 // will get a callback and handle the activity start token lifecycle.
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001302 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001303 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1304 scheduleTempWhitelistLocked(filter.owningUid,
1305 brOptions.getTemporaryAppWhitelistDuration(), r);
1306 }
1307 }
1308 return;
1309 }
1310
1311 // Hard case: need to instantiate the receiver, possibly
1312 // starting its application process to host it.
1313
1314 ResolveInfo info =
1315 (ResolveInfo)nextReceiver;
1316 ComponentName component = new ComponentName(
1317 info.activityInfo.applicationInfo.packageName,
1318 info.activityInfo.name);
1319
1320 boolean skip = false;
1321 if (brOptions != null &&
1322 (info.activityInfo.applicationInfo.targetSdkVersion
1323 < brOptions.getMinManifestReceiverApiLevel() ||
1324 info.activityInfo.applicationInfo.targetSdkVersion
1325 > brOptions.getMaxManifestReceiverApiLevel())) {
1326 skip = true;
1327 }
Dianne Hackborn769b2e72018-12-05 08:51:20 -08001328 if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
1329 component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
1330 Slog.w(TAG, "Association not allowed: broadcasting "
1331 + r.intent.toString()
1332 + " from " + r.callerPackage + " (pid=" + r.callingPid
1333 + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1334 skip = true;
1335 }
1336 if (!skip) {
1337 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1338 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1339 if (skip) {
1340 Slog.w(TAG, "Firewall blocked: broadcasting "
1341 + r.intent.toString()
1342 + " from " + r.callerPackage + " (pid=" + r.callingPid
1343 + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1344 }
1345 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001346 int perm = mService.checkComponentPermission(info.activityInfo.permission,
1347 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1348 info.activityInfo.exported);
1349 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
1350 if (!info.activityInfo.exported) {
1351 Slog.w(TAG, "Permission Denial: broadcasting "
1352 + r.intent.toString()
1353 + " from " + r.callerPackage + " (pid=" + r.callingPid
1354 + ", uid=" + r.callingUid + ")"
1355 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
1356 + " due to receiver " + component.flattenToShortString());
1357 } else {
1358 Slog.w(TAG, "Permission Denial: broadcasting "
1359 + r.intent.toString()
1360 + " from " + r.callerPackage + " (pid=" + r.callingPid
1361 + ", uid=" + r.callingUid + ")"
1362 + " requires " + info.activityInfo.permission
1363 + " due to receiver " + component.flattenToShortString());
1364 }
1365 skip = true;
1366 } else if (!skip && info.activityInfo.permission != null) {
1367 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1368 if (opCode != AppOpsManager.OP_NONE
1369 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1370 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1371 Slog.w(TAG, "Appop Denial: broadcasting "
1372 + r.intent.toString()
1373 + " from " + r.callerPackage + " (pid="
1374 + r.callingPid + ", uid=" + r.callingUid + ")"
1375 + " requires appop " + AppOpsManager.permissionToOp(
1376 info.activityInfo.permission)
1377 + " due to registered receiver "
1378 + component.flattenToShortString());
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001379 skip = true;
1380 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001381 }
1382 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
1383 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1384 for (int i = 0; i < r.requiredPermissions.length; i++) {
1385 String requiredPermission = r.requiredPermissions[i];
1386 try {
1387 perm = AppGlobals.getPackageManager().
1388 checkPermission(requiredPermission,
1389 info.activityInfo.applicationInfo.packageName,
1390 UserHandle
1391 .getUserId(info.activityInfo.applicationInfo.uid));
1392 } catch (RemoteException e) {
1393 perm = PackageManager.PERMISSION_DENIED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001394 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001395 if (perm != PackageManager.PERMISSION_GRANTED) {
1396 Slog.w(TAG, "Permission Denial: receiving "
1397 + r.intent + " to "
1398 + component.flattenToShortString()
1399 + " requires " + requiredPermission
1400 + " due to sender " + r.callerPackage
1401 + " (uid " + r.callingUid + ")");
1402 skip = true;
1403 break;
1404 }
1405 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1406 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1407 && mService.mAppOpsService.noteOperation(appOp,
1408 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1409 != AppOpsManager.MODE_ALLOWED) {
1410 Slog.w(TAG, "Appop Denial: receiving "
1411 + r.intent + " to "
1412 + component.flattenToShortString()
Svet Ganov99b60432015-06-27 13:15:22 -07001413 + " requires appop " + AppOpsManager.permissionToOp(
Amith Yamasani4e820542018-05-09 13:37:20 -07001414 requiredPermission)
1415 + " due to sender " + r.callerPackage
1416 + " (uid " + r.callingUid + ")");
1417 skip = true;
1418 break;
1419 }
1420 }
1421 }
1422 if (!skip && r.appOp != AppOpsManager.OP_NONE
1423 && mService.mAppOpsService.noteOperation(r.appOp,
1424 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1425 != AppOpsManager.MODE_ALLOWED) {
1426 Slog.w(TAG, "Appop Denial: receiving "
1427 + r.intent + " to "
1428 + component.flattenToShortString()
1429 + " requires appop " + AppOpsManager.opToName(r.appOp)
1430 + " due to sender " + r.callerPackage
1431 + " (uid " + r.callingUid + ")");
1432 skip = true;
1433 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001434 boolean isSingleton = false;
1435 try {
1436 isSingleton = mService.isSingleton(info.activityInfo.processName,
1437 info.activityInfo.applicationInfo,
1438 info.activityInfo.name, info.activityInfo.flags);
1439 } catch (SecurityException e) {
1440 Slog.w(TAG, e.getMessage());
1441 skip = true;
1442 }
1443 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1444 if (ActivityManager.checkUidPermission(
1445 android.Manifest.permission.INTERACT_ACROSS_USERS,
1446 info.activityInfo.applicationInfo.uid)
1447 != PackageManager.PERMISSION_GRANTED) {
1448 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1449 + " requests FLAG_SINGLE_USER, but app does not hold "
1450 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1451 skip = true;
1452 }
1453 }
1454 if (!skip && info.activityInfo.applicationInfo.isInstantApp()
1455 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1456 Slog.w(TAG, "Instant App Denial: receiving "
1457 + r.intent
1458 + " to " + component.flattenToShortString()
1459 + " due to sender " + r.callerPackage
1460 + " (uid " + r.callingUid + ")"
1461 + " Instant Apps do not support manifest receivers");
1462 skip = true;
1463 }
1464 if (!skip && r.callerInstantApp
1465 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
1466 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1467 Slog.w(TAG, "Instant App Denial: receiving "
1468 + r.intent
1469 + " to " + component.flattenToShortString()
1470 + " requires receiver have visibleToInstantApps set"
1471 + " due to sender " + r.callerPackage
1472 + " (uid " + r.callingUid + ")");
1473 skip = true;
1474 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001475 if (r.curApp != null && r.curApp.isCrashing()) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001476 // If the target process is crashing, just skip it.
1477 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1478 + " to " + r.curApp + ": process crashing");
1479 skip = true;
1480 }
1481 if (!skip) {
1482 boolean isAvailable = false;
1483 try {
1484 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1485 info.activityInfo.packageName,
1486 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1487 } catch (Exception e) {
1488 // all such failures mean we skip this receiver
1489 Slog.w(TAG, "Exception getting recipient info for "
1490 + info.activityInfo.packageName, e);
1491 }
1492 if (!isAvailable) {
1493 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1494 "Skipping delivery to " + info.activityInfo.packageName + " / "
1495 + info.activityInfo.applicationInfo.uid
1496 + " : package no longer available");
1497 skip = true;
1498 }
1499 }
1500
1501 // If permissions need a review before any of the app components can run, we drop
1502 // the broadcast and if the calling app is in the foreground and the broadcast is
1503 // explicit we launch the review UI passing it a pending intent to send the skipped
1504 // broadcast.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001505 if (!skip) {
Amith Yamasani4e820542018-05-09 13:37:20 -07001506 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1507 info.activityInfo.packageName, UserHandle.getUserId(
1508 info.activityInfo.applicationInfo.uid))) {
1509 skip = true;
1510 }
1511 }
1512
1513 // This is safe to do even if we are skipping the broadcast, and we need
1514 // this information now to evaluate whether it is going to be allowed to run.
1515 final int receiverUid = info.activityInfo.applicationInfo.uid;
1516 // If it's a singleton, it needs to be the same app or a special app
1517 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1518 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1519 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1520 }
1521 String targetProcess = info.activityInfo.processName;
1522 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1523 info.activityInfo.applicationInfo.uid, false);
1524
1525 if (!skip) {
1526 final int allowed = mService.getAppStartModeLocked(
1527 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1528 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
1529 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1530 // We won't allow this receiver to be launched if the app has been
1531 // completely disabled from launches, or it was not explicitly sent
1532 // to it and the app is in a state that should not receive it
1533 // (depending on how getAppStartModeLocked has determined that).
1534 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1535 Slog.w(TAG, "Background execution disabled: receiving "
1536 + r.intent + " to "
1537 + component.flattenToShortString());
1538 skip = true;
1539 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
1540 || (r.intent.getComponent() == null
1541 && r.intent.getPackage() == null
1542 && ((r.intent.getFlags()
1543 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1544 && !isSignaturePerm(r.requiredPermissions))) {
1545 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1546 component.getPackageName());
1547 Slog.w(TAG, "Background execution not allowed: receiving "
1548 + r.intent + " to "
Svet Ganov99b60432015-06-27 13:15:22 -07001549 + component.flattenToShortString());
1550 skip = true;
1551 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001552 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001553 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001554
Amith Yamasani4e820542018-05-09 13:37:20 -07001555 if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1556 && !mService.mUserController
1557 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1558 0 /* flags */)) {
1559 skip = true;
1560 Slog.w(TAG,
1561 "Skipping delivery to " + info.activityInfo.packageName + " / "
1562 + info.activityInfo.applicationInfo.uid + " : user is not running");
1563 }
Svet Ganov9c165d72015-12-01 19:52:26 -08001564
Amith Yamasani4e820542018-05-09 13:37:20 -07001565 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001566 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Amith Yamasani4e820542018-05-09 13:37:20 -07001567 "Skipping delivery of ordered [" + mQueueName + "] "
Christopher Tate41c56912019-03-01 18:56:58 -08001568 + r + " for reason described above");
Amith Yamasani4e820542018-05-09 13:37:20 -07001569 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1570 r.receiver = null;
1571 r.curFilter = null;
1572 r.state = BroadcastRecord.IDLE;
1573 r.manifestSkipCount++;
1574 scheduleBroadcastsLocked();
1575 return;
1576 }
1577 r.manifestCount++;
1578
1579 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1580 r.state = BroadcastRecord.APP_RECEIVE;
1581 r.curComponent = component;
1582 r.curReceiver = info.activityInfo;
1583 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1584 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1585 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1586 + receiverUid);
1587 }
1588
1589 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1590 scheduleTempWhitelistLocked(receiverUid,
1591 brOptions.getTemporaryAppWhitelistDuration(), r);
1592 }
1593
1594 // Broadcast is being executed, its package can't be stopped.
1595 try {
1596 AppGlobals.getPackageManager().setPackageStoppedState(
Christopher Tatea3a455d2018-12-07 17:22:46 -08001597 r.curComponent.getPackageName(), false, r.userId);
Amith Yamasani4e820542018-05-09 13:37:20 -07001598 } catch (RemoteException e) {
1599 } catch (IllegalArgumentException e) {
1600 Slog.w(TAG, "Failed trying to unstop package "
1601 + r.curComponent.getPackageName() + ": " + e);
1602 }
1603
1604 // Is this receiver's application already running?
1605 if (app != null && app.thread != null && !app.killed) {
1606 try {
1607 app.addPackage(info.activityInfo.packageName,
Dianne Hackborn6f30f182019-05-23 15:41:41 -07001608 info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001609 maybeAddAllowBackgroundActivityStartsToken(app, r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001610 processCurBroadcastLocked(r, app, skipOomAdj);
1611 return;
1612 } catch (RemoteException e) {
1613 Slog.w(TAG, "Exception when sending broadcast to "
1614 + r.curComponent, e);
1615 } catch (RuntimeException e) {
1616 Slog.wtf(TAG, "Failed sending broadcast to "
1617 + r.curComponent + " with " + r.intent, e);
1618 // If some unexpected exception happened, just skip
1619 // this broadcast. At this point we are not in the call
1620 // from a client, so throwing an exception out from here
1621 // will crash the entire system instead of just whoever
1622 // sent the broadcast.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001623 logBroadcastReceiverDiscardLocked(r);
1624 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001625 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001626 scheduleBroadcastsLocked();
Amith Yamasani4e820542018-05-09 13:37:20 -07001627 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001628 r.state = BroadcastRecord.IDLE;
1629 return;
1630 }
1631
Amith Yamasani4e820542018-05-09 13:37:20 -07001632 // If a dead object exception was thrown -- fall through to
1633 // restart the application.
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001634 }
Amith Yamasani4e820542018-05-09 13:37:20 -07001635
1636 // Not running -- get it started, to be executed when the app comes up.
1637 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1638 "Need to start app ["
1639 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1640 if ((r.curApp=mService.startProcessLocked(targetProcess,
1641 info.activityInfo.applicationInfo, true,
1642 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
Martijn Coenene8431c22019-03-28 14:09:38 +01001643 new HostingRecord("broadcast", r.curComponent),
Amith Yamasani4e820542018-05-09 13:37:20 -07001644 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1645 == null) {
1646 // Ah, this recipient is unavailable. Finish it if necessary,
1647 // and mark the broadcast record as ready for the next.
1648 Slog.w(TAG, "Unable to launch app "
1649 + info.activityInfo.applicationInfo.packageName + "/"
1650 + receiverUid + " for broadcast "
1651 + r.intent + ": process is bad");
1652 logBroadcastReceiverDiscardLocked(r);
1653 finishReceiverLocked(r, r.resultCode, r.resultData,
1654 r.resultExtras, r.resultAbort, false);
1655 scheduleBroadcastsLocked();
1656 r.state = BroadcastRecord.IDLE;
1657 return;
1658 }
1659
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001660 maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
Amith Yamasani4e820542018-05-09 13:37:20 -07001661 mPendingBroadcast = r;
1662 mPendingBroadcastRecvIndex = recIdx;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001663 }
1664
Michal Karpinski4b8aef22019-02-21 14:56:51 +00001665 private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
1666 if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
1667 return;
1668 }
1669 String msgToken = (proc.toShortString() + r.toString()).intern();
1670 // first, if there exists a past scheduled request to remove this token, drop
1671 // that request - we don't want the token to be swept from under our feet...
1672 mHandler.removeCallbacksAndMessages(msgToken);
1673 // ...then add the token
1674 proc.addAllowBackgroundActivityStartsToken(r);
1675 }
1676
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001677 final void setBroadcastTimeoutLocked(long timeoutTime) {
1678 if (! mPendingBroadcastTimeoutMessage) {
1679 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1680 mHandler.sendMessageAtTime(msg, timeoutTime);
1681 mPendingBroadcastTimeoutMessage = true;
1682 }
1683 }
1684
1685 final void cancelBroadcastTimeoutLocked() {
1686 if (mPendingBroadcastTimeoutMessage) {
1687 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1688 mPendingBroadcastTimeoutMessage = false;
1689 }
1690 }
1691
1692 final void broadcastTimeoutLocked(boolean fromMsg) {
1693 if (fromMsg) {
1694 mPendingBroadcastTimeoutMessage = false;
1695 }
1696
Christopher Tate2f558d22019-01-17 16:58:31 -08001697 if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001698 return;
1699 }
1700
1701 long now = SystemClock.uptimeMillis();
Christopher Tate2f558d22019-01-17 16:58:31 -08001702 BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001703 if (fromMsg) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001704 if (!mService.mProcessesReady) {
Christopher Tate1b72ca32019-01-30 16:25:53 -08001705 // Only process broadcast timeouts if the system is ready; some early
1706 // broadcasts do heavy work setting up system facilities
1707 return;
1708 }
1709
1710 // If the broadcast is generally exempt from timeout tracking, we're done
1711 if (r.timeoutExempt) {
1712 if (DEBUG_BROADCAST) {
1713 Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1714 + r.intent.getAction());
1715 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001716 return;
1717 }
1718
Christopher Tate2f558d22019-01-17 16:58:31 -08001719 long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001720 if (timeoutTime > now) {
1721 // We can observe premature timeouts because we do not cancel and reset the
1722 // broadcast timeout message after each receiver finishes. Instead, we set up
1723 // an initial timeout then kick it down the road a little further as needed
1724 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001725 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001726 "Premature timeout ["
1727 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1728 + timeoutTime);
1729 setBroadcastTimeoutLocked(timeoutTime);
1730 return;
1731 }
1732 }
1733
Christopher Tate2f558d22019-01-17 16:58:31 -08001734 if (r.state == BroadcastRecord.WAITING_SERVICES) {
Dianne Hackborn6285a322013-09-18 12:09:47 -07001735 // In this case the broadcast had already finished, but we had decided to wait
1736 // for started services to finish as well before going on. So if we have actually
1737 // waited long enough time timeout the broadcast, let's give up on the whole thing
1738 // and just move on to the next.
Christopher Tate2f558d22019-01-17 16:58:31 -08001739 Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1740 ? r.curComponent.flattenToShortString() : "(null)"));
1741 r.curComponent = null;
1742 r.state = BroadcastRecord.IDLE;
Dianne Hackborn6285a322013-09-18 12:09:47 -07001743 processNextBroadcast(false);
1744 return;
1745 }
1746
Christopher Tatef2370162018-03-16 16:26:23 -07001747 // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1748 // tidying up and moving on to the next broadcast without crashing or ANRing this
1749 // app just because it's stopped at a breakpoint.
Wale Ogunwale906f9c62018-07-23 11:23:44 -07001750 final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
Christopher Tatef2370162018-03-16 16:26:23 -07001751
1752 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001753 + ", started " + (now - r.receiverTime) + "ms ago");
1754 r.receiverTime = now;
Christopher Tatef2370162018-03-16 16:26:23 -07001755 if (!debugging) {
1756 r.anrCount++;
1757 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001758
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001759 ProcessRecord app = null;
1760 String anrMessage = null;
1761
Christopher Tatea6b2c882017-09-01 11:41:39 -07001762 Object curReceiver;
1763 if (r.nextReceiver > 0) {
1764 curReceiver = r.receivers.get(r.nextReceiver-1);
1765 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1766 } else {
1767 curReceiver = r.curReceiver;
1768 }
1769 Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001770 logBroadcastReceiverDiscardLocked(r);
Christopher Tatea6b2c882017-09-01 11:41:39 -07001771 if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001772 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1773 if (bf.receiverList.pid != 0
1774 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1775 synchronized (mService.mPidsSelfLocked) {
1776 app = mService.mPidsSelfLocked.get(
1777 bf.receiverList.pid);
1778 }
1779 }
1780 } else {
1781 app = r.curApp;
1782 }
1783
1784 if (app != null) {
1785 anrMessage = "Broadcast of " + r.intent.toString();
1786 }
1787
1788 if (mPendingBroadcast == r) {
1789 mPendingBroadcast = null;
1790 }
1791
1792 // Move on to the next receiver.
1793 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001794 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001795 scheduleBroadcastsLocked();
1796
Christopher Tatef2370162018-03-16 16:26:23 -07001797 if (!debugging && anrMessage != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001798 // Post the ANR to the handler since we do not want to process ANRs while
1799 // potentially holding our lock.
1800 mHandler.post(new AppNotResponding(app, anrMessage));
1801 }
1802 }
1803
Christopher Tatef278f122015-04-22 13:12:01 -07001804 private final int ringAdvance(int x, final int increment, final int ringSize) {
1805 x += increment;
1806 if (x < 0) return (ringSize - 1);
1807 else if (x >= ringSize) return 0;
1808 else return x;
1809 }
1810
Makoto Onuki97f82f22017-05-31 16:20:21 -07001811 private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1812 if (original.callingUid < 0) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001813 // This was from a registerReceiver() call; ignore it.
1814 return;
1815 }
Makoto Onuki97f82f22017-05-31 16:20:21 -07001816 original.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001817
Carmen Jacksona68e3452017-01-17 14:01:33 -08001818 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1819 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Makoto Onuki97f82f22017-05-31 16:20:21 -07001820 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1821 System.identityHashCode(original));
Carmen Jacksona68e3452017-01-17 14:01:33 -08001822 }
1823
Makoto Onuki97f82f22017-05-31 16:20:21 -07001824 // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1825 // So don't change the incoming record directly.
1826 final BroadcastRecord historyRecord = original.maybeStripForHistory();
1827
1828 mBroadcastHistory[mHistoryNext] = historyRecord;
Christopher Tatef278f122015-04-22 13:12:01 -07001829 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1830
Makoto Onuki97f82f22017-05-31 16:20:21 -07001831 mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1832 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1833 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
Christopher Tatef278f122015-04-22 13:12:01 -07001834 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1835 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001836 }
1837
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001838 boolean cleanupDisabledPackageReceiversLocked(
1839 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1840 boolean didSomething = false;
1841 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1842 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1843 packageName, filterByClasses, userId, doit);
1844 if (!doit && didSomething) {
1845 return true;
1846 }
1847 }
1848
Christopher Tate2f558d22019-01-17 16:58:31 -08001849 didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1850 filterByClasses, userId, doit);
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001851
1852 return didSomething;
1853 }
1854
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001855 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001856 final int logIndex = r.nextReceiver - 1;
1857 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1858 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001859 if (curReceiver instanceof BroadcastFilter) {
1860 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1861 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001862 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001863 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001864 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001865 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001866 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001867 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001868 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001869 }
1870 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001871 if (logIndex < 0) Slog.w(TAG,
1872 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001873 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001874 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001875 r.intent.getAction(),
1876 r.nextReceiver,
1877 "NONE");
1878 }
1879 }
1880
Carmen Jacksona68e3452017-01-17 14:01:33 -08001881 private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1882 return String.format("Broadcast %s from %s (%s) %s",
1883 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1884 record.callerPackage == null ? "" : record.callerPackage,
1885 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1886 record.intent == null ? "" : record.intent.getAction());
1887 }
1888
Christopher Tateb486f412019-02-12 18:05:17 -08001889 boolean isIdle() {
Christopher Tate2f558d22019-01-17 16:58:31 -08001890 return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
Jeff Sharkeyfd658132017-05-03 11:38:01 -06001891 && (mPendingBroadcast == null);
1892 }
1893
Christopher Tateb486f412019-02-12 18:05:17 -08001894 // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1895 // be immediately deliverable.
1896 void cancelDeferrals() {
Christopher Tate01c3ae12019-02-27 16:51:10 -08001897 synchronized (mService) {
1898 mDispatcher.cancelDeferralsLocked();
1899 scheduleBroadcastsLocked();
1900 }
Christopher Tateb486f412019-02-12 18:05:17 -08001901 }
1902
1903 String describeState() {
1904 synchronized (mService) {
1905 return mParallelBroadcasts.size() + " parallel; "
1906 + mDispatcher.describeStateLocked();
1907 }
1908 }
1909
Yi Jin129fc6c2017-09-28 15:48:38 -07001910 void writeToProto(ProtoOutputStream proto, long fieldId) {
1911 long token = proto.start(fieldId);
1912 proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1913 int N;
1914 N = mParallelBroadcasts.size();
1915 for (int i = N - 1; i >= 0; i--) {
1916 mParallelBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1917 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001918 mDispatcher.writeToProto(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
Yi Jin129fc6c2017-09-28 15:48:38 -07001919 if (mPendingBroadcast != null) {
1920 mPendingBroadcast.writeToProto(proto, BroadcastQueueProto.PENDING_BROADCAST);
1921 }
1922
1923 int lastIndex = mHistoryNext;
1924 int ringIndex = lastIndex;
1925 do {
1926 // increasing index = more recent entry, and we want to print the most
1927 // recent first and work backwards, so we roll through the ring backwards.
1928 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1929 BroadcastRecord r = mBroadcastHistory[ringIndex];
1930 if (r != null) {
1931 r.writeToProto(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1932 }
1933 } while (ringIndex != lastIndex);
1934
1935 lastIndex = ringIndex = mSummaryHistoryNext;
1936 do {
1937 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1938 Intent intent = mBroadcastSummaryHistory[ringIndex];
1939 if (intent == null) {
1940 continue;
1941 }
1942 long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1943 intent.writeToProto(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1944 false, true, true, false);
1945 proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1946 mSummaryHistoryEnqueueTime[ringIndex]);
1947 proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1948 mSummaryHistoryDispatchTime[ringIndex]);
1949 proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1950 mSummaryHistoryFinishTime[ringIndex]);
1951 proto.end(summaryToken);
1952 } while (ringIndex != lastIndex);
1953 proto.end(token);
1954 }
1955
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001956 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1957 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Ng Zhi Ana7f50d42018-09-18 10:51:34 -07001958 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tate2f558d22019-01-17 16:58:31 -08001959 if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001960 || mPendingBroadcast != null) {
1961 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001962 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001963 BroadcastRecord br = mParallelBroadcasts.get(i);
1964 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1965 continue;
1966 }
1967 if (!printed) {
1968 if (needSep) {
1969 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001970 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001971 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001972 printed = true;
1973 pw.println(" Active broadcasts [" + mQueueName + "]:");
1974 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001975 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001976 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001977 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001978
1979 mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1980
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001981 if (dumpPackage == null || (mPendingBroadcast != null
1982 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
Christopher Tate2f558d22019-01-17 16:58:31 -08001983 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001984 pw.println(" Pending broadcast [" + mQueueName + "]:");
1985 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001986 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001987 } else {
1988 pw.println(" (null)");
1989 }
1990 needSep = true;
1991 }
1992 }
1993
Christopher Tate2f558d22019-01-17 16:58:31 -08001994 mConstants.dump(pw);
1995
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001996 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001997 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001998
1999 i = -1;
2000 int lastIndex = mHistoryNext;
2001 int ringIndex = lastIndex;
2002 do {
2003 // increasing index = more recent entry, and we want to print the most
2004 // recent first and work backwards, so we roll through the ring backwards.
2005 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
2006 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002007 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07002008 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002009 }
Christopher Tatef278f122015-04-22 13:12:01 -07002010
2011 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002012 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
2013 continue;
2014 }
2015 if (!printed) {
2016 if (needSep) {
2017 pw.println();
2018 }
2019 needSep = true;
2020 pw.println(" Historical broadcasts [" + mQueueName + "]:");
2021 printed = true;
2022 }
2023 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07002024 pw.print(" Historical Broadcast " + mQueueName + " #");
2025 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07002026 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002027 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002028 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
2029 pw.print(" ");
2030 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07002031 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
2032 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
2033 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002034 Bundle bundle = r.intent.getExtras();
2035 if (bundle != null) {
2036 pw.print(" extras: "); pw.println(bundle.toString());
2037 }
2038 }
Christopher Tatef278f122015-04-22 13:12:01 -07002039 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002040
2041 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07002042 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002043 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002044 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07002045 i = -1;
2046 } else {
2047 // roll over the 'i' full dumps that have already been issued
2048 for (int j = i;
2049 j > 0 && ringIndex != lastIndex;) {
2050 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2051 BroadcastRecord r = mBroadcastHistory[ringIndex];
2052 if (r == null) {
2053 continue;
2054 }
2055 j--;
2056 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002057 }
Christopher Tatef278f122015-04-22 13:12:01 -07002058 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
2059 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07002060 do {
2061 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2062 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002063 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07002064 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002065 }
2066 if (!printed) {
2067 if (needSep) {
2068 pw.println();
2069 }
2070 needSep = true;
2071 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
2072 printed = true;
2073 }
2074 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002075 pw.println(" ...");
2076 break;
2077 }
Christopher Tatef278f122015-04-22 13:12:01 -07002078 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002079 pw.print(" #"); pw.print(i); pw.print(": ");
2080 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07002081 pw.print(" ");
2082 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
2083 - mSummaryHistoryEnqueueTime[ringIndex], pw);
2084 pw.print(" dispatch ");
2085 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
2086 - mSummaryHistoryDispatchTime[ringIndex], pw);
2087 pw.println(" finish");
2088 pw.print(" enq=");
2089 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
2090 pw.print(" disp=");
2091 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
2092 pw.print(" fin=");
2093 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07002094 Bundle bundle = intent.getExtras();
2095 if (bundle != null) {
2096 pw.print(" extras: "); pw.println(bundle.toString());
2097 }
Christopher Tatef278f122015-04-22 13:12:01 -07002098 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08002099 }
2100
2101 return needSep;
2102 }
2103}