blob: c62cc38b716fe3d8d071d146d6194b417c07b56a [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 Hackbornbc02a392016-06-02 17:15:08 -07001201 if (!skip) {
1202 r.manifestCount++;
1203 } else {
1204 r.manifestSkipCount++;
1205 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001206 if (r.curApp != null && r.curApp.crashing) {
1207 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001208 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1209 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001210 skip = true;
1211 }
Christopher Tateba629da2013-11-13 17:42:28 -08001212 if (!skip) {
1213 boolean isAvailable = false;
1214 try {
1215 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1216 info.activityInfo.packageName,
1217 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1218 } catch (Exception e) {
1219 // all such failures mean we skip this receiver
1220 Slog.w(TAG, "Exception getting recipient info for "
1221 + info.activityInfo.packageName, e);
1222 }
1223 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001224 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1225 "Skipping delivery to " + info.activityInfo.packageName + " / "
1226 + info.activityInfo.applicationInfo.uid
1227 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001228 skip = true;
1229 }
1230 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001231
Svet Ganov9c165d72015-12-01 19:52:26 -08001232 // If permissions need a review before any of the app components can run, we drop
1233 // the broadcast and if the calling app is in the foreground and the broadcast is
1234 // explicit we launch the review UI passing it a pending intent to send the skipped
1235 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -07001236 if (mService.mPermissionReviewRequired && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001237 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1238 info.activityInfo.packageName, UserHandle.getUserId(
1239 info.activityInfo.applicationInfo.uid))) {
1240 skip = true;
1241 }
1242 }
1243
Dianne Hackborn76e80092015-12-09 14:15:34 -08001244 // This is safe to do even if we are skipping the broadcast, and we need
1245 // this information now to evaluate whether it is going to be allowed to run.
1246 final int receiverUid = info.activityInfo.applicationInfo.uid;
1247 // If it's a singleton, it needs to be the same app or a special app
1248 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1249 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1250 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1251 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001252 String targetProcess = info.activityInfo.processName;
1253 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1254 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001255
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001256 if (!skip) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001257 final int allowed = mService.getAppStartModeLocked(
1258 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1259 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001260 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1261 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001262 // completely disabled from launches, or it was not explicitly sent
1263 // to it and the app is in a state that should not receive it
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001264 // (depending on how getAppStartModeLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001265 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1266 Slog.w(TAG, "Background execution disabled: receiving "
1267 + r.intent + " to "
1268 + component.flattenToShortString());
1269 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001270 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001271 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001272 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001273 && ((r.intent.getFlags()
Dianne Hackbornb8633f32017-04-11 17:38:42 -07001274 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1275 && !isSignaturePerm(r.requiredPermissions))) {
Dianne Hackborn7fc46d82017-02-14 15:20:06 -08001276 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1277 component.getPackageName());
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001278 Slog.w(TAG, "Background execution not allowed: receiving "
1279 + r.intent + " to "
1280 + component.flattenToShortString());
1281 skip = true;
1282 }
1283 }
1284 }
1285
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001286 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001287 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001288 "Skipping delivery of ordered [" + mQueueName + "] "
1289 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001290 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001291 r.receiver = null;
1292 r.curFilter = null;
1293 r.state = BroadcastRecord.IDLE;
1294 scheduleBroadcastsLocked();
1295 return;
1296 }
1297
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001298 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001299 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001300 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001301 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001302 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001303 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1304 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1305 + info.activityInfo.applicationInfo.uid);
1306 }
1307
Dianne Hackborna750a632015-06-16 17:18:23 -07001308 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1309 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001310 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001311 }
1312
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001313 // Broadcast is being executed, its package can't be stopped.
1314 try {
1315 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001316 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001317 } catch (RemoteException e) {
1318 } catch (IllegalArgumentException e) {
1319 Slog.w(TAG, "Failed trying to unstop package "
1320 + r.curComponent.getPackageName() + ": " + e);
1321 }
1322
1323 // Is this receiver's application already running?
Dianne Hackborn443d35a2017-06-16 17:59:35 -07001324 if (app != null && app.thread != null && !app.killed) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001325 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001326 app.addPackage(info.activityInfo.packageName,
1327 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001328 processCurBroadcastLocked(r, app);
1329 return;
1330 } catch (RemoteException e) {
1331 Slog.w(TAG, "Exception when sending broadcast to "
1332 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001333 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001334 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001335 + r.curComponent + " with " + r.intent, e);
1336 // If some unexpected exception happened, just skip
1337 // this broadcast. At this point we are not in the call
1338 // from a client, so throwing an exception out from here
1339 // will crash the entire system instead of just whoever
1340 // sent the broadcast.
1341 logBroadcastReceiverDiscardLocked(r);
1342 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001343 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001344 scheduleBroadcastsLocked();
1345 // We need to reset the state if we failed to start the receiver.
1346 r.state = BroadcastRecord.IDLE;
1347 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001348 }
1349
1350 // If a dead object exception was thrown -- fall through to
1351 // restart the application.
1352 }
1353
1354 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001355 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001356 "Need to start app ["
1357 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1358 if ((r.curApp=mService.startProcessLocked(targetProcess,
1359 info.activityInfo.applicationInfo, true,
1360 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1361 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001362 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001363 == null) {
1364 // Ah, this recipient is unavailable. Finish it if necessary,
1365 // and mark the broadcast record as ready for the next.
1366 Slog.w(TAG, "Unable to launch app "
1367 + info.activityInfo.applicationInfo.packageName + "/"
1368 + info.activityInfo.applicationInfo.uid + " for broadcast "
1369 + r.intent + ": process is bad");
1370 logBroadcastReceiverDiscardLocked(r);
1371 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001372 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001373 scheduleBroadcastsLocked();
1374 r.state = BroadcastRecord.IDLE;
1375 return;
1376 }
1377
1378 mPendingBroadcast = r;
1379 mPendingBroadcastRecvIndex = recIdx;
1380 }
1381 }
1382
1383 final void setBroadcastTimeoutLocked(long timeoutTime) {
1384 if (! mPendingBroadcastTimeoutMessage) {
1385 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1386 mHandler.sendMessageAtTime(msg, timeoutTime);
1387 mPendingBroadcastTimeoutMessage = true;
1388 }
1389 }
1390
1391 final void cancelBroadcastTimeoutLocked() {
1392 if (mPendingBroadcastTimeoutMessage) {
1393 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1394 mPendingBroadcastTimeoutMessage = false;
1395 }
1396 }
1397
1398 final void broadcastTimeoutLocked(boolean fromMsg) {
1399 if (fromMsg) {
1400 mPendingBroadcastTimeoutMessage = false;
1401 }
1402
1403 if (mOrderedBroadcasts.size() == 0) {
1404 return;
1405 }
1406
1407 long now = SystemClock.uptimeMillis();
1408 BroadcastRecord r = mOrderedBroadcasts.get(0);
1409 if (fromMsg) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001410 if (!mService.mProcessesReady) {
1411 // Only process broadcast timeouts if the system is ready. That way
1412 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1413 // to do heavy lifting for system up.
1414 return;
1415 }
1416
1417 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1418 if (timeoutTime > now) {
1419 // We can observe premature timeouts because we do not cancel and reset the
1420 // broadcast timeout message after each receiver finishes. Instead, we set up
1421 // an initial timeout then kick it down the road a little further as needed
1422 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001423 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001424 "Premature timeout ["
1425 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1426 + timeoutTime);
1427 setBroadcastTimeoutLocked(timeoutTime);
1428 return;
1429 }
1430 }
1431
Dianne Hackborn6285a322013-09-18 12:09:47 -07001432 BroadcastRecord br = mOrderedBroadcasts.get(0);
1433 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1434 // In this case the broadcast had already finished, but we had decided to wait
1435 // for started services to finish as well before going on. So if we have actually
1436 // waited long enough time timeout the broadcast, let's give up on the whole thing
1437 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001438 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001439 ? br.curComponent.flattenToShortString() : "(null)"));
1440 br.curComponent = null;
1441 br.state = BroadcastRecord.IDLE;
1442 processNextBroadcast(false);
1443 return;
1444 }
1445
1446 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001447 + ", started " + (now - r.receiverTime) + "ms ago");
1448 r.receiverTime = now;
1449 r.anrCount++;
1450
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001451 ProcessRecord app = null;
1452 String anrMessage = null;
1453
Christopher Tatea6b2c882017-09-01 11:41:39 -07001454 Object curReceiver;
1455 if (r.nextReceiver > 0) {
1456 curReceiver = r.receivers.get(r.nextReceiver-1);
1457 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1458 } else {
1459 curReceiver = r.curReceiver;
1460 }
1461 Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001462 logBroadcastReceiverDiscardLocked(r);
Christopher Tatea6b2c882017-09-01 11:41:39 -07001463 if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001464 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1465 if (bf.receiverList.pid != 0
1466 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1467 synchronized (mService.mPidsSelfLocked) {
1468 app = mService.mPidsSelfLocked.get(
1469 bf.receiverList.pid);
1470 }
1471 }
1472 } else {
1473 app = r.curApp;
1474 }
1475
1476 if (app != null) {
1477 anrMessage = "Broadcast of " + r.intent.toString();
1478 }
1479
1480 if (mPendingBroadcast == r) {
1481 mPendingBroadcast = null;
1482 }
1483
1484 // Move on to the next receiver.
1485 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001486 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 scheduleBroadcastsLocked();
1488
1489 if (anrMessage != null) {
1490 // Post the ANR to the handler since we do not want to process ANRs while
1491 // potentially holding our lock.
1492 mHandler.post(new AppNotResponding(app, anrMessage));
1493 }
1494 }
1495
Christopher Tatef278f122015-04-22 13:12:01 -07001496 private final int ringAdvance(int x, final int increment, final int ringSize) {
1497 x += increment;
1498 if (x < 0) return (ringSize - 1);
1499 else if (x >= ringSize) return 0;
1500 else return x;
1501 }
1502
Makoto Onuki97f82f22017-05-31 16:20:21 -07001503 private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1504 if (original.callingUid < 0) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001505 // This was from a registerReceiver() call; ignore it.
1506 return;
1507 }
Makoto Onuki97f82f22017-05-31 16:20:21 -07001508 original.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001509
Carmen Jacksona68e3452017-01-17 14:01:33 -08001510 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1511 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
Makoto Onuki97f82f22017-05-31 16:20:21 -07001512 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1513 System.identityHashCode(original));
Carmen Jacksona68e3452017-01-17 14:01:33 -08001514 }
1515
Makoto Onuki97f82f22017-05-31 16:20:21 -07001516 // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1517 // So don't change the incoming record directly.
1518 final BroadcastRecord historyRecord = original.maybeStripForHistory();
1519
1520 mBroadcastHistory[mHistoryNext] = historyRecord;
Christopher Tatef278f122015-04-22 13:12:01 -07001521 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1522
Makoto Onuki97f82f22017-05-31 16:20:21 -07001523 mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1524 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1525 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
Christopher Tatef278f122015-04-22 13:12:01 -07001526 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1527 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001528 }
1529
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001530 boolean cleanupDisabledPackageReceiversLocked(
1531 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1532 boolean didSomething = false;
1533 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1534 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1535 packageName, filterByClasses, userId, doit);
1536 if (!doit && didSomething) {
1537 return true;
1538 }
1539 }
1540
1541 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1542 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1543 packageName, filterByClasses, userId, doit);
1544 if (!doit && didSomething) {
1545 return true;
1546 }
1547 }
1548
1549 return didSomething;
1550 }
1551
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001552 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001553 final int logIndex = r.nextReceiver - 1;
1554 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1555 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001556 if (curReceiver instanceof BroadcastFilter) {
1557 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1558 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001559 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001560 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001561 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001562 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001563 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001564 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001565 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001566 }
1567 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001568 if (logIndex < 0) Slog.w(TAG,
1569 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001570 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001571 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001572 r.intent.getAction(),
1573 r.nextReceiver,
1574 "NONE");
1575 }
1576 }
1577
Carmen Jacksona68e3452017-01-17 14:01:33 -08001578 private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1579 return String.format("Broadcast %s from %s (%s) %s",
1580 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1581 record.callerPackage == null ? "" : record.callerPackage,
1582 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1583 record.intent == null ? "" : record.intent.getAction());
1584 }
1585
Jeff Sharkeyfd658132017-05-03 11:38:01 -06001586 final boolean isIdle() {
1587 return mParallelBroadcasts.isEmpty() && mOrderedBroadcasts.isEmpty()
1588 && (mPendingBroadcast == null);
1589 }
1590
Yi Jin129fc6c2017-09-28 15:48:38 -07001591 void writeToProto(ProtoOutputStream proto, long fieldId) {
1592 long token = proto.start(fieldId);
1593 proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1594 int N;
1595 N = mParallelBroadcasts.size();
1596 for (int i = N - 1; i >= 0; i--) {
1597 mParallelBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1598 }
1599 N = mOrderedBroadcasts.size();
1600 for (int i = N - 1; i >= 0; i--) {
1601 mOrderedBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1602 }
1603 if (mPendingBroadcast != null) {
1604 mPendingBroadcast.writeToProto(proto, BroadcastQueueProto.PENDING_BROADCAST);
1605 }
1606
1607 int lastIndex = mHistoryNext;
1608 int ringIndex = lastIndex;
1609 do {
1610 // increasing index = more recent entry, and we want to print the most
1611 // recent first and work backwards, so we roll through the ring backwards.
1612 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1613 BroadcastRecord r = mBroadcastHistory[ringIndex];
1614 if (r != null) {
1615 r.writeToProto(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1616 }
1617 } while (ringIndex != lastIndex);
1618
1619 lastIndex = ringIndex = mSummaryHistoryNext;
1620 do {
1621 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1622 Intent intent = mBroadcastSummaryHistory[ringIndex];
1623 if (intent == null) {
1624 continue;
1625 }
1626 long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1627 intent.writeToProto(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1628 false, true, true, false);
1629 proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1630 mSummaryHistoryEnqueueTime[ringIndex]);
1631 proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1632 mSummaryHistoryDispatchTime[ringIndex]);
1633 proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1634 mSummaryHistoryFinishTime[ringIndex]);
1635 proto.end(summaryToken);
1636 } while (ringIndex != lastIndex);
1637 proto.end(token);
1638 }
1639
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001640 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1641 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001642 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001643 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1644 || mPendingBroadcast != null) {
1645 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001646 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001647 BroadcastRecord br = mParallelBroadcasts.get(i);
1648 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1649 continue;
1650 }
1651 if (!printed) {
1652 if (needSep) {
1653 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001654 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001655 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001656 printed = true;
1657 pw.println(" Active broadcasts [" + mQueueName + "]:");
1658 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001659 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001660 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001661 }
1662 printed = false;
1663 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001664 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001665 BroadcastRecord br = mOrderedBroadcasts.get(i);
1666 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1667 continue;
1668 }
1669 if (!printed) {
1670 if (needSep) {
1671 pw.println();
1672 }
1673 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001674 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001675 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1676 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001677 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001678 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001679 }
1680 if (dumpPackage == null || (mPendingBroadcast != null
1681 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1682 if (needSep) {
1683 pw.println();
1684 }
1685 pw.println(" Pending broadcast [" + mQueueName + "]:");
1686 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001687 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001688 } else {
1689 pw.println(" (null)");
1690 }
1691 needSep = true;
1692 }
1693 }
1694
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001695 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001696 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001697
1698 i = -1;
1699 int lastIndex = mHistoryNext;
1700 int ringIndex = lastIndex;
1701 do {
1702 // increasing index = more recent entry, and we want to print the most
1703 // recent first and work backwards, so we roll through the ring backwards.
1704 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1705 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001706 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001707 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001708 }
Christopher Tatef278f122015-04-22 13:12:01 -07001709
1710 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001711 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1712 continue;
1713 }
1714 if (!printed) {
1715 if (needSep) {
1716 pw.println();
1717 }
1718 needSep = true;
1719 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1720 printed = true;
1721 }
1722 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001723 pw.print(" Historical Broadcast " + mQueueName + " #");
1724 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001725 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001726 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001727 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1728 pw.print(" ");
1729 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001730 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1731 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1732 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001733 Bundle bundle = r.intent.getExtras();
1734 if (bundle != null) {
1735 pw.print(" extras: "); pw.println(bundle.toString());
1736 }
1737 }
Christopher Tatef278f122015-04-22 13:12:01 -07001738 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001739
1740 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001741 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001742 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001743 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001744 i = -1;
1745 } else {
1746 // roll over the 'i' full dumps that have already been issued
1747 for (int j = i;
1748 j > 0 && ringIndex != lastIndex;) {
1749 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1750 BroadcastRecord r = mBroadcastHistory[ringIndex];
1751 if (r == null) {
1752 continue;
1753 }
1754 j--;
1755 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001756 }
Christopher Tatef278f122015-04-22 13:12:01 -07001757 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1758 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001759 do {
1760 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1761 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001762 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001763 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001764 }
1765 if (!printed) {
1766 if (needSep) {
1767 pw.println();
1768 }
1769 needSep = true;
1770 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1771 printed = true;
1772 }
1773 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001774 pw.println(" ...");
1775 break;
1776 }
Christopher Tatef278f122015-04-22 13:12:01 -07001777 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001778 pw.print(" #"); pw.print(i); pw.print(": ");
1779 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001780 pw.print(" ");
1781 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1782 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1783 pw.print(" dispatch ");
1784 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1785 - mSummaryHistoryDispatchTime[ringIndex], pw);
1786 pw.println(" finish");
1787 pw.print(" enq=");
1788 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1789 pw.print(" disp=");
1790 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1791 pw.print(" fin=");
1792 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001793 Bundle bundle = intent.getExtras();
1794 if (bundle != null) {
1795 pw.print(" extras: "); pw.println(bundle.toString());
1796 }
Christopher Tatef278f122015-04-22 13:12:01 -07001797 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001798 }
1799
1800 return needSep;
1801 }
1802}