blob: aa82d000386a8d1080239ff4bd7d561ec7a34874 [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
Dianne Hackbornb8633f32017-04-11 17:38:42 -070019import android.content.pm.IPackageManager;
20import android.content.pm.PermissionInfo;
Carmen Jacksona68e3452017-01-17 14:01:33 -080021import android.os.Trace;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080022import java.io.FileDescriptor;
23import java.io.PrintWriter;
Christopher Tatef278f122015-04-22 13:12:01 -070024import java.text.SimpleDateFormat;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080025import java.util.ArrayList;
Christopher Tatef278f122015-04-22 13:12:01 -070026import java.util.Date;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -070027import java.util.Set;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080028
Dianne Hackborn7d19e022012-08-07 19:12:33 -070029import android.app.ActivityManager;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080030import android.app.AppGlobals;
Dianne Hackbornf51f6122013-02-04 18:23:34 -080031import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070032import android.app.BroadcastOptions;
Svet Ganov9c165d72015-12-01 19:52:26 -080033import android.app.PendingIntent;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080034import android.content.ComponentName;
35import android.content.IIntentReceiver;
Svet Ganov9c165d72015-12-01 19:52:26 -080036import android.content.IIntentSender;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080037import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080038import android.content.IntentSender;
Dianne Hackborn7d19e022012-08-07 19:12:33 -070039import android.content.pm.ActivityInfo;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080040import android.content.pm.PackageManager;
41import android.content.pm.ResolveInfo;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080045import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080046import android.os.Message;
47import android.os.Process;
48import android.os.RemoteException;
49import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080051import android.util.EventLog;
52import android.util.Slog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070053import android.util.TimeUtils;
Yi Jin129fc6c2017-09-28 15:48:38 -070054import android.util.proto.ProtoOutputStream;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080055
Wale Ogunwaled57969f2014-11-15 19:37:29 -080056import static com.android.server.am.ActivityManagerDebugConfig.*;
57
Yi Jin129fc6c2017-09-28 15:48:38 -070058import com.android.server.am.proto.BroadcastQueueProto;
59
Dianne Hackborn40c8db52012-02-10 18:59:48 -080060/**
61 * BROADCASTS
62 *
63 * We keep two broadcast queues and associated bookkeeping, one for those at
64 * foreground priority, and one for normal (background-priority) broadcasts.
65 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070066public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070067 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080068 private static final String TAG_MU = TAG + POSTFIX_MU;
69 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080070
Dianne Hackborn4c51de42013-10-16 23:34:35 -070071 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070072 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070073 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080074
75 final ActivityManagerService mService;
76
77 /**
78 * Recognizable moniker for this queue
79 */
80 final String mQueueName;
81
82 /**
83 * Timeout period for this queue's broadcasts
84 */
85 final long mTimeoutPeriod;
86
87 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070088 * If true, we can delay broadcasts while waiting services to finish in the previous
89 * receiver's process.
90 */
91 final boolean mDelayBehindServices;
92
93 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080094 * Lists of all active broadcasts that are to be executed immediately
95 * (without waiting for another broadcast to finish). Currently this only
96 * contains broadcasts to registered receivers, to avoid spinning up
97 * a bunch of processes to execute IntentReceiver components. Background-
98 * and foreground-priority broadcasts are queued separately.
99 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700100 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -0700101
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800102 /**
103 * List of all active broadcasts that are to be executed one at a time.
104 * The object at the top of the list is the currently activity broadcasts;
105 * those after it are waiting for the top to finish. As with parallel
106 * broadcasts, separate background- and foreground-priority queues are
107 * maintained.
108 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700109 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800110
111 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700112 * Historical data of past broadcasts, for debugging. This is a ring buffer
113 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800114 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700115 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700116 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800117
118 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700119 * Summary of historical data of past broadcasts, for debugging. This is a
120 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700121 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700122 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700123 int mSummaryHistoryNext = 0;
124
125 /**
126 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
127 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
128 * clock time, not elapsed.
129 */
130 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
131 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
132 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700133
134 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800135 * Set when we current have a BROADCAST_INTENT_MSG in flight.
136 */
137 boolean mBroadcastsScheduled = false;
138
139 /**
140 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
141 */
142 boolean mPendingBroadcastTimeoutMessage;
143
144 /**
145 * Intent broadcasts that we have tried to start, but are
146 * waiting for the application's process to be created. We only
147 * need one per scheduling class (instead of a list) because we always
148 * process broadcasts one at a time, so no others can be started while
149 * waiting for this one.
150 */
151 BroadcastRecord mPendingBroadcast = null;
152
153 /**
154 * The receiver index that is pending, to restart the broadcast if needed.
155 */
156 int mPendingBroadcastRecvIndex;
157
158 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
159 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
160
Jeff Brown6f357d32014-01-15 20:40:55 -0800161 final BroadcastHandler mHandler;
162
163 private final class BroadcastHandler extends Handler {
164 public BroadcastHandler(Looper looper) {
165 super(looper, null, true);
166 }
167
168 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800169 public void handleMessage(Message msg) {
170 switch (msg.what) {
171 case BROADCAST_INTENT_MSG: {
172 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800173 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800174 processNextBroadcast(true);
175 } break;
176 case BROADCAST_TIMEOUT_MSG: {
177 synchronized (mService) {
178 broadcastTimeoutLocked(true);
179 }
180 } break;
181 }
182 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800183 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800184
185 private final class AppNotResponding implements Runnable {
186 private final ProcessRecord mApp;
187 private final String mAnnotation;
188
189 public AppNotResponding(ProcessRecord app, String annotation) {
190 mApp = app;
191 mAnnotation = annotation;
192 }
193
194 @Override
195 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100196 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800197 }
198 }
199
Jeff Brown6f357d32014-01-15 20:40:55 -0800200 BroadcastQueue(ActivityManagerService service, Handler handler,
201 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800202 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800203 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800204 mQueueName = name;
205 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700206 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800207 }
208
Jeff Sharkeyfd658132017-05-03 11:38:01 -0600209 @Override
210 public String toString() {
211 return mQueueName;
212 }
213
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800214 public boolean isPendingBroadcastProcessLocked(int pid) {
215 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
216 }
217
218 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
219 mParallelBroadcasts.add(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800220 enqueueBroadcastHelper(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800221 }
222
223 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
224 mOrderedBroadcasts.add(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800225 enqueueBroadcastHelper(r);
226 }
227
228 /**
229 * Don't call this method directly; call enqueueParallelBroadcastLocked or
230 * enqueueOrderedBroadcastLocked.
231 */
232 private void enqueueBroadcastHelper(BroadcastRecord r) {
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700233 r.enqueueClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -0800234
235 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
236 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
237 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
238 System.identityHashCode(r));
239 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800240 }
241
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800242 /**
243 * Find the same intent from queued parallel broadcast, replace with a new one and return
244 * the old one.
245 */
246 public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
247 return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800248 }
249
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800250 /**
251 * Find the same intent from queued ordered broadcast, replace with a new one and return
252 * the old one.
253 */
254 public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
255 return replaceBroadcastLocked(mOrderedBroadcasts, r, "ORDERED");
256 }
257
258 private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
259 BroadcastRecord r, String typeForLogging) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700260 final Intent intent = r.intent;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800261 for (int i = queue.size() - 1; i > 0; i--) {
262 final BroadcastRecord old = queue.get(i);
263 if (old.userId == r.userId && intent.filterEquals(old.intent)) {
264 if (DEBUG_BROADCAST) {
265 Slog.v(TAG_BROADCAST, "***** DROPPING "
266 + typeForLogging + " [" + mQueueName + "]: " + intent);
267 }
268 queue.set(i, r);
269 return old;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800270 }
271 }
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800272 return null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800273 }
274
275 private final void processCurBroadcastLocked(BroadcastRecord r,
276 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800277 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800278 "Process cur broadcast " + r + " for app " + app);
279 if (app.thread == null) {
280 throw new RemoteException();
281 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700282 if (app.inFullBackup) {
283 skipReceiverLocked(r);
284 return;
285 }
286
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800287 r.receiver = app.thread.asBinder();
288 r.curApp = app;
yangzhenyud509bc92016-08-31 18:26:46 +0800289 app.curReceivers.add(r);
Dianne Hackborna413dc02013-07-12 12:02:55 -0700290 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700291 mService.updateLruProcessLocked(app, false, null);
292 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800293
294 // Tell the application to launch this receiver.
295 r.intent.setComponent(r.curComponent);
296
297 boolean started = false;
298 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800299 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 "Delivering to component " + r.curComponent
301 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700302 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
303 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
305 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700306 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
307 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800308 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800309 "Process cur broadcast " + r + " DELIVERED for app " + app);
310 started = true;
311 } finally {
312 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800313 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800314 "Process cur broadcast " + r + ": NOT STARTED!");
315 r.receiver = null;
316 r.curApp = null;
yangzhenyud509bc92016-08-31 18:26:46 +0800317 app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800318 }
319 }
320 }
321
322 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
323 boolean didSomething = false;
324 final BroadcastRecord br = mPendingBroadcast;
325 if (br != null && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700326 if (br.curApp != app) {
327 Slog.e(TAG, "App mismatch when sending pending broadcast to "
328 + app.processName + ", intended target is " + br.curApp.processName);
329 return false;
330 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800331 try {
332 mPendingBroadcast = null;
333 processCurBroadcastLocked(br, app);
334 didSomething = true;
335 } catch (Exception e) {
336 Slog.w(TAG, "Exception in new application when starting receiver "
337 + br.curComponent.flattenToShortString(), e);
338 logBroadcastReceiverDiscardLocked(br);
339 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700340 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800341 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700342 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800343 br.state = BroadcastRecord.IDLE;
344 throw new RuntimeException(e.getMessage());
345 }
346 }
347 return didSomething;
348 }
349
350 public void skipPendingBroadcastLocked(int pid) {
351 final BroadcastRecord br = mPendingBroadcast;
352 if (br != null && br.curApp.pid == pid) {
353 br.state = BroadcastRecord.IDLE;
354 br.nextReceiver = mPendingBroadcastRecvIndex;
355 mPendingBroadcast = null;
356 scheduleBroadcastsLocked();
357 }
358 }
359
360 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700361 BroadcastRecord r = null;
362 if (mOrderedBroadcasts.size() > 0) {
363 BroadcastRecord br = mOrderedBroadcasts.get(0);
364 if (br.curApp == app) {
365 r = br;
366 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800367 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800368 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800369 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800370 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800371 r = mPendingBroadcast;
372 }
373
374 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700375 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800376 }
377 }
378
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700379 private void skipReceiverLocked(BroadcastRecord r) {
380 logBroadcastReceiverDiscardLocked(r);
381 finishReceiverLocked(r, r.resultCode, r.resultData,
382 r.resultExtras, r.resultAbort, false);
383 scheduleBroadcastsLocked();
384 }
385
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800386 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800387 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800388 + mQueueName + "]: current="
389 + mBroadcastsScheduled);
390
391 if (mBroadcastsScheduled) {
392 return;
393 }
394 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
395 mBroadcastsScheduled = true;
396 }
397
398 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
399 if (mOrderedBroadcasts.size() > 0) {
400 final BroadcastRecord r = mOrderedBroadcasts.get(0);
401 if (r != null && r.receiver == receiver) {
402 return r;
403 }
404 }
405 return null;
406 }
407
408 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700409 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
410 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700411 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800412 r.state = BroadcastRecord.IDLE;
413 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700414 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800415 }
416 r.receiver = null;
417 r.intent.setComponent(null);
yangzhenyud509bc92016-08-31 18:26:46 +0800418 if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
419 r.curApp.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800420 }
421 if (r.curFilter != null) {
422 r.curFilter.receiverList.curBroadcast = null;
423 }
424 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800425 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700426 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800427 mPendingBroadcast = null;
428
429 r.resultCode = resultCode;
430 r.resultData = resultData;
431 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700432 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
433 r.resultAbort = resultAbort;
434 } else {
435 r.resultAbort = false;
436 }
437
438 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
439 && r.queue.mOrderedBroadcasts.size() > 0
440 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700441 ActivityInfo nextReceiver;
442 if (r.nextReceiver < r.receivers.size()) {
443 Object obj = r.receivers.get(r.nextReceiver);
444 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
445 } else {
446 nextReceiver = null;
447 }
448 // Don't do this if the next receive is in the same process as the current one.
449 if (receiver == null || nextReceiver == null
450 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
451 || !receiver.processName.equals(nextReceiver.processName)) {
452 // In this case, we are ready to process the next receiver for the current broadcast,
453 // but are on a queue that would like to wait for services to finish before moving
454 // on. If there are background services currently starting, then we will go into a
455 // special state where we hold off on continuing this broadcast until they are done.
Dianne Hackbornad51be92016-08-16 16:27:36 -0700456 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800457 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700458 r.state = BroadcastRecord.WAITING_SERVICES;
459 return false;
460 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700461 }
462 }
463
464 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800465
466 // We will process the next receiver right now if this is finishing
467 // an app receiver (which is always asynchronous) or after we have
468 // come back from calling a receiver.
469 return state == BroadcastRecord.APP_RECEIVE
470 || state == BroadcastRecord.CALL_DONE_RECEIVE;
471 }
472
Dianne Hackborn6285a322013-09-18 12:09:47 -0700473 public void backgroundServicesFinishedLocked(int userId) {
474 if (mOrderedBroadcasts.size() > 0) {
475 BroadcastRecord br = mOrderedBroadcasts.get(0);
476 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800477 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700478 br.curComponent = null;
479 br.state = BroadcastRecord.IDLE;
480 processNextBroadcast(false);
481 }
482 }
483 }
484
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700485 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800486 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700487 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800488 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000489 if (app != null) {
490 if (app.thread != null) {
491 // If we have an app thread, do the call through that so it is
492 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700493 try {
494 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
495 data, extras, ordered, sticky, sendingUser, app.repProcState);
496 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
497 // DeadObjectException when the process isn't actually dead.
498 //} catch (DeadObjectException ex) {
499 // Failed to call into the process. It's dying so just let it die and move on.
500 // throw ex;
501 } catch (RemoteException ex) {
502 // Failed to call into the process. It's either dying or wedged. Kill it gently.
503 synchronized (mService) {
504 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
505 + " (pid " + app.pid + "). Crashing it.");
506 app.scheduleCrash("can't deliver broadcast");
507 }
508 throw ex;
509 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000510 } else {
511 // Application has died. Receiver doesn't exist.
512 throw new RemoteException("app.thread must not be null");
513 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800514 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700515 receiver.performReceive(intent, resultCode, data, extras, ordered,
516 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800517 }
518 }
519
Svet Ganov99b60432015-06-27 13:15:22 -0700520 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800521 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800522 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700523 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800524 int perm = mService.checkComponentPermission(filter.requiredPermission,
525 r.callingPid, r.callingUid, -1, true);
526 if (perm != PackageManager.PERMISSION_GRANTED) {
527 Slog.w(TAG, "Permission Denial: broadcasting "
528 + r.intent.toString()
529 + " from " + r.callerPackage + " (pid="
530 + r.callingPid + ", uid=" + r.callingUid + ")"
531 + " requires " + filter.requiredPermission
532 + " due to registered receiver " + filter);
533 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700534 } else {
535 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
536 if (opCode != AppOpsManager.OP_NONE
537 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
538 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
539 Slog.w(TAG, "Appop Denial: broadcasting "
540 + r.intent.toString()
541 + " from " + r.callerPackage + " (pid="
542 + r.callingPid + ", uid=" + r.callingUid + ")"
543 + " requires appop " + AppOpsManager.permissionToOp(
544 filter.requiredPermission)
545 + " due to registered receiver " + filter);
546 skip = true;
547 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800548 }
549 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700550 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
551 for (int i = 0; i < r.requiredPermissions.length; i++) {
552 String requiredPermission = r.requiredPermissions[i];
553 int perm = mService.checkComponentPermission(requiredPermission,
554 filter.receiverList.pid, filter.receiverList.uid, -1, true);
555 if (perm != PackageManager.PERMISSION_GRANTED) {
556 Slog.w(TAG, "Permission Denial: receiving "
557 + r.intent.toString()
558 + " to " + filter.receiverList.app
559 + " (pid=" + filter.receiverList.pid
560 + ", uid=" + filter.receiverList.uid + ")"
561 + " requires " + requiredPermission
562 + " due to sender " + r.callerPackage
563 + " (uid " + r.callingUid + ")");
564 skip = true;
565 break;
566 }
567 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700568 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700569 && mService.mAppOpsService.noteOperation(appOp,
570 filter.receiverList.uid, filter.packageName)
571 != AppOpsManager.MODE_ALLOWED) {
572 Slog.w(TAG, "Appop Denial: receiving "
573 + r.intent.toString()
574 + " to " + filter.receiverList.app
575 + " (pid=" + filter.receiverList.pid
576 + ", uid=" + filter.receiverList.uid + ")"
577 + " requires appop " + AppOpsManager.permissionToOp(
578 requiredPermission)
579 + " due to sender " + r.callerPackage
580 + " (uid " + r.callingUid + ")");
581 skip = true;
582 break;
583 }
584 }
585 }
586 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
587 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000588 filter.receiverList.pid, filter.receiverList.uid, -1, true);
589 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700590 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000591 + r.intent.toString()
592 + " to " + filter.receiverList.app
593 + " (pid=" + filter.receiverList.pid
594 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000595 + " due to sender " + r.callerPackage
596 + " (uid " + r.callingUid + ")");
597 skip = true;
598 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700599 }
600 if (!skip && r.appOp != AppOpsManager.OP_NONE
601 && mService.mAppOpsService.noteOperation(r.appOp,
602 filter.receiverList.uid, filter.packageName)
603 != AppOpsManager.MODE_ALLOWED) {
604 Slog.w(TAG, "Appop Denial: receiving "
605 + r.intent.toString()
606 + " to " + filter.receiverList.app
607 + " (pid=" + filter.receiverList.pid
608 + ", uid=" + filter.receiverList.uid + ")"
609 + " requires appop " + AppOpsManager.opToName(r.appOp)
610 + " due to sender " + r.callerPackage
611 + " (uid " + r.callingUid + ")");
612 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700613 }
Svet Ganov99b60432015-06-27 13:15:22 -0700614
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700615 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
616 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800617 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700618 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800619
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700620 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.killed
621 || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700622 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
Dianne Hackborn443d35a2017-06-16 17:59:35 -0700623 + " to " + filter.receiverList + ": process gone or crashing");
Dianne Hackborn9357b112013-10-03 18:27:48 -0700624 skip = true;
625 }
626
Chad Brubakerb7e34d52017-02-22 12:36:06 -0800627 // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
628 // visible to Instant Apps.
629 final boolean visibleToInstantApps =
630 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
631
632 if (!skip && !visibleToInstantApps && filter.instantApp
633 && filter.receiverList.uid != r.callingUid) {
634 Slog.w(TAG, "Instant App Denial: receiving "
635 + r.intent.toString()
636 + " to " + filter.receiverList.app
637 + " (pid=" + filter.receiverList.pid
638 + ", uid=" + filter.receiverList.uid + ")"
639 + " due to sender " + r.callerPackage
640 + " (uid " + r.callingUid + ")"
641 + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
642 skip = true;
643 }
644
Chad Brubaker816c83b2017-03-02 10:27:59 -0800645 if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
646 && filter.receiverList.uid != r.callingUid) {
647 Slog.w(TAG, "Instant App Denial: receiving "
648 + r.intent.toString()
649 + " to " + filter.receiverList.app
650 + " (pid=" + filter.receiverList.pid
651 + ", uid=" + filter.receiverList.uid + ")"
652 + " requires receiver be visible to instant apps"
653 + " due to sender " + r.callerPackage
654 + " (uid " + r.callingUid + ")");
655 skip = true;
656 }
657
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800658 if (skip) {
659 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
660 return;
661 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800662
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800663 // If permissions need a review before any of the app components can run, we drop
664 // the broadcast and if the calling app is in the foreground and the broadcast is
665 // explicit we launch the review UI passing it a pending intent to send the skipped
666 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -0700667 if (mService.mPermissionReviewRequired) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800668 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
669 filter.owningUserId)) {
670 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
671 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800672 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800673 }
674
675 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
676
677 // If this is not being sent as an ordered broadcast, then we
678 // don't want to touch the fields that keep track of the current
679 // state of ordered broadcasts.
680 if (ordered) {
681 r.receiver = filter.receiverList.receiver.asBinder();
682 r.curFilter = filter;
683 filter.receiverList.curBroadcast = r;
684 r.state = BroadcastRecord.CALL_IN_RECEIVE;
685 if (filter.receiverList.app != null) {
686 // Bump hosting application to no longer be in background
687 // scheduling class. Note that we can't do that if there
688 // isn't an app... but we can only be in that case for
689 // things that directly call the IActivityManager API, which
690 // are already core system stuff so don't matter for this.
691 r.curApp = filter.receiverList.app;
yangzhenyud509bc92016-08-31 18:26:46 +0800692 filter.receiverList.app.curReceivers.add(r);
Amith Yamasani385c3ad2017-05-04 14:27:11 -0700693 mService.updateOomAdjLocked(r.curApp, true);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800694 }
695 }
696 try {
697 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
698 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700699 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
700 // Skip delivery if full backup in progress
701 // If it's an ordered broadcast, we need to continue to the next receiver.
702 if (ordered) {
703 skipReceiverLocked(r);
704 }
705 } else {
706 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
707 new Intent(r.intent), r.resultCode, r.resultData,
708 r.resultExtras, r.ordered, r.initialSticky, r.userId);
709 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800710 if (ordered) {
711 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
712 }
713 } catch (RemoteException e) {
714 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
715 if (ordered) {
716 r.receiver = null;
717 r.curFilter = null;
718 filter.receiverList.curBroadcast = null;
719 if (filter.receiverList.app != null) {
yangzhenyud509bc92016-08-31 18:26:46 +0800720 filter.receiverList.app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800721 }
722 }
723 }
724 }
725
Svet Ganov9c165d72015-12-01 19:52:26 -0800726 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
727 BroadcastRecord receiverRecord, String receivingPackageName,
728 final int receivingUserId) {
729 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
730 receivingPackageName, receivingUserId)) {
731 return true;
732 }
733
734 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800735 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800736 : true;
737
738 // Show a permission review UI only for explicit broadcast from a foreground app
739 if (callerForeground && receiverRecord.intent.getComponent() != null) {
740 IIntentSender target = mService.getIntentSenderLocked(
741 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
742 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
743 new Intent[]{receiverRecord.intent},
744 new String[]{receiverRecord.intent.resolveType(mService.mContext
745 .getContentResolver())},
746 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
747 | PendingIntent.FLAG_IMMUTABLE, null);
748
749 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
750 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
751 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
752 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
753 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
754
755 if (DEBUG_PERMISSIONS_REVIEW) {
756 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
757 + receivingPackageName);
758 }
759
760 mHandler.post(new Runnable() {
761 @Override
762 public void run() {
763 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
764 }
765 });
766 } else {
767 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
768 + receivingPackageName + " requires a permissions review");
769 }
770
771 return false;
772 }
773
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700774 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700775 if (duration > Integer.MAX_VALUE) {
776 duration = Integer.MAX_VALUE;
777 }
778 // XXX ideally we should pause the broadcast until everything behind this is done,
779 // or else we will likely start dispatching the broadcast before we have opened
780 // access to the app (there is a lot of asynchronicity behind this). It is probably
781 // not that big a deal, however, because the main purpose here is to allow apps
782 // to hold wake locks, and they will be able to acquire their wake lock immediately
783 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700784 StringBuilder b = new StringBuilder();
785 b.append("broadcast:");
786 UserHandle.formatUid(b, r.callingUid);
787 b.append(":");
788 if (r.intent.getAction() != null) {
789 b.append(r.intent.getAction());
790 } else if (r.intent.getComponent() != null) {
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700791 r.intent.getComponent().appendShortString(b);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700792 } else if (r.intent.getData() != null) {
793 b.append(r.intent.getData());
794 }
Dianne Hackborne4d1a2e2017-04-14 17:57:33 -0700795 mService.tempWhitelistUidLocked(uid, duration, b.toString());
Dianne Hackborna750a632015-06-16 17:18:23 -0700796 }
797
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700798 /**
799 * Return true if all given permissions are signature-only perms.
800 */
801 final boolean isSignaturePerm(String[] perms) {
802 if (perms == null) {
803 return false;
804 }
805 IPackageManager pm = AppGlobals.getPackageManager();
806 for (int i = perms.length-1; i >= 0; i--) {
807 try {
Svetoslav Ganovadb8c522017-07-28 05:46:53 +0000808 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700809 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
810 | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
811 != PermissionInfo.PROTECTION_SIGNATURE) {
812 // If this a signature permission and NOT allowed for privileged apps, it
813 // is okay... otherwise, nope!
814 return false;
815 }
816 } catch (RemoteException e) {
817 return false;
818 }
819 }
820 return true;
821 }
822
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800823 final void processNextBroadcast(boolean fromMsg) {
824 synchronized(mService) {
825 BroadcastRecord r;
826
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800827 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800828 + mQueueName + "]: "
Carmen Jacksona68e3452017-01-17 14:01:33 -0800829 + mParallelBroadcasts.size() + " parallel broadcasts, "
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800830 + mOrderedBroadcasts.size() + " ordered broadcasts");
831
832 mService.updateCpuStats();
833
834 if (fromMsg) {
835 mBroadcastsScheduled = false;
836 }
837
838 // First, deliver any non-serialized broadcasts right away.
839 while (mParallelBroadcasts.size() > 0) {
840 r = mParallelBroadcasts.remove(0);
841 r.dispatchTime = SystemClock.uptimeMillis();
842 r.dispatchClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -0800843
844 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
845 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
846 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
847 System.identityHashCode(r));
848 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
849 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
850 System.identityHashCode(r));
851 }
852
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800853 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800854 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800855 + mQueueName + "] " + r);
856 for (int i=0; i<N; i++) {
857 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800858 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800859 "Delivering non-ordered on [" + mQueueName + "] to registered "
860 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800861 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800862 }
863 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800864 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800865 + mQueueName + "] " + r);
866 }
867
868 // Now take care of the next serialized one...
869
870 // If we are waiting for a process to come up to handle the next
871 // broadcast, then do nothing at this point. Just in case, we
872 // check that the process we're waiting for still exists.
873 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700874 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
875 "processNextBroadcast [" + mQueueName + "]: waiting for "
876 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800877
878 boolean isDead;
879 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700880 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
881 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800882 }
883 if (!isDead) {
884 // It's still alive, so keep waiting
885 return;
886 } else {
887 Slog.w(TAG, "pending app ["
888 + mQueueName + "]" + mPendingBroadcast.curApp
889 + " died before responding to broadcast");
890 mPendingBroadcast.state = BroadcastRecord.IDLE;
891 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
892 mPendingBroadcast = null;
893 }
894 }
895
896 boolean looped = false;
897
898 do {
899 if (mOrderedBroadcasts.size() == 0) {
900 // No more broadcasts pending, so all done!
901 mService.scheduleAppGcsLocked();
902 if (looped) {
903 // If we had finished the last ordered broadcast, then
904 // make sure all processes have correct oom and sched
905 // adjustments.
906 mService.updateOomAdjLocked();
907 }
908 return;
909 }
910 r = mOrderedBroadcasts.get(0);
911 boolean forceReceive = false;
912
913 // Ensure that even if something goes awry with the timeout
914 // detection, we catch "hung" broadcasts here, discard them,
915 // and continue to make progress.
916 //
917 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
918 // receivers don't get executed with timeouts. They're intended for
919 // one time heavy lifting after system upgrades and can take
920 // significant amounts of time.
921 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
922 if (mService.mProcessesReady && r.dispatchTime > 0) {
923 long now = SystemClock.uptimeMillis();
924 if ((numReceivers > 0) &&
925 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
926 Slog.w(TAG, "Hung broadcast ["
927 + mQueueName + "] discarded after timeout failure:"
928 + " now=" + now
929 + " dispatchTime=" + r.dispatchTime
930 + " startTime=" + r.receiverTime
931 + " intent=" + r.intent
932 + " numReceivers=" + numReceivers
933 + " nextReceiver=" + r.nextReceiver
934 + " state=" + r.state);
935 broadcastTimeoutLocked(false); // forcibly finish this broadcast
936 forceReceive = true;
937 r.state = BroadcastRecord.IDLE;
938 }
939 }
940
941 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800942 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800943 "processNextBroadcast("
944 + mQueueName + ") called when not idle (state="
945 + r.state + ")");
946 return;
947 }
948
949 if (r.receivers == null || r.nextReceiver >= numReceivers
950 || r.resultAbort || forceReceive) {
951 // No more receivers for this broadcast! Send the final
952 // result if requested...
953 if (r.resultTo != null) {
954 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800955 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800956 "Finishing broadcast [" + mQueueName + "] "
957 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800958 performReceiveLocked(r.callerApp, r.resultTo,
959 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700960 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800961 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700962 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800963 r.resultTo = null;
964 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000965 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800966 Slog.w(TAG, "Failure ["
967 + mQueueName + "] sending broadcast result of "
968 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700969
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800970 }
971 }
972
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800973 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800974 cancelBroadcastTimeoutLocked();
975
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700976 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
977 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800978
979 // ... and on to the next...
980 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700981 if (r.intent.getComponent() == null && r.intent.getPackage() == null
982 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
983 // This was an implicit broadcast... let's record it for posterity.
984 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
985 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
986 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800987 mOrderedBroadcasts.remove(0);
988 r = null;
989 looped = true;
990 continue;
991 }
992 } while (r == null);
993
994 // Get the next receiver...
995 int recIdx = r.nextReceiver++;
996
997 // Keep track of when this receiver started, and make sure there
998 // is a timeout message pending to kill it if need be.
999 r.receiverTime = SystemClock.uptimeMillis();
1000 if (recIdx == 0) {
1001 r.dispatchTime = r.receiverTime;
1002 r.dispatchClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -08001003 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1004 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1005 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1006 System.identityHashCode(r));
1007 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1008 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1009 System.identityHashCode(r));
1010 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001011 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001012 + mQueueName + "] " + r);
1013 }
1014 if (! mPendingBroadcastTimeoutMessage) {
1015 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001016 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001017 "Submitting BROADCAST_TIMEOUT_MSG ["
1018 + mQueueName + "] for " + r + " at " + timeoutTime);
1019 setBroadcastTimeoutLocked(timeoutTime);
1020 }
1021
Dianne Hackborna750a632015-06-16 17:18:23 -07001022 final BroadcastOptions brOptions = r.options;
1023 final Object nextReceiver = r.receivers.get(recIdx);
1024
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001025 if (nextReceiver instanceof BroadcastFilter) {
1026 // Simple case: this is a registered receiver who gets
1027 // a direct call.
1028 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001029 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001030 "Delivering ordered ["
1031 + mQueueName + "] to registered "
1032 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001033 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001034 if (r.receiver == null || !r.ordered) {
1035 // The receiver has already finished, so schedule to
1036 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001037 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001038 + mQueueName + "]: ordered="
1039 + r.ordered + " receiver=" + r.receiver);
1040 r.state = BroadcastRecord.IDLE;
1041 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -07001042 } else {
1043 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1044 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001045 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001046 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001047 }
1048 return;
1049 }
1050
1051 // Hard case: need to instantiate the receiver, possibly
1052 // starting its application process to host it.
1053
1054 ResolveInfo info =
1055 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001056 ComponentName component = new ComponentName(
1057 info.activityInfo.applicationInfo.packageName,
1058 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001059
1060 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001061 if (brOptions != null &&
1062 (info.activityInfo.applicationInfo.targetSdkVersion
1063 < brOptions.getMinManifestReceiverApiLevel() ||
1064 info.activityInfo.applicationInfo.targetSdkVersion
1065 > brOptions.getMaxManifestReceiverApiLevel())) {
1066 skip = true;
1067 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001068 int perm = mService.checkComponentPermission(info.activityInfo.permission,
1069 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1070 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001071 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001072 if (!info.activityInfo.exported) {
1073 Slog.w(TAG, "Permission Denial: broadcasting "
1074 + r.intent.toString()
1075 + " from " + r.callerPackage + " (pid=" + r.callingPid
1076 + ", uid=" + r.callingUid + ")"
1077 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001078 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001079 } else {
1080 Slog.w(TAG, "Permission Denial: broadcasting "
1081 + r.intent.toString()
1082 + " from " + r.callerPackage + " (pid=" + r.callingPid
1083 + ", uid=" + r.callingUid + ")"
1084 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001085 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001086 }
1087 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001088 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001089 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1090 if (opCode != AppOpsManager.OP_NONE
1091 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1092 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1093 Slog.w(TAG, "Appop Denial: broadcasting "
1094 + r.intent.toString()
1095 + " from " + r.callerPackage + " (pid="
1096 + r.callingPid + ", uid=" + r.callingUid + ")"
1097 + " requires appop " + AppOpsManager.permissionToOp(
1098 info.activityInfo.permission)
1099 + " due to registered receiver "
1100 + component.flattenToShortString());
1101 skip = true;
1102 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001103 }
Svet Ganov99b60432015-06-27 13:15:22 -07001104 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001105 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1106 for (int i = 0; i < r.requiredPermissions.length; i++) {
1107 String requiredPermission = r.requiredPermissions[i];
1108 try {
1109 perm = AppGlobals.getPackageManager().
1110 checkPermission(requiredPermission,
1111 info.activityInfo.applicationInfo.packageName,
1112 UserHandle
1113 .getUserId(info.activityInfo.applicationInfo.uid));
1114 } catch (RemoteException e) {
1115 perm = PackageManager.PERMISSION_DENIED;
1116 }
1117 if (perm != PackageManager.PERMISSION_GRANTED) {
1118 Slog.w(TAG, "Permission Denial: receiving "
1119 + r.intent + " to "
1120 + component.flattenToShortString()
1121 + " requires " + requiredPermission
1122 + " due to sender " + r.callerPackage
1123 + " (uid " + r.callingUid + ")");
1124 skip = true;
1125 break;
1126 }
1127 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1128 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1129 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001130 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001131 != AppOpsManager.MODE_ALLOWED) {
1132 Slog.w(TAG, "Appop Denial: receiving "
1133 + r.intent + " to "
1134 + component.flattenToShortString()
1135 + " requires appop " + AppOpsManager.permissionToOp(
1136 requiredPermission)
1137 + " due to sender " + r.callerPackage
1138 + " (uid " + r.callingUid + ")");
1139 skip = true;
1140 break;
1141 }
1142 }
1143 }
1144 if (!skip && r.appOp != AppOpsManager.OP_NONE
1145 && mService.mAppOpsService.noteOperation(r.appOp,
1146 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1147 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001148 Slog.w(TAG, "Appop Denial: receiving "
1149 + r.intent + " to "
1150 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001151 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001152 + " due to sender " + r.callerPackage
1153 + " (uid " + r.callingUid + ")");
1154 skip = true;
1155 }
Ben Gruver49660c72013-08-06 19:54:08 -07001156 if (!skip) {
1157 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1158 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1159 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001160 boolean isSingleton = false;
1161 try {
1162 isSingleton = mService.isSingleton(info.activityInfo.processName,
1163 info.activityInfo.applicationInfo,
1164 info.activityInfo.name, info.activityInfo.flags);
1165 } catch (SecurityException e) {
1166 Slog.w(TAG, e.getMessage());
1167 skip = true;
1168 }
1169 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1170 if (ActivityManager.checkUidPermission(
1171 android.Manifest.permission.INTERACT_ACROSS_USERS,
1172 info.activityInfo.applicationInfo.uid)
1173 != PackageManager.PERMISSION_GRANTED) {
1174 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1175 + " requests FLAG_SINGLE_USER, but app does not hold "
1176 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1177 skip = true;
1178 }
1179 }
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001180 if (!skip && info.activityInfo.applicationInfo.isInstantApp()
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001181 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1182 Slog.w(TAG, "Instant App Denial: receiving "
1183 + r.intent
1184 + " to " + component.flattenToShortString()
1185 + " due to sender " + r.callerPackage
1186 + " (uid " + r.callingUid + ")"
Chad Brubakerabd2b662017-03-16 11:24:16 -07001187 + " Instant Apps do not support manifest receivers");
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001188 skip = true;
1189 }
Chad Brubaker816c83b2017-03-02 10:27:59 -08001190 if (!skip && r.callerInstantApp
Todd Kennedyc05f5d12017-04-25 11:11:40 -07001191 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
Chad Brubaker816c83b2017-03-02 10:27:59 -08001192 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1193 Slog.w(TAG, "Instant App Denial: receiving "
1194 + r.intent
1195 + " to " + component.flattenToShortString()
1196 + " requires receiver have visibleToInstantApps set"
1197 + " due to sender " + r.callerPackage
1198 + " (uid " + r.callingUid + ")");
1199 skip = true;
1200 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001201 if (r.curApp != null && r.curApp.crashing) {
1202 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001203 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1204 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001205 skip = true;
1206 }
Christopher Tateba629da2013-11-13 17:42:28 -08001207 if (!skip) {
1208 boolean isAvailable = false;
1209 try {
1210 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1211 info.activityInfo.packageName,
1212 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1213 } catch (Exception e) {
1214 // all such failures mean we skip this receiver
1215 Slog.w(TAG, "Exception getting recipient info for "
1216 + info.activityInfo.packageName, e);
1217 }
1218 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001219 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1220 "Skipping delivery to " + info.activityInfo.packageName + " / "
1221 + info.activityInfo.applicationInfo.uid
1222 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001223 skip = true;
1224 }
1225 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001226
Svet Ganov9c165d72015-12-01 19:52:26 -08001227 // If permissions need a review before any of the app components can run, we drop
1228 // the broadcast and if the calling app is in the foreground and the broadcast is
1229 // explicit we launch the review UI passing it a pending intent to send the skipped
1230 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -07001231 if (mService.mPermissionReviewRequired && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001232 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1233 info.activityInfo.packageName, UserHandle.getUserId(
1234 info.activityInfo.applicationInfo.uid))) {
1235 skip = true;
1236 }
1237 }
1238
Dianne Hackborn76e80092015-12-09 14:15:34 -08001239 // This is safe to do even if we are skipping the broadcast, and we need
1240 // this information now to evaluate whether it is going to be allowed to run.
1241 final int receiverUid = info.activityInfo.applicationInfo.uid;
1242 // If it's a singleton, it needs to be the same app or a special app
1243 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1244 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1245 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1246 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001247 String targetProcess = info.activityInfo.processName;
1248 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1249 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001250
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001251 if (!skip) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001252 final int allowed = mService.getAppStartModeLocked(
1253 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1254 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001255 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1256 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001257 // completely disabled from launches, or it was not explicitly sent
1258 // to it and the app is in a state that should not receive it
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001259 // (depending on how getAppStartModeLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001260 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1261 Slog.w(TAG, "Background execution disabled: receiving "
1262 + r.intent + " to "
1263 + component.flattenToShortString());
1264 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001265 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001266 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001267 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001268 && ((r.intent.getFlags()
Dianne Hackbornb8633f32017-04-11 17:38:42 -07001269 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1270 && !isSignaturePerm(r.requiredPermissions))) {
Dianne Hackborn7fc46d82017-02-14 15:20:06 -08001271 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1272 component.getPackageName());
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001273 Slog.w(TAG, "Background execution not allowed: receiving "
1274 + r.intent + " to "
1275 + component.flattenToShortString());
1276 skip = true;
1277 }
1278 }
1279 }
1280
Fyodor Kupolov099ae882017-10-23 11:23:51 -07001281 if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1282 && !mService.mUserController
1283 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1284 0 /* flags */)) {
1285 skip = true;
1286 Slog.w(TAG,
1287 "Skipping delivery to " + info.activityInfo.packageName + " / "
1288 + info.activityInfo.applicationInfo.uid + " : user is not running");
1289 }
1290
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001291 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001292 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001293 "Skipping delivery of ordered [" + mQueueName + "] "
1294 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001295 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001296 r.receiver = null;
1297 r.curFilter = null;
1298 r.state = BroadcastRecord.IDLE;
Fyodor Kupolov099ae882017-10-23 11:23:51 -07001299 r.manifestSkipCount++;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001300 scheduleBroadcastsLocked();
1301 return;
1302 }
Fyodor Kupolov099ae882017-10-23 11:23:51 -07001303 r.manifestCount++;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001304
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001305 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001306 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001307 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001308 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001309 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001310 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1311 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
Fyodor Kupolov099ae882017-10-23 11:23:51 -07001312 + receiverUid);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001313 }
1314
Dianne Hackborna750a632015-06-16 17:18:23 -07001315 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1316 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001317 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001318 }
1319
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001320 // Broadcast is being executed, its package can't be stopped.
1321 try {
1322 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001323 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001324 } catch (RemoteException e) {
1325 } catch (IllegalArgumentException e) {
1326 Slog.w(TAG, "Failed trying to unstop package "
1327 + r.curComponent.getPackageName() + ": " + e);
1328 }
1329
1330 // Is this receiver's application already running?
Dianne Hackborn443d35a2017-06-16 17:59:35 -07001331 if (app != null && app.thread != null && !app.killed) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001332 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001333 app.addPackage(info.activityInfo.packageName,
1334 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001335 processCurBroadcastLocked(r, app);
1336 return;
1337 } catch (RemoteException e) {
1338 Slog.w(TAG, "Exception when sending broadcast to "
1339 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001340 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001341 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001342 + r.curComponent + " with " + r.intent, e);
1343 // If some unexpected exception happened, just skip
1344 // this broadcast. At this point we are not in the call
1345 // from a client, so throwing an exception out from here
1346 // will crash the entire system instead of just whoever
1347 // sent the broadcast.
1348 logBroadcastReceiverDiscardLocked(r);
1349 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001350 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001351 scheduleBroadcastsLocked();
1352 // We need to reset the state if we failed to start the receiver.
1353 r.state = BroadcastRecord.IDLE;
1354 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001355 }
1356
1357 // If a dead object exception was thrown -- fall through to
1358 // restart the application.
1359 }
1360
1361 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001362 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001363 "Need to start app ["
1364 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1365 if ((r.curApp=mService.startProcessLocked(targetProcess,
1366 info.activityInfo.applicationInfo, true,
1367 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1368 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001369 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001370 == null) {
1371 // Ah, this recipient is unavailable. Finish it if necessary,
1372 // and mark the broadcast record as ready for the next.
1373 Slog.w(TAG, "Unable to launch app "
1374 + info.activityInfo.applicationInfo.packageName + "/"
Fyodor Kupolov099ae882017-10-23 11:23:51 -07001375 + receiverUid + " for broadcast "
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001376 + r.intent + ": process is bad");
1377 logBroadcastReceiverDiscardLocked(r);
1378 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001379 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001380 scheduleBroadcastsLocked();
1381 r.state = BroadcastRecord.IDLE;
1382 return;
1383 }
1384
1385 mPendingBroadcast = r;
1386 mPendingBroadcastRecvIndex = recIdx;
1387 }
1388 }
1389
1390 final void setBroadcastTimeoutLocked(long timeoutTime) {
1391 if (! mPendingBroadcastTimeoutMessage) {
1392 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1393 mHandler.sendMessageAtTime(msg, timeoutTime);
1394 mPendingBroadcastTimeoutMessage = true;
1395 }
1396 }
1397
1398 final void cancelBroadcastTimeoutLocked() {
1399 if (mPendingBroadcastTimeoutMessage) {
1400 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1401 mPendingBroadcastTimeoutMessage = false;
1402 }
1403 }
1404
1405 final void broadcastTimeoutLocked(boolean fromMsg) {
1406 if (fromMsg) {
1407 mPendingBroadcastTimeoutMessage = false;
1408 }
1409
1410 if (mOrderedBroadcasts.size() == 0) {
1411 return;
1412 }
1413
1414 long now = SystemClock.uptimeMillis();
1415 BroadcastRecord r = mOrderedBroadcasts.get(0);
1416 if (fromMsg) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001417 if (!mService.mProcessesReady) {
1418 // Only process broadcast timeouts if the system is ready. That way
1419 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1420 // to do heavy lifting for system up.
1421 return;
1422 }
1423
1424 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1425 if (timeoutTime > now) {
1426 // We can observe premature timeouts because we do not cancel and reset the
1427 // broadcast timeout message after each receiver finishes. Instead, we set up
1428 // an initial timeout then kick it down the road a little further as needed
1429 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001430 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001431 "Premature timeout ["
1432 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1433 + timeoutTime);
1434 setBroadcastTimeoutLocked(timeoutTime);
1435 return;
1436 }
1437 }
1438
Dianne Hackborn6285a322013-09-18 12:09:47 -07001439 BroadcastRecord br = mOrderedBroadcasts.get(0);
1440 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1441 // In this case the broadcast had already finished, but we had decided to wait
1442 // for started services to finish as well before going on. So if we have actually
1443 // waited long enough time timeout the broadcast, let's give up on the whole thing
1444 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001445 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001446 ? br.curComponent.flattenToShortString() : "(null)"));
1447 br.curComponent = null;
1448 br.state = BroadcastRecord.IDLE;
1449 processNextBroadcast(false);
1450 return;
1451 }
1452
1453 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001454 + ", started " + (now - r.receiverTime) + "ms ago");
1455 r.receiverTime = now;
1456 r.anrCount++;
1457
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001458 ProcessRecord app = null;
1459 String anrMessage = null;
1460
Christopher Tatea6b2c882017-09-01 11:41:39 -07001461 Object curReceiver;
1462 if (r.nextReceiver > 0) {
1463 curReceiver = r.receivers.get(r.nextReceiver-1);
1464 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1465 } else {
1466 curReceiver = r.curReceiver;
1467 }
1468 Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001469 logBroadcastReceiverDiscardLocked(r);
Christopher Tatea6b2c882017-09-01 11:41:39 -07001470 if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001471 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1472 if (bf.receiverList.pid != 0
1473 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1474 synchronized (mService.mPidsSelfLocked) {
1475 app = mService.mPidsSelfLocked.get(
1476 bf.receiverList.pid);
1477 }
1478 }
1479 } else {
1480 app = r.curApp;
1481 }
1482
1483 if (app != null) {
1484 anrMessage = "Broadcast of " + r.intent.toString();
1485 }
1486
1487 if (mPendingBroadcast == r) {
1488 mPendingBroadcast = null;
1489 }
1490
1491 // Move on to the next receiver.
1492 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001493 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001494 scheduleBroadcastsLocked();
1495
1496 if (anrMessage != null) {
1497 // Post the ANR to the handler since we do not want to process ANRs while
1498 // potentially holding our lock.
1499 mHandler.post(new AppNotResponding(app, anrMessage));
1500 }
1501 }
1502
Christopher Tatef278f122015-04-22 13:12:01 -07001503 private final int ringAdvance(int x, final int increment, final int ringSize) {
1504 x += increment;
1505 if (x < 0) return (ringSize - 1);
1506 else if (x >= ringSize) return 0;
1507 else return x;
1508 }
1509
Makoto Onuki97f82f22017-05-31 16:20:21 -07001510 private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1511 if (original.callingUid < 0) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001512 // This was from a registerReceiver() call; ignore it.
1513 return;
1514 }
Makoto Onuki97f82f22017-05-31 16:20:21 -07001515 original.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001516
Carmen Jacksona68e3452017-01-17 14:01:33 -08001517 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1518 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Makoto Onuki97f82f22017-05-31 16:20:21 -07001519 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1520 System.identityHashCode(original));
Carmen Jacksona68e3452017-01-17 14:01:33 -08001521 }
1522
Makoto Onuki97f82f22017-05-31 16:20:21 -07001523 // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1524 // So don't change the incoming record directly.
1525 final BroadcastRecord historyRecord = original.maybeStripForHistory();
1526
1527 mBroadcastHistory[mHistoryNext] = historyRecord;
Christopher Tatef278f122015-04-22 13:12:01 -07001528 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1529
Makoto Onuki97f82f22017-05-31 16:20:21 -07001530 mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1531 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1532 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
Christopher Tatef278f122015-04-22 13:12:01 -07001533 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1534 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001535 }
1536
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001537 boolean cleanupDisabledPackageReceiversLocked(
1538 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1539 boolean didSomething = false;
1540 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1541 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1542 packageName, filterByClasses, userId, doit);
1543 if (!doit && didSomething) {
1544 return true;
1545 }
1546 }
1547
1548 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1549 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1550 packageName, filterByClasses, userId, doit);
1551 if (!doit && didSomething) {
1552 return true;
1553 }
1554 }
1555
1556 return didSomething;
1557 }
1558
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001559 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001560 final int logIndex = r.nextReceiver - 1;
1561 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1562 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001563 if (curReceiver instanceof BroadcastFilter) {
1564 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1565 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001566 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001567 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001568 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001569 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001570 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001571 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001572 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001573 }
1574 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001575 if (logIndex < 0) Slog.w(TAG,
1576 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001577 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001578 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001579 r.intent.getAction(),
1580 r.nextReceiver,
1581 "NONE");
1582 }
1583 }
1584
Carmen Jacksona68e3452017-01-17 14:01:33 -08001585 private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1586 return String.format("Broadcast %s from %s (%s) %s",
1587 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1588 record.callerPackage == null ? "" : record.callerPackage,
1589 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1590 record.intent == null ? "" : record.intent.getAction());
1591 }
1592
Jeff Sharkeyfd658132017-05-03 11:38:01 -06001593 final boolean isIdle() {
1594 return mParallelBroadcasts.isEmpty() && mOrderedBroadcasts.isEmpty()
1595 && (mPendingBroadcast == null);
1596 }
1597
Yi Jin129fc6c2017-09-28 15:48:38 -07001598 void writeToProto(ProtoOutputStream proto, long fieldId) {
1599 long token = proto.start(fieldId);
1600 proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1601 int N;
1602 N = mParallelBroadcasts.size();
1603 for (int i = N - 1; i >= 0; i--) {
1604 mParallelBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1605 }
1606 N = mOrderedBroadcasts.size();
1607 for (int i = N - 1; i >= 0; i--) {
1608 mOrderedBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1609 }
1610 if (mPendingBroadcast != null) {
1611 mPendingBroadcast.writeToProto(proto, BroadcastQueueProto.PENDING_BROADCAST);
1612 }
1613
1614 int lastIndex = mHistoryNext;
1615 int ringIndex = lastIndex;
1616 do {
1617 // increasing index = more recent entry, and we want to print the most
1618 // recent first and work backwards, so we roll through the ring backwards.
1619 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1620 BroadcastRecord r = mBroadcastHistory[ringIndex];
1621 if (r != null) {
1622 r.writeToProto(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1623 }
1624 } while (ringIndex != lastIndex);
1625
1626 lastIndex = ringIndex = mSummaryHistoryNext;
1627 do {
1628 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1629 Intent intent = mBroadcastSummaryHistory[ringIndex];
1630 if (intent == null) {
1631 continue;
1632 }
1633 long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1634 intent.writeToProto(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1635 false, true, true, false);
1636 proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1637 mSummaryHistoryEnqueueTime[ringIndex]);
1638 proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1639 mSummaryHistoryDispatchTime[ringIndex]);
1640 proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1641 mSummaryHistoryFinishTime[ringIndex]);
1642 proto.end(summaryToken);
1643 } while (ringIndex != lastIndex);
1644 proto.end(token);
1645 }
1646
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001647 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1648 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001649 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001650 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1651 || mPendingBroadcast != null) {
1652 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001653 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001654 BroadcastRecord br = mParallelBroadcasts.get(i);
1655 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1656 continue;
1657 }
1658 if (!printed) {
1659 if (needSep) {
1660 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001661 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001662 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001663 printed = true;
1664 pw.println(" Active broadcasts [" + mQueueName + "]:");
1665 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001666 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001667 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001668 }
1669 printed = false;
1670 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001671 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001672 BroadcastRecord br = mOrderedBroadcasts.get(i);
1673 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1674 continue;
1675 }
1676 if (!printed) {
1677 if (needSep) {
1678 pw.println();
1679 }
1680 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001681 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001682 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1683 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001684 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001685 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001686 }
1687 if (dumpPackage == null || (mPendingBroadcast != null
1688 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1689 if (needSep) {
1690 pw.println();
1691 }
1692 pw.println(" Pending broadcast [" + mQueueName + "]:");
1693 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001694 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001695 } else {
1696 pw.println(" (null)");
1697 }
1698 needSep = true;
1699 }
1700 }
1701
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001702 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001703 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001704
1705 i = -1;
1706 int lastIndex = mHistoryNext;
1707 int ringIndex = lastIndex;
1708 do {
1709 // increasing index = more recent entry, and we want to print the most
1710 // recent first and work backwards, so we roll through the ring backwards.
1711 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1712 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001713 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001714 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001715 }
Christopher Tatef278f122015-04-22 13:12:01 -07001716
1717 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001718 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1719 continue;
1720 }
1721 if (!printed) {
1722 if (needSep) {
1723 pw.println();
1724 }
1725 needSep = true;
1726 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1727 printed = true;
1728 }
1729 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001730 pw.print(" Historical Broadcast " + mQueueName + " #");
1731 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001732 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001733 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001734 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1735 pw.print(" ");
1736 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001737 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1738 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1739 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001740 Bundle bundle = r.intent.getExtras();
1741 if (bundle != null) {
1742 pw.print(" extras: "); pw.println(bundle.toString());
1743 }
1744 }
Christopher Tatef278f122015-04-22 13:12:01 -07001745 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001746
1747 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001748 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001749 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001750 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001751 i = -1;
1752 } else {
1753 // roll over the 'i' full dumps that have already been issued
1754 for (int j = i;
1755 j > 0 && ringIndex != lastIndex;) {
1756 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1757 BroadcastRecord r = mBroadcastHistory[ringIndex];
1758 if (r == null) {
1759 continue;
1760 }
1761 j--;
1762 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001763 }
Christopher Tatef278f122015-04-22 13:12:01 -07001764 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1765 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001766 do {
1767 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1768 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001769 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001770 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001771 }
1772 if (!printed) {
1773 if (needSep) {
1774 pw.println();
1775 }
1776 needSep = true;
1777 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1778 printed = true;
1779 }
1780 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001781 pw.println(" ...");
1782 break;
1783 }
Christopher Tatef278f122015-04-22 13:12:01 -07001784 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001785 pw.print(" #"); pw.print(i); pw.print(": ");
1786 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001787 pw.print(" ");
1788 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1789 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1790 pw.print(" dispatch ");
1791 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1792 - mSummaryHistoryDispatchTime[ringIndex], pw);
1793 pw.println(" finish");
1794 pw.print(" enq=");
1795 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1796 pw.print(" disp=");
1797 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1798 pw.print(" fin=");
1799 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001800 Bundle bundle = intent.getExtras();
1801 if (bundle != null) {
1802 pw.print(" extras: "); pw.println(bundle.toString());
1803 }
Christopher Tatef278f122015-04-22 13:12:01 -07001804 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001805 }
1806
1807 return needSep;
1808 }
1809}