blob: baa71d708caadc8d04228cae3c593dc1dbe04faf [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;
Dianne Hackborna750a632015-06-16 17:18:23 -070054import com.android.server.DeviceIdleController;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080055
Wale Ogunwaled57969f2014-11-15 19:37:29 -080056import static com.android.server.am.ActivityManagerDebugConfig.*;
57
Dianne Hackborn40c8db52012-02-10 18:59:48 -080058/**
59 * BROADCASTS
60 *
61 * We keep two broadcast queues and associated bookkeeping, one for those at
62 * foreground priority, and one for normal (background-priority) broadcasts.
63 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070064public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070065 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080066 private static final String TAG_MU = TAG + POSTFIX_MU;
67 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080068
Dianne Hackborn4c51de42013-10-16 23:34:35 -070069 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070070 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070071 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080072
73 final ActivityManagerService mService;
74
75 /**
76 * Recognizable moniker for this queue
77 */
78 final String mQueueName;
79
80 /**
81 * Timeout period for this queue's broadcasts
82 */
83 final long mTimeoutPeriod;
84
85 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070086 * If true, we can delay broadcasts while waiting services to finish in the previous
87 * receiver's process.
88 */
89 final boolean mDelayBehindServices;
90
91 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080092 * Lists of all active broadcasts that are to be executed immediately
93 * (without waiting for another broadcast to finish). Currently this only
94 * contains broadcasts to registered receivers, to avoid spinning up
95 * a bunch of processes to execute IntentReceiver components. Background-
96 * and foreground-priority broadcasts are queued separately.
97 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070098 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070099
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800100 /**
101 * List of all active broadcasts that are to be executed one at a time.
102 * The object at the top of the list is the currently activity broadcasts;
103 * those after it are waiting for the top to finish. As with parallel
104 * broadcasts, separate background- and foreground-priority queues are
105 * maintained.
106 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700107 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800108
109 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700110 * Historical data of past broadcasts, for debugging. This is a ring buffer
111 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800112 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700113 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700114 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800115
116 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700117 * Summary of historical data of past broadcasts, for debugging. This is a
118 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700119 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700120 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700121 int mSummaryHistoryNext = 0;
122
123 /**
124 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
125 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
126 * clock time, not elapsed.
127 */
128 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
129 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
130 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700131
132 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800133 * Set when we current have a BROADCAST_INTENT_MSG in flight.
134 */
135 boolean mBroadcastsScheduled = false;
136
137 /**
138 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
139 */
140 boolean mPendingBroadcastTimeoutMessage;
141
142 /**
143 * Intent broadcasts that we have tried to start, but are
144 * waiting for the application's process to be created. We only
145 * need one per scheduling class (instead of a list) because we always
146 * process broadcasts one at a time, so no others can be started while
147 * waiting for this one.
148 */
149 BroadcastRecord mPendingBroadcast = null;
150
151 /**
152 * The receiver index that is pending, to restart the broadcast if needed.
153 */
154 int mPendingBroadcastRecvIndex;
155
156 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
157 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700158 static final int SCHEDULE_TEMP_WHITELIST_MSG
159 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800160
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;
Dianne Hackborna750a632015-06-16 17:18:23 -0700181 case SCHEDULE_TEMP_WHITELIST_MSG: {
182 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
183 if (dic != null) {
184 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700185 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700186 }
187 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800188 }
189 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800190 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800191
192 private final class AppNotResponding implements Runnable {
193 private final ProcessRecord mApp;
194 private final String mAnnotation;
195
196 public AppNotResponding(ProcessRecord app, String annotation) {
197 mApp = app;
198 mAnnotation = annotation;
199 }
200
201 @Override
202 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100203 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800204 }
205 }
206
Jeff Brown6f357d32014-01-15 20:40:55 -0800207 BroadcastQueue(ActivityManagerService service, Handler handler,
208 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800209 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800210 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800211 mQueueName = name;
212 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700213 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800214 }
215
216 public boolean isPendingBroadcastProcessLocked(int pid) {
217 return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
218 }
219
220 public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
221 mParallelBroadcasts.add(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800222 enqueueBroadcastHelper(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800223 }
224
225 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
226 mOrderedBroadcasts.add(r);
Carmen Jacksona68e3452017-01-17 14:01:33 -0800227 enqueueBroadcastHelper(r);
228 }
229
230 /**
231 * Don't call this method directly; call enqueueParallelBroadcastLocked or
232 * enqueueOrderedBroadcastLocked.
233 */
234 private void enqueueBroadcastHelper(BroadcastRecord r) {
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700235 r.enqueueClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -0800236
237 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
238 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
239 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
240 System.identityHashCode(r));
241 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800242 }
243
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800244 /**
245 * Find the same intent from queued parallel broadcast, replace with a new one and return
246 * the old one.
247 */
248 public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
249 return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800250 }
251
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800252 /**
253 * Find the same intent from queued ordered broadcast, replace with a new one and return
254 * the old one.
255 */
256 public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
257 return replaceBroadcastLocked(mOrderedBroadcasts, r, "ORDERED");
258 }
259
260 private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
261 BroadcastRecord r, String typeForLogging) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700262 final Intent intent = r.intent;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800263 for (int i = queue.size() - 1; i > 0; i--) {
264 final BroadcastRecord old = queue.get(i);
265 if (old.userId == r.userId && intent.filterEquals(old.intent)) {
266 if (DEBUG_BROADCAST) {
267 Slog.v(TAG_BROADCAST, "***** DROPPING "
268 + typeForLogging + " [" + mQueueName + "]: " + intent);
269 }
270 queue.set(i, r);
271 return old;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800272 }
273 }
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800274 return null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275 }
276
277 private final void processCurBroadcastLocked(BroadcastRecord r,
278 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800279 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800280 "Process cur broadcast " + r + " for app " + app);
281 if (app.thread == null) {
282 throw new RemoteException();
283 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700284 if (app.inFullBackup) {
285 skipReceiverLocked(r);
286 return;
287 }
288
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800289 r.receiver = app.thread.asBinder();
290 r.curApp = app;
yangzhenyud509bc92016-08-31 18:26:46 +0800291 app.curReceivers.add(r);
Dianne Hackborna413dc02013-07-12 12:02:55 -0700292 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700293 mService.updateLruProcessLocked(app, false, null);
294 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800295
296 // Tell the application to launch this receiver.
297 r.intent.setComponent(r.curComponent);
298
299 boolean started = false;
300 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800301 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800302 "Delivering to component " + r.curComponent
303 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700304 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
305 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800306 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
307 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700308 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
309 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800310 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800311 "Process cur broadcast " + r + " DELIVERED for app " + app);
312 started = true;
313 } finally {
314 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800315 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800316 "Process cur broadcast " + r + ": NOT STARTED!");
317 r.receiver = null;
318 r.curApp = null;
yangzhenyud509bc92016-08-31 18:26:46 +0800319 app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800320 }
321 }
322 }
323
324 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
325 boolean didSomething = false;
326 final BroadcastRecord br = mPendingBroadcast;
327 if (br != null && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700328 if (br.curApp != app) {
329 Slog.e(TAG, "App mismatch when sending pending broadcast to "
330 + app.processName + ", intended target is " + br.curApp.processName);
331 return false;
332 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800333 try {
334 mPendingBroadcast = null;
335 processCurBroadcastLocked(br, app);
336 didSomething = true;
337 } catch (Exception e) {
338 Slog.w(TAG, "Exception in new application when starting receiver "
339 + br.curComponent.flattenToShortString(), e);
340 logBroadcastReceiverDiscardLocked(br);
341 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700342 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800343 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700344 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800345 br.state = BroadcastRecord.IDLE;
346 throw new RuntimeException(e.getMessage());
347 }
348 }
349 return didSomething;
350 }
351
352 public void skipPendingBroadcastLocked(int pid) {
353 final BroadcastRecord br = mPendingBroadcast;
354 if (br != null && br.curApp.pid == pid) {
355 br.state = BroadcastRecord.IDLE;
356 br.nextReceiver = mPendingBroadcastRecvIndex;
357 mPendingBroadcast = null;
358 scheduleBroadcastsLocked();
359 }
360 }
361
362 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700363 BroadcastRecord r = null;
364 if (mOrderedBroadcasts.size() > 0) {
365 BroadcastRecord br = mOrderedBroadcasts.get(0);
366 if (br.curApp == app) {
367 r = br;
368 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800369 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800370 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800371 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800372 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800373 r = mPendingBroadcast;
374 }
375
376 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700377 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800378 }
379 }
380
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700381 private void skipReceiverLocked(BroadcastRecord r) {
382 logBroadcastReceiverDiscardLocked(r);
383 finishReceiverLocked(r, r.resultCode, r.resultData,
384 r.resultExtras, r.resultAbort, false);
385 scheduleBroadcastsLocked();
386 }
387
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800388 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800389 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800390 + mQueueName + "]: current="
391 + mBroadcastsScheduled);
392
393 if (mBroadcastsScheduled) {
394 return;
395 }
396 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
397 mBroadcastsScheduled = true;
398 }
399
400 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
401 if (mOrderedBroadcasts.size() > 0) {
402 final BroadcastRecord r = mOrderedBroadcasts.get(0);
403 if (r != null && r.receiver == receiver) {
404 return r;
405 }
406 }
407 return null;
408 }
409
410 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700411 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
412 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700413 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800414 r.state = BroadcastRecord.IDLE;
415 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700416 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800417 }
418 r.receiver = null;
419 r.intent.setComponent(null);
yangzhenyud509bc92016-08-31 18:26:46 +0800420 if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
421 r.curApp.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800422 }
423 if (r.curFilter != null) {
424 r.curFilter.receiverList.curBroadcast = null;
425 }
426 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800427 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700428 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800429 mPendingBroadcast = null;
430
431 r.resultCode = resultCode;
432 r.resultData = resultData;
433 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700434 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
435 r.resultAbort = resultAbort;
436 } else {
437 r.resultAbort = false;
438 }
439
440 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
441 && r.queue.mOrderedBroadcasts.size() > 0
442 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700443 ActivityInfo nextReceiver;
444 if (r.nextReceiver < r.receivers.size()) {
445 Object obj = r.receivers.get(r.nextReceiver);
446 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
447 } else {
448 nextReceiver = null;
449 }
450 // Don't do this if the next receive is in the same process as the current one.
451 if (receiver == null || nextReceiver == null
452 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
453 || !receiver.processName.equals(nextReceiver.processName)) {
454 // In this case, we are ready to process the next receiver for the current broadcast,
455 // but are on a queue that would like to wait for services to finish before moving
456 // on. If there are background services currently starting, then we will go into a
457 // special state where we hold off on continuing this broadcast until they are done.
Dianne Hackbornad51be92016-08-16 16:27:36 -0700458 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800459 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700460 r.state = BroadcastRecord.WAITING_SERVICES;
461 return false;
462 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700463 }
464 }
465
466 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800467
468 // We will process the next receiver right now if this is finishing
469 // an app receiver (which is always asynchronous) or after we have
470 // come back from calling a receiver.
471 return state == BroadcastRecord.APP_RECEIVE
472 || state == BroadcastRecord.CALL_DONE_RECEIVE;
473 }
474
Dianne Hackborn6285a322013-09-18 12:09:47 -0700475 public void backgroundServicesFinishedLocked(int userId) {
476 if (mOrderedBroadcasts.size() > 0) {
477 BroadcastRecord br = mOrderedBroadcasts.get(0);
478 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800479 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700480 br.curComponent = null;
481 br.state = BroadcastRecord.IDLE;
482 processNextBroadcast(false);
483 }
484 }
485 }
486
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700487 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800488 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700489 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800490 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000491 if (app != null) {
492 if (app.thread != null) {
493 // If we have an app thread, do the call through that so it is
494 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700495 try {
496 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
497 data, extras, ordered, sticky, sendingUser, app.repProcState);
498 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
499 // DeadObjectException when the process isn't actually dead.
500 //} catch (DeadObjectException ex) {
501 // Failed to call into the process. It's dying so just let it die and move on.
502 // throw ex;
503 } catch (RemoteException ex) {
504 // Failed to call into the process. It's either dying or wedged. Kill it gently.
505 synchronized (mService) {
506 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
507 + " (pid " + app.pid + "). Crashing it.");
508 app.scheduleCrash("can't deliver broadcast");
509 }
510 throw ex;
511 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000512 } else {
513 // Application has died. Receiver doesn't exist.
514 throw new RemoteException("app.thread must not be null");
515 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800516 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700517 receiver.performReceive(intent, resultCode, data, extras, ordered,
518 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800519 }
520 }
521
Svet Ganov99b60432015-06-27 13:15:22 -0700522 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800523 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800524 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700525 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800526 int perm = mService.checkComponentPermission(filter.requiredPermission,
527 r.callingPid, r.callingUid, -1, true);
528 if (perm != PackageManager.PERMISSION_GRANTED) {
529 Slog.w(TAG, "Permission Denial: broadcasting "
530 + r.intent.toString()
531 + " from " + r.callerPackage + " (pid="
532 + r.callingPid + ", uid=" + r.callingUid + ")"
533 + " requires " + filter.requiredPermission
534 + " due to registered receiver " + filter);
535 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700536 } else {
537 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
538 if (opCode != AppOpsManager.OP_NONE
539 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
540 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
541 Slog.w(TAG, "Appop Denial: broadcasting "
542 + r.intent.toString()
543 + " from " + r.callerPackage + " (pid="
544 + r.callingPid + ", uid=" + r.callingUid + ")"
545 + " requires appop " + AppOpsManager.permissionToOp(
546 filter.requiredPermission)
547 + " due to registered receiver " + filter);
548 skip = true;
549 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800550 }
551 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700552 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
553 for (int i = 0; i < r.requiredPermissions.length; i++) {
554 String requiredPermission = r.requiredPermissions[i];
555 int perm = mService.checkComponentPermission(requiredPermission,
556 filter.receiverList.pid, filter.receiverList.uid, -1, true);
557 if (perm != PackageManager.PERMISSION_GRANTED) {
558 Slog.w(TAG, "Permission Denial: receiving "
559 + r.intent.toString()
560 + " to " + filter.receiverList.app
561 + " (pid=" + filter.receiverList.pid
562 + ", uid=" + filter.receiverList.uid + ")"
563 + " requires " + requiredPermission
564 + " due to sender " + r.callerPackage
565 + " (uid " + r.callingUid + ")");
566 skip = true;
567 break;
568 }
569 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700570 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700571 && mService.mAppOpsService.noteOperation(appOp,
572 filter.receiverList.uid, filter.packageName)
573 != AppOpsManager.MODE_ALLOWED) {
574 Slog.w(TAG, "Appop Denial: receiving "
575 + r.intent.toString()
576 + " to " + filter.receiverList.app
577 + " (pid=" + filter.receiverList.pid
578 + ", uid=" + filter.receiverList.uid + ")"
579 + " requires appop " + AppOpsManager.permissionToOp(
580 requiredPermission)
581 + " due to sender " + r.callerPackage
582 + " (uid " + r.callingUid + ")");
583 skip = true;
584 break;
585 }
586 }
587 }
588 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
589 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000590 filter.receiverList.pid, filter.receiverList.uid, -1, true);
591 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700592 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000593 + r.intent.toString()
594 + " to " + filter.receiverList.app
595 + " (pid=" + filter.receiverList.pid
596 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000597 + " due to sender " + r.callerPackage
598 + " (uid " + r.callingUid + ")");
599 skip = true;
600 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700601 }
602 if (!skip && r.appOp != AppOpsManager.OP_NONE
603 && mService.mAppOpsService.noteOperation(r.appOp,
604 filter.receiverList.uid, filter.packageName)
605 != AppOpsManager.MODE_ALLOWED) {
606 Slog.w(TAG, "Appop Denial: receiving "
607 + r.intent.toString()
608 + " to " + filter.receiverList.app
609 + " (pid=" + filter.receiverList.pid
610 + ", uid=" + filter.receiverList.uid + ")"
611 + " requires appop " + AppOpsManager.opToName(r.appOp)
612 + " due to sender " + r.callerPackage
613 + " (uid " + r.callingUid + ")");
614 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700615 }
Svet Ganov99b60432015-06-27 13:15:22 -0700616
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700617 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
618 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800619 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700620 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800621
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800622 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700623 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
624 + " to " + filter.receiverList + ": process crashing");
625 skip = true;
626 }
627
Chad Brubakerb7e34d52017-02-22 12:36:06 -0800628 // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
629 // visible to Instant Apps.
630 final boolean visibleToInstantApps =
631 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
632
633 if (!skip && !visibleToInstantApps && filter.instantApp
634 && filter.receiverList.uid != r.callingUid) {
635 Slog.w(TAG, "Instant App Denial: receiving "
636 + r.intent.toString()
637 + " to " + filter.receiverList.app
638 + " (pid=" + filter.receiverList.pid
639 + ", uid=" + filter.receiverList.uid + ")"
640 + " due to sender " + r.callerPackage
641 + " (uid " + r.callingUid + ")"
642 + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
643 skip = true;
644 }
645
Chad Brubaker816c83b2017-03-02 10:27:59 -0800646 if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
647 && filter.receiverList.uid != r.callingUid) {
648 Slog.w(TAG, "Instant App Denial: receiving "
649 + r.intent.toString()
650 + " to " + filter.receiverList.app
651 + " (pid=" + filter.receiverList.pid
652 + ", uid=" + filter.receiverList.uid + ")"
653 + " requires receiver be visible to instant apps"
654 + " due to sender " + r.callerPackage
655 + " (uid " + r.callingUid + ")");
656 skip = true;
657 }
658
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800659 if (skip) {
660 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
661 return;
662 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800663
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800664 // If permissions need a review before any of the app components can run, we drop
665 // the broadcast and if the calling app is in the foreground and the broadcast is
666 // explicit we launch the review UI passing it a pending intent to send the skipped
667 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -0700668 if (mService.mPermissionReviewRequired) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800669 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
670 filter.owningUserId)) {
671 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
672 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800673 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800674 }
675
676 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
677
678 // If this is not being sent as an ordered broadcast, then we
679 // don't want to touch the fields that keep track of the current
680 // state of ordered broadcasts.
681 if (ordered) {
682 r.receiver = filter.receiverList.receiver.asBinder();
683 r.curFilter = filter;
684 filter.receiverList.curBroadcast = r;
685 r.state = BroadcastRecord.CALL_IN_RECEIVE;
686 if (filter.receiverList.app != null) {
687 // Bump hosting application to no longer be in background
688 // scheduling class. Note that we can't do that if there
689 // isn't an app... but we can only be in that case for
690 // things that directly call the IActivityManager API, which
691 // are already core system stuff so don't matter for this.
692 r.curApp = filter.receiverList.app;
yangzhenyud509bc92016-08-31 18:26:46 +0800693 filter.receiverList.app.curReceivers.add(r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800694 mService.updateOomAdjLocked(r.curApp);
695 }
696 }
697 try {
698 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
699 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700700 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
701 // Skip delivery if full backup in progress
702 // If it's an ordered broadcast, we need to continue to the next receiver.
703 if (ordered) {
704 skipReceiverLocked(r);
705 }
706 } else {
707 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
708 new Intent(r.intent), r.resultCode, r.resultData,
709 r.resultExtras, r.ordered, r.initialSticky, r.userId);
710 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800711 if (ordered) {
712 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
713 }
714 } catch (RemoteException e) {
715 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
716 if (ordered) {
717 r.receiver = null;
718 r.curFilter = null;
719 filter.receiverList.curBroadcast = null;
720 if (filter.receiverList.app != null) {
yangzhenyud509bc92016-08-31 18:26:46 +0800721 filter.receiverList.app.curReceivers.remove(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800722 }
723 }
724 }
725 }
726
Svet Ganov9c165d72015-12-01 19:52:26 -0800727 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
728 BroadcastRecord receiverRecord, String receivingPackageName,
729 final int receivingUserId) {
730 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
731 receivingPackageName, receivingUserId)) {
732 return true;
733 }
734
735 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800736 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800737 : true;
738
739 // Show a permission review UI only for explicit broadcast from a foreground app
740 if (callerForeground && receiverRecord.intent.getComponent() != null) {
741 IIntentSender target = mService.getIntentSenderLocked(
742 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
743 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
744 new Intent[]{receiverRecord.intent},
745 new String[]{receiverRecord.intent.resolveType(mService.mContext
746 .getContentResolver())},
747 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
748 | PendingIntent.FLAG_IMMUTABLE, null);
749
750 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
751 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
752 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
753 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
754 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
755
756 if (DEBUG_PERMISSIONS_REVIEW) {
757 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
758 + receivingPackageName);
759 }
760
761 mHandler.post(new Runnable() {
762 @Override
763 public void run() {
764 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
765 }
766 });
767 } else {
768 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
769 + receivingPackageName + " requires a permissions review");
770 }
771
772 return false;
773 }
774
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700775 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700776 if (duration > Integer.MAX_VALUE) {
777 duration = Integer.MAX_VALUE;
778 }
779 // XXX ideally we should pause the broadcast until everything behind this is done,
780 // or else we will likely start dispatching the broadcast before we have opened
781 // access to the app (there is a lot of asynchronicity behind this). It is probably
782 // not that big a deal, however, because the main purpose here is to allow apps
783 // to hold wake locks, and they will be able to acquire their wake lock immediately
784 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700785 StringBuilder b = new StringBuilder();
786 b.append("broadcast:");
787 UserHandle.formatUid(b, r.callingUid);
788 b.append(":");
789 if (r.intent.getAction() != null) {
790 b.append(r.intent.getAction());
791 } else if (r.intent.getComponent() != null) {
792 b.append(r.intent.getComponent().flattenToShortString());
793 } else if (r.intent.getData() != null) {
794 b.append(r.intent.getData());
795 }
796 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
797 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700798 }
799
Dianne Hackbornb8633f32017-04-11 17:38:42 -0700800 /**
801 * Return true if all given permissions are signature-only perms.
802 */
803 final boolean isSignaturePerm(String[] perms) {
804 if (perms == null) {
805 return false;
806 }
807 IPackageManager pm = AppGlobals.getPackageManager();
808 for (int i = perms.length-1; i >= 0; i--) {
809 try {
810 PermissionInfo pi = pm.getPermissionInfo(perms[i], 0);
811 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
812 | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
813 != PermissionInfo.PROTECTION_SIGNATURE) {
814 // If this a signature permission and NOT allowed for privileged apps, it
815 // is okay... otherwise, nope!
816 return false;
817 }
818 } catch (RemoteException e) {
819 return false;
820 }
821 }
822 return true;
823 }
824
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800825 final void processNextBroadcast(boolean fromMsg) {
826 synchronized(mService) {
827 BroadcastRecord r;
828
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800829 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800830 + mQueueName + "]: "
Carmen Jacksona68e3452017-01-17 14:01:33 -0800831 + mParallelBroadcasts.size() + " parallel broadcasts, "
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800832 + mOrderedBroadcasts.size() + " ordered broadcasts");
833
834 mService.updateCpuStats();
835
836 if (fromMsg) {
837 mBroadcastsScheduled = false;
838 }
839
840 // First, deliver any non-serialized broadcasts right away.
841 while (mParallelBroadcasts.size() > 0) {
842 r = mParallelBroadcasts.remove(0);
843 r.dispatchTime = SystemClock.uptimeMillis();
844 r.dispatchClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -0800845
846 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
847 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
848 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
849 System.identityHashCode(r));
850 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
851 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
852 System.identityHashCode(r));
853 }
854
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800855 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800856 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800857 + mQueueName + "] " + r);
858 for (int i=0; i<N; i++) {
859 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800860 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800861 "Delivering non-ordered on [" + mQueueName + "] to registered "
862 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800863 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800864 }
865 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800866 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800867 + mQueueName + "] " + r);
868 }
869
870 // Now take care of the next serialized one...
871
872 // If we are waiting for a process to come up to handle the next
873 // broadcast, then do nothing at this point. Just in case, we
874 // check that the process we're waiting for still exists.
875 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700876 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
877 "processNextBroadcast [" + mQueueName + "]: waiting for "
878 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800879
880 boolean isDead;
881 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700882 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
883 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800884 }
885 if (!isDead) {
886 // It's still alive, so keep waiting
887 return;
888 } else {
889 Slog.w(TAG, "pending app ["
890 + mQueueName + "]" + mPendingBroadcast.curApp
891 + " died before responding to broadcast");
892 mPendingBroadcast.state = BroadcastRecord.IDLE;
893 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
894 mPendingBroadcast = null;
895 }
896 }
897
898 boolean looped = false;
899
900 do {
901 if (mOrderedBroadcasts.size() == 0) {
902 // No more broadcasts pending, so all done!
903 mService.scheduleAppGcsLocked();
904 if (looped) {
905 // If we had finished the last ordered broadcast, then
906 // make sure all processes have correct oom and sched
907 // adjustments.
908 mService.updateOomAdjLocked();
909 }
910 return;
911 }
912 r = mOrderedBroadcasts.get(0);
913 boolean forceReceive = false;
914
915 // Ensure that even if something goes awry with the timeout
916 // detection, we catch "hung" broadcasts here, discard them,
917 // and continue to make progress.
918 //
919 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
920 // receivers don't get executed with timeouts. They're intended for
921 // one time heavy lifting after system upgrades and can take
922 // significant amounts of time.
923 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
924 if (mService.mProcessesReady && r.dispatchTime > 0) {
925 long now = SystemClock.uptimeMillis();
926 if ((numReceivers > 0) &&
927 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
928 Slog.w(TAG, "Hung broadcast ["
929 + mQueueName + "] discarded after timeout failure:"
930 + " now=" + now
931 + " dispatchTime=" + r.dispatchTime
932 + " startTime=" + r.receiverTime
933 + " intent=" + r.intent
934 + " numReceivers=" + numReceivers
935 + " nextReceiver=" + r.nextReceiver
936 + " state=" + r.state);
937 broadcastTimeoutLocked(false); // forcibly finish this broadcast
938 forceReceive = true;
939 r.state = BroadcastRecord.IDLE;
940 }
941 }
942
943 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800944 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800945 "processNextBroadcast("
946 + mQueueName + ") called when not idle (state="
947 + r.state + ")");
948 return;
949 }
950
951 if (r.receivers == null || r.nextReceiver >= numReceivers
952 || r.resultAbort || forceReceive) {
953 // No more receivers for this broadcast! Send the final
954 // result if requested...
955 if (r.resultTo != null) {
956 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800957 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800958 "Finishing broadcast [" + mQueueName + "] "
959 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800960 performReceiveLocked(r.callerApp, r.resultTo,
961 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700962 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800963 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700964 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800965 r.resultTo = null;
966 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000967 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800968 Slog.w(TAG, "Failure ["
969 + mQueueName + "] sending broadcast result of "
970 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700971
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800972 }
973 }
974
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800975 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800976 cancelBroadcastTimeoutLocked();
977
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700978 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
979 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800980
981 // ... and on to the next...
982 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700983 if (r.intent.getComponent() == null && r.intent.getPackage() == null
984 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
985 // This was an implicit broadcast... let's record it for posterity.
986 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
987 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
988 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800989 mOrderedBroadcasts.remove(0);
990 r = null;
991 looped = true;
992 continue;
993 }
994 } while (r == null);
995
996 // Get the next receiver...
997 int recIdx = r.nextReceiver++;
998
999 // Keep track of when this receiver started, and make sure there
1000 // is a timeout message pending to kill it if need be.
1001 r.receiverTime = SystemClock.uptimeMillis();
1002 if (recIdx == 0) {
1003 r.dispatchTime = r.receiverTime;
1004 r.dispatchClockTime = System.currentTimeMillis();
Carmen Jacksona68e3452017-01-17 14:01:33 -08001005 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1006 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1007 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1008 System.identityHashCode(r));
1009 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1010 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1011 System.identityHashCode(r));
1012 }
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001013 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001014 + mQueueName + "] " + r);
1015 }
1016 if (! mPendingBroadcastTimeoutMessage) {
1017 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001018 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001019 "Submitting BROADCAST_TIMEOUT_MSG ["
1020 + mQueueName + "] for " + r + " at " + timeoutTime);
1021 setBroadcastTimeoutLocked(timeoutTime);
1022 }
1023
Dianne Hackborna750a632015-06-16 17:18:23 -07001024 final BroadcastOptions brOptions = r.options;
1025 final Object nextReceiver = r.receivers.get(recIdx);
1026
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001027 if (nextReceiver instanceof BroadcastFilter) {
1028 // Simple case: this is a registered receiver who gets
1029 // a direct call.
1030 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001031 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001032 "Delivering ordered ["
1033 + mQueueName + "] to registered "
1034 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001035 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001036 if (r.receiver == null || !r.ordered) {
1037 // The receiver has already finished, so schedule to
1038 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001039 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001040 + mQueueName + "]: ordered="
1041 + r.ordered + " receiver=" + r.receiver);
1042 r.state = BroadcastRecord.IDLE;
1043 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -07001044 } else {
1045 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1046 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001047 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001048 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001049 }
1050 return;
1051 }
1052
1053 // Hard case: need to instantiate the receiver, possibly
1054 // starting its application process to host it.
1055
1056 ResolveInfo info =
1057 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001058 ComponentName component = new ComponentName(
1059 info.activityInfo.applicationInfo.packageName,
1060 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001061
1062 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001063 if (brOptions != null &&
1064 (info.activityInfo.applicationInfo.targetSdkVersion
1065 < brOptions.getMinManifestReceiverApiLevel() ||
1066 info.activityInfo.applicationInfo.targetSdkVersion
1067 > brOptions.getMaxManifestReceiverApiLevel())) {
1068 skip = true;
1069 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001070 int perm = mService.checkComponentPermission(info.activityInfo.permission,
1071 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1072 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001073 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001074 if (!info.activityInfo.exported) {
1075 Slog.w(TAG, "Permission Denial: broadcasting "
1076 + r.intent.toString()
1077 + " from " + r.callerPackage + " (pid=" + r.callingPid
1078 + ", uid=" + r.callingUid + ")"
1079 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001080 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001081 } else {
1082 Slog.w(TAG, "Permission Denial: broadcasting "
1083 + r.intent.toString()
1084 + " from " + r.callerPackage + " (pid=" + r.callingPid
1085 + ", uid=" + r.callingUid + ")"
1086 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001087 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001088 }
1089 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001090 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001091 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1092 if (opCode != AppOpsManager.OP_NONE
1093 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1094 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1095 Slog.w(TAG, "Appop Denial: broadcasting "
1096 + r.intent.toString()
1097 + " from " + r.callerPackage + " (pid="
1098 + r.callingPid + ", uid=" + r.callingUid + ")"
1099 + " requires appop " + AppOpsManager.permissionToOp(
1100 info.activityInfo.permission)
1101 + " due to registered receiver "
1102 + component.flattenToShortString());
1103 skip = true;
1104 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001105 }
Svet Ganov99b60432015-06-27 13:15:22 -07001106 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001107 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1108 for (int i = 0; i < r.requiredPermissions.length; i++) {
1109 String requiredPermission = r.requiredPermissions[i];
1110 try {
1111 perm = AppGlobals.getPackageManager().
1112 checkPermission(requiredPermission,
1113 info.activityInfo.applicationInfo.packageName,
1114 UserHandle
1115 .getUserId(info.activityInfo.applicationInfo.uid));
1116 } catch (RemoteException e) {
1117 perm = PackageManager.PERMISSION_DENIED;
1118 }
1119 if (perm != PackageManager.PERMISSION_GRANTED) {
1120 Slog.w(TAG, "Permission Denial: receiving "
1121 + r.intent + " to "
1122 + component.flattenToShortString()
1123 + " requires " + requiredPermission
1124 + " due to sender " + r.callerPackage
1125 + " (uid " + r.callingUid + ")");
1126 skip = true;
1127 break;
1128 }
1129 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1130 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1131 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001132 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001133 != AppOpsManager.MODE_ALLOWED) {
1134 Slog.w(TAG, "Appop Denial: receiving "
1135 + r.intent + " to "
1136 + component.flattenToShortString()
1137 + " requires appop " + AppOpsManager.permissionToOp(
1138 requiredPermission)
1139 + " due to sender " + r.callerPackage
1140 + " (uid " + r.callingUid + ")");
1141 skip = true;
1142 break;
1143 }
1144 }
1145 }
1146 if (!skip && r.appOp != AppOpsManager.OP_NONE
1147 && mService.mAppOpsService.noteOperation(r.appOp,
1148 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1149 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001150 Slog.w(TAG, "Appop Denial: receiving "
1151 + r.intent + " to "
1152 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001153 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001154 + " due to sender " + r.callerPackage
1155 + " (uid " + r.callingUid + ")");
1156 skip = true;
1157 }
Ben Gruver49660c72013-08-06 19:54:08 -07001158 if (!skip) {
1159 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1160 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1161 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001162 boolean isSingleton = false;
1163 try {
1164 isSingleton = mService.isSingleton(info.activityInfo.processName,
1165 info.activityInfo.applicationInfo,
1166 info.activityInfo.name, info.activityInfo.flags);
1167 } catch (SecurityException e) {
1168 Slog.w(TAG, e.getMessage());
1169 skip = true;
1170 }
1171 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1172 if (ActivityManager.checkUidPermission(
1173 android.Manifest.permission.INTERACT_ACROSS_USERS,
1174 info.activityInfo.applicationInfo.uid)
1175 != PackageManager.PERMISSION_GRANTED) {
1176 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1177 + " requests FLAG_SINGLE_USER, but app does not hold "
1178 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1179 skip = true;
1180 }
1181 }
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001182 if (!skip && info.activityInfo.applicationInfo.isInstantApp()
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001183 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1184 Slog.w(TAG, "Instant App Denial: receiving "
1185 + r.intent
1186 + " to " + component.flattenToShortString()
1187 + " due to sender " + r.callerPackage
1188 + " (uid " + r.callingUid + ")"
Chad Brubakerabd2b662017-03-16 11:24:16 -07001189 + " Instant Apps do not support manifest receivers");
Chad Brubakerb7e34d52017-02-22 12:36:06 -08001190 skip = true;
1191 }
Chad Brubaker816c83b2017-03-02 10:27:59 -08001192 if (!skip && r.callerInstantApp
1193 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0
1194 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1195 Slog.w(TAG, "Instant App Denial: receiving "
1196 + r.intent
1197 + " to " + component.flattenToShortString()
1198 + " requires receiver have visibleToInstantApps set"
1199 + " due to sender " + r.callerPackage
1200 + " (uid " + r.callingUid + ")");
1201 skip = true;
1202 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001203 if (!skip) {
1204 r.manifestCount++;
1205 } else {
1206 r.manifestSkipCount++;
1207 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001208 if (r.curApp != null && r.curApp.crashing) {
1209 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001210 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1211 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001212 skip = true;
1213 }
Christopher Tateba629da2013-11-13 17:42:28 -08001214 if (!skip) {
1215 boolean isAvailable = false;
1216 try {
1217 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1218 info.activityInfo.packageName,
1219 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1220 } catch (Exception e) {
1221 // all such failures mean we skip this receiver
1222 Slog.w(TAG, "Exception getting recipient info for "
1223 + info.activityInfo.packageName, e);
1224 }
1225 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001226 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1227 "Skipping delivery to " + info.activityInfo.packageName + " / "
1228 + info.activityInfo.applicationInfo.uid
1229 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001230 skip = true;
1231 }
1232 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001233
Svet Ganov9c165d72015-12-01 19:52:26 -08001234 // If permissions need a review before any of the app components can run, we drop
1235 // the broadcast and if the calling app is in the foreground and the broadcast is
1236 // explicit we launch the review UI passing it a pending intent to send the skipped
1237 // broadcast.
Svet Ganov77df6f32016-08-17 11:46:34 -07001238 if (mService.mPermissionReviewRequired && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001239 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1240 info.activityInfo.packageName, UserHandle.getUserId(
1241 info.activityInfo.applicationInfo.uid))) {
1242 skip = true;
1243 }
1244 }
1245
Dianne Hackborn76e80092015-12-09 14:15:34 -08001246 // This is safe to do even if we are skipping the broadcast, and we need
1247 // this information now to evaluate whether it is going to be allowed to run.
1248 final int receiverUid = info.activityInfo.applicationInfo.uid;
1249 // If it's a singleton, it needs to be the same app or a special app
1250 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1251 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1252 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1253 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001254 String targetProcess = info.activityInfo.processName;
1255 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1256 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001257
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001258 if (!skip) {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001259 final int allowed = mService.getAppStartModeLocked(
1260 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1261 info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001262 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1263 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001264 // completely disabled from launches, or it was not explicitly sent
1265 // to it and the app is in a state that should not receive it
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001266 // (depending on how getAppStartModeLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001267 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1268 Slog.w(TAG, "Background execution disabled: receiving "
1269 + r.intent + " to "
1270 + component.flattenToShortString());
1271 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001272 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001273 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001274 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001275 && ((r.intent.getFlags()
Dianne Hackbornb8633f32017-04-11 17:38:42 -07001276 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1277 && !isSignaturePerm(r.requiredPermissions))) {
Dianne Hackborn7fc46d82017-02-14 15:20:06 -08001278 mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1279 component.getPackageName());
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001280 Slog.w(TAG, "Background execution not allowed: receiving "
1281 + r.intent + " to "
1282 + component.flattenToShortString());
1283 skip = true;
1284 }
1285 }
1286 }
1287
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001288 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001289 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001290 "Skipping delivery of ordered [" + mQueueName + "] "
1291 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001292 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001293 r.receiver = null;
1294 r.curFilter = null;
1295 r.state = BroadcastRecord.IDLE;
1296 scheduleBroadcastsLocked();
1297 return;
1298 }
1299
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001300 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001301 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001302 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001303 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001304 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001305 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1306 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1307 + info.activityInfo.applicationInfo.uid);
1308 }
1309
Dianne Hackborna750a632015-06-16 17:18:23 -07001310 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1311 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001312 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001313 }
1314
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001315 // Broadcast is being executed, its package can't be stopped.
1316 try {
1317 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001318 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001319 } catch (RemoteException e) {
1320 } catch (IllegalArgumentException e) {
1321 Slog.w(TAG, "Failed trying to unstop package "
1322 + r.curComponent.getPackageName() + ": " + e);
1323 }
1324
1325 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001326 if (app != null && app.thread != null) {
1327 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001328 app.addPackage(info.activityInfo.packageName,
1329 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001330 processCurBroadcastLocked(r, app);
1331 return;
1332 } catch (RemoteException e) {
1333 Slog.w(TAG, "Exception when sending broadcast to "
1334 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001335 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001336 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001337 + r.curComponent + " with " + r.intent, e);
1338 // If some unexpected exception happened, just skip
1339 // this broadcast. At this point we are not in the call
1340 // from a client, so throwing an exception out from here
1341 // will crash the entire system instead of just whoever
1342 // sent the broadcast.
1343 logBroadcastReceiverDiscardLocked(r);
1344 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001345 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001346 scheduleBroadcastsLocked();
1347 // We need to reset the state if we failed to start the receiver.
1348 r.state = BroadcastRecord.IDLE;
1349 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001350 }
1351
1352 // If a dead object exception was thrown -- fall through to
1353 // restart the application.
1354 }
1355
1356 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001357 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001358 "Need to start app ["
1359 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1360 if ((r.curApp=mService.startProcessLocked(targetProcess,
1361 info.activityInfo.applicationInfo, true,
1362 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1363 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001364 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001365 == null) {
1366 // Ah, this recipient is unavailable. Finish it if necessary,
1367 // and mark the broadcast record as ready for the next.
1368 Slog.w(TAG, "Unable to launch app "
1369 + info.activityInfo.applicationInfo.packageName + "/"
1370 + info.activityInfo.applicationInfo.uid + " for broadcast "
1371 + r.intent + ": process is bad");
1372 logBroadcastReceiverDiscardLocked(r);
1373 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001374 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001375 scheduleBroadcastsLocked();
1376 r.state = BroadcastRecord.IDLE;
1377 return;
1378 }
1379
1380 mPendingBroadcast = r;
1381 mPendingBroadcastRecvIndex = recIdx;
1382 }
1383 }
1384
1385 final void setBroadcastTimeoutLocked(long timeoutTime) {
1386 if (! mPendingBroadcastTimeoutMessage) {
1387 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1388 mHandler.sendMessageAtTime(msg, timeoutTime);
1389 mPendingBroadcastTimeoutMessage = true;
1390 }
1391 }
1392
1393 final void cancelBroadcastTimeoutLocked() {
1394 if (mPendingBroadcastTimeoutMessage) {
1395 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1396 mPendingBroadcastTimeoutMessage = false;
1397 }
1398 }
1399
1400 final void broadcastTimeoutLocked(boolean fromMsg) {
1401 if (fromMsg) {
1402 mPendingBroadcastTimeoutMessage = false;
1403 }
1404
1405 if (mOrderedBroadcasts.size() == 0) {
1406 return;
1407 }
1408
1409 long now = SystemClock.uptimeMillis();
1410 BroadcastRecord r = mOrderedBroadcasts.get(0);
1411 if (fromMsg) {
1412 if (mService.mDidDexOpt) {
1413 // Delay timeouts until dexopt finishes.
1414 mService.mDidDexOpt = false;
1415 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1416 setBroadcastTimeoutLocked(timeoutTime);
1417 return;
1418 }
1419 if (!mService.mProcessesReady) {
1420 // Only process broadcast timeouts if the system is ready. That way
1421 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1422 // to do heavy lifting for system up.
1423 return;
1424 }
1425
1426 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1427 if (timeoutTime > now) {
1428 // We can observe premature timeouts because we do not cancel and reset the
1429 // broadcast timeout message after each receiver finishes. Instead, we set up
1430 // an initial timeout then kick it down the road a little further as needed
1431 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001432 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001433 "Premature timeout ["
1434 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1435 + timeoutTime);
1436 setBroadcastTimeoutLocked(timeoutTime);
1437 return;
1438 }
1439 }
1440
Dianne Hackborn6285a322013-09-18 12:09:47 -07001441 BroadcastRecord br = mOrderedBroadcasts.get(0);
1442 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1443 // In this case the broadcast had already finished, but we had decided to wait
1444 // for started services to finish as well before going on. So if we have actually
1445 // waited long enough time timeout the broadcast, let's give up on the whole thing
1446 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001447 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001448 ? br.curComponent.flattenToShortString() : "(null)"));
1449 br.curComponent = null;
1450 br.state = BroadcastRecord.IDLE;
1451 processNextBroadcast(false);
1452 return;
1453 }
1454
1455 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001456 + ", started " + (now - r.receiverTime) + "ms ago");
1457 r.receiverTime = now;
1458 r.anrCount++;
1459
1460 // Current receiver has passed its expiration date.
1461 if (r.nextReceiver <= 0) {
1462 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1463 return;
1464 }
1465
1466 ProcessRecord app = null;
1467 String anrMessage = null;
1468
1469 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001470 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001471 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1472 logBroadcastReceiverDiscardLocked(r);
1473 if (curReceiver instanceof BroadcastFilter) {
1474 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1475 if (bf.receiverList.pid != 0
1476 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1477 synchronized (mService.mPidsSelfLocked) {
1478 app = mService.mPidsSelfLocked.get(
1479 bf.receiverList.pid);
1480 }
1481 }
1482 } else {
1483 app = r.curApp;
1484 }
1485
1486 if (app != null) {
1487 anrMessage = "Broadcast of " + r.intent.toString();
1488 }
1489
1490 if (mPendingBroadcast == r) {
1491 mPendingBroadcast = null;
1492 }
1493
1494 // Move on to the next receiver.
1495 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001496 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001497 scheduleBroadcastsLocked();
1498
1499 if (anrMessage != null) {
1500 // Post the ANR to the handler since we do not want to process ANRs while
1501 // potentially holding our lock.
1502 mHandler.post(new AppNotResponding(app, anrMessage));
1503 }
1504 }
1505
Christopher Tatef278f122015-04-22 13:12:01 -07001506 private final int ringAdvance(int x, final int increment, final int ringSize) {
1507 x += increment;
1508 if (x < 0) return (ringSize - 1);
1509 else if (x >= ringSize) return 0;
1510 else return x;
1511 }
1512
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001513 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1514 if (r.callingUid < 0) {
1515 // This was from a registerReceiver() call; ignore it.
1516 return;
1517 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001518 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001519
Carmen Jacksona68e3452017-01-17 14:01:33 -08001520 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1521 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1522 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1523 System.identityHashCode(r));
1524 }
1525
Christopher Tatef278f122015-04-22 13:12:01 -07001526 mBroadcastHistory[mHistoryNext] = r;
1527 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1528
1529 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1530 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1531 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1532 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1533 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001534 }
1535
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001536 boolean cleanupDisabledPackageReceiversLocked(
1537 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1538 boolean didSomething = false;
1539 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1540 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1541 packageName, filterByClasses, userId, doit);
1542 if (!doit && didSomething) {
1543 return true;
1544 }
1545 }
1546
1547 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1548 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1549 packageName, filterByClasses, userId, doit);
1550 if (!doit && didSomething) {
1551 return true;
1552 }
1553 }
1554
1555 return didSomething;
1556 }
1557
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001558 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001559 final int logIndex = r.nextReceiver - 1;
1560 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1561 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001562 if (curReceiver instanceof BroadcastFilter) {
1563 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1564 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001565 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001566 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001567 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001568 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001569 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001570 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001571 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001572 }
1573 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001574 if (logIndex < 0) Slog.w(TAG,
1575 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001576 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001577 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001578 r.intent.getAction(),
1579 r.nextReceiver,
1580 "NONE");
1581 }
1582 }
1583
Carmen Jacksona68e3452017-01-17 14:01:33 -08001584 private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1585 return String.format("Broadcast %s from %s (%s) %s",
1586 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1587 record.callerPackage == null ? "" : record.callerPackage,
1588 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1589 record.intent == null ? "" : record.intent.getAction());
1590 }
1591
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001592 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1593 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001594 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001595 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1596 || mPendingBroadcast != null) {
1597 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001598 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001599 BroadcastRecord br = mParallelBroadcasts.get(i);
1600 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1601 continue;
1602 }
1603 if (!printed) {
1604 if (needSep) {
1605 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001606 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001607 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001608 printed = true;
1609 pw.println(" Active broadcasts [" + mQueueName + "]:");
1610 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001611 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001612 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001613 }
1614 printed = false;
1615 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001616 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001617 BroadcastRecord br = mOrderedBroadcasts.get(i);
1618 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1619 continue;
1620 }
1621 if (!printed) {
1622 if (needSep) {
1623 pw.println();
1624 }
1625 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001626 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001627 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1628 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001629 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001630 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001631 }
1632 if (dumpPackage == null || (mPendingBroadcast != null
1633 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1634 if (needSep) {
1635 pw.println();
1636 }
1637 pw.println(" Pending broadcast [" + mQueueName + "]:");
1638 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001639 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001640 } else {
1641 pw.println(" (null)");
1642 }
1643 needSep = true;
1644 }
1645 }
1646
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001647 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001648 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001649
1650 i = -1;
1651 int lastIndex = mHistoryNext;
1652 int ringIndex = lastIndex;
1653 do {
1654 // increasing index = more recent entry, and we want to print the most
1655 // recent first and work backwards, so we roll through the ring backwards.
1656 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1657 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001658 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001659 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001660 }
Christopher Tatef278f122015-04-22 13:12:01 -07001661
1662 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001663 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1664 continue;
1665 }
1666 if (!printed) {
1667 if (needSep) {
1668 pw.println();
1669 }
1670 needSep = true;
1671 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1672 printed = true;
1673 }
1674 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001675 pw.print(" Historical Broadcast " + mQueueName + " #");
1676 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001677 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001678 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001679 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1680 pw.print(" ");
1681 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001682 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1683 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1684 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001685 Bundle bundle = r.intent.getExtras();
1686 if (bundle != null) {
1687 pw.print(" extras: "); pw.println(bundle.toString());
1688 }
1689 }
Christopher Tatef278f122015-04-22 13:12:01 -07001690 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001691
1692 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001693 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001694 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001695 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001696 i = -1;
1697 } else {
1698 // roll over the 'i' full dumps that have already been issued
1699 for (int j = i;
1700 j > 0 && ringIndex != lastIndex;) {
1701 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1702 BroadcastRecord r = mBroadcastHistory[ringIndex];
1703 if (r == null) {
1704 continue;
1705 }
1706 j--;
1707 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001708 }
Christopher Tatef278f122015-04-22 13:12:01 -07001709 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1710 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001711 do {
1712 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1713 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001714 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001715 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001716 }
1717 if (!printed) {
1718 if (needSep) {
1719 pw.println();
1720 }
1721 needSep = true;
1722 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1723 printed = true;
1724 }
1725 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001726 pw.println(" ...");
1727 break;
1728 }
Christopher Tatef278f122015-04-22 13:12:01 -07001729 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001730 pw.print(" #"); pw.print(i); pw.print(": ");
1731 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001732 pw.print(" ");
1733 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1734 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1735 pw.print(" dispatch ");
1736 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1737 - mSummaryHistoryDispatchTime[ringIndex], pw);
1738 pw.println(" finish");
1739 pw.print(" enq=");
1740 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1741 pw.print(" disp=");
1742 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1743 pw.print(" fin=");
1744 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001745 Bundle bundle = intent.getExtras();
1746 if (bundle != null) {
1747 pw.print(" extras: "); pw.println(bundle.toString());
1748 }
Christopher Tatef278f122015-04-22 13:12:01 -07001749 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001750 }
1751
1752 return needSep;
1753 }
1754}