blob: 8f2e05f7dc030bb424c71521f5dd2cd00f4c4f3c [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
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
Christopher Tatef278f122015-04-22 13:12:01 -070021import java.text.SimpleDateFormat;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080022import java.util.ArrayList;
Christopher Tatef278f122015-04-22 13:12:01 -070023import java.util.Date;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -070024import java.util.Set;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080025
Dianne Hackborn7d19e022012-08-07 19:12:33 -070026import android.app.ActivityManager;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080027import android.app.AppGlobals;
Dianne Hackbornf51f6122013-02-04 18:23:34 -080028import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070029import android.app.BroadcastOptions;
Svet Ganov9c165d72015-12-01 19:52:26 -080030import android.app.PendingIntent;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080031import android.content.ComponentName;
32import android.content.IIntentReceiver;
Svet Ganov9c165d72015-12-01 19:52:26 -080033import android.content.IIntentSender;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080034import android.content.Intent;
Svet Ganov9c165d72015-12-01 19:52:26 -080035import android.content.IntentSender;
Dianne Hackborn7d19e022012-08-07 19:12:33 -070036import android.content.pm.ActivityInfo;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
Svet Ganov9c165d72015-12-01 19:52:26 -080039import android.os.Build;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080040import android.os.Bundle;
41import android.os.Handler;
42import android.os.IBinder;
Jeff Brown6f357d32014-01-15 20:40:55 -080043import android.os.Looper;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080044import android.os.Message;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080049import android.util.EventLog;
50import android.util.Slog;
Dianne Hackborn865907d2015-10-21 17:12:53 -070051import android.util.TimeUtils;
Dianne Hackborna750a632015-06-16 17:18:23 -070052import com.android.server.DeviceIdleController;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080053
Wale Ogunwaled57969f2014-11-15 19:37:29 -080054import static com.android.server.am.ActivityManagerDebugConfig.*;
55
Dianne Hackborn40c8db52012-02-10 18:59:48 -080056/**
57 * BROADCASTS
58 *
59 * We keep two broadcast queues and associated bookkeeping, one for those at
60 * foreground priority, and one for normal (background-priority) broadcasts.
61 */
Dianne Hackbornbe4e6aa2013-06-07 13:25:29 -070062public final class BroadcastQueue {
Wale Ogunwalebfac4682015-04-08 14:33:21 -070063 private static final String TAG = "BroadcastQueue";
Wale Ogunwaled57969f2014-11-15 19:37:29 -080064 private static final String TAG_MU = TAG + POSTFIX_MU;
65 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080066
Dianne Hackborn4c51de42013-10-16 23:34:35 -070067 static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
Dianne Hackborn6285a322013-09-18 12:09:47 -070068 static final int MAX_BROADCAST_SUMMARY_HISTORY
Dianne Hackborn4c51de42013-10-16 23:34:35 -070069 = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
Dianne Hackborn40c8db52012-02-10 18:59:48 -080070
71 final ActivityManagerService mService;
72
73 /**
74 * Recognizable moniker for this queue
75 */
76 final String mQueueName;
77
78 /**
79 * Timeout period for this queue's broadcasts
80 */
81 final long mTimeoutPeriod;
82
83 /**
Dianne Hackborn6285a322013-09-18 12:09:47 -070084 * If true, we can delay broadcasts while waiting services to finish in the previous
85 * receiver's process.
86 */
87 final boolean mDelayBehindServices;
88
89 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -080090 * Lists of all active broadcasts that are to be executed immediately
91 * (without waiting for another broadcast to finish). Currently this only
92 * contains broadcasts to registered receivers, to avoid spinning up
93 * a bunch of processes to execute IntentReceiver components. Background-
94 * and foreground-priority broadcasts are queued separately.
95 */
Wale Ogunwale540e1232015-05-01 15:35:39 -070096 final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
Dianne Hackborn6285a322013-09-18 12:09:47 -070097
Dianne Hackborn40c8db52012-02-10 18:59:48 -080098 /**
99 * List of all active broadcasts that are to be executed one at a time.
100 * The object at the top of the list is the currently activity broadcasts;
101 * those after it are waiting for the top to finish. As with parallel
102 * broadcasts, separate background- and foreground-priority queues are
103 * maintained.
104 */
Wale Ogunwale540e1232015-05-01 15:35:39 -0700105 final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800106
107 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700108 * Historical data of past broadcasts, for debugging. This is a ring buffer
109 * whose last element is at mHistoryNext.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800110 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700111 final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700112 int mHistoryNext = 0;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800113
114 /**
Christopher Tatef278f122015-04-22 13:12:01 -0700115 * Summary of historical data of past broadcasts, for debugging. This is a
116 * ring buffer whose last element is at mSummaryHistoryNext.
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700117 */
Dianne Hackborn6285a322013-09-18 12:09:47 -0700118 final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
Christopher Tatef278f122015-04-22 13:12:01 -0700119 int mSummaryHistoryNext = 0;
120
121 /**
122 * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
123 * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall
124 * clock time, not elapsed.
125 */
126 final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
127 final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
128 final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -0700129
130 /**
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800131 * Set when we current have a BROADCAST_INTENT_MSG in flight.
132 */
133 boolean mBroadcastsScheduled = false;
134
135 /**
136 * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
137 */
138 boolean mPendingBroadcastTimeoutMessage;
139
140 /**
141 * Intent broadcasts that we have tried to start, but are
142 * waiting for the application's process to be created. We only
143 * need one per scheduling class (instead of a list) because we always
144 * process broadcasts one at a time, so no others can be started while
145 * waiting for this one.
146 */
147 BroadcastRecord mPendingBroadcast = null;
148
149 /**
150 * The receiver index that is pending, to restart the broadcast if needed.
151 */
152 int mPendingBroadcastRecvIndex;
153
154 static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
155 static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
Dianne Hackborna750a632015-06-16 17:18:23 -0700156 static final int SCHEDULE_TEMP_WHITELIST_MSG
157 = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800158
Jeff Brown6f357d32014-01-15 20:40:55 -0800159 final BroadcastHandler mHandler;
160
161 private final class BroadcastHandler extends Handler {
162 public BroadcastHandler(Looper looper) {
163 super(looper, null, true);
164 }
165
166 @Override
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800167 public void handleMessage(Message msg) {
168 switch (msg.what) {
169 case BROADCAST_INTENT_MSG: {
170 if (DEBUG_BROADCAST) Slog.v(
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800171 TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800172 processNextBroadcast(true);
173 } break;
174 case BROADCAST_TIMEOUT_MSG: {
175 synchronized (mService) {
176 broadcastTimeoutLocked(true);
177 }
178 } break;
Dianne Hackborna750a632015-06-16 17:18:23 -0700179 case SCHEDULE_TEMP_WHITELIST_MSG: {
180 DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
181 if (dic != null) {
182 dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700183 msg.arg2, true, (String)msg.obj);
Dianne Hackborna750a632015-06-16 17:18:23 -0700184 }
185 } break;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800186 }
187 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800188 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800189
190 private final class AppNotResponding implements Runnable {
191 private final ProcessRecord mApp;
192 private final String mAnnotation;
193
194 public AppNotResponding(ProcessRecord app, String annotation) {
195 mApp = app;
196 mAnnotation = annotation;
197 }
198
199 @Override
200 public void run() {
Adrian Roos20d7df32016-01-12 18:59:43 +0100201 mService.mAppErrors.appNotResponding(mApp, null, null, false, mAnnotation);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800202 }
203 }
204
Jeff Brown6f357d32014-01-15 20:40:55 -0800205 BroadcastQueue(ActivityManagerService service, Handler handler,
206 String name, long timeoutPeriod, boolean allowDelayBehindServices) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800207 mService = service;
Jeff Brown6f357d32014-01-15 20:40:55 -0800208 mHandler = new BroadcastHandler(handler.getLooper());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800209 mQueueName = name;
210 mTimeoutPeriod = timeoutPeriod;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700211 mDelayBehindServices = allowDelayBehindServices;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800212 }
213
214 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);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700220 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800221 }
222
223 public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
224 mOrderedBroadcasts.add(r);
Jeff Brown9fb3fd12014-09-29 15:32:12 -0700225 r.enqueueClockTime = System.currentTimeMillis();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800226 }
227
228 public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700229 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700230 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn448489a2016-09-29 10:55:10 -0700231 final Intent curIntent = mParallelBroadcasts.get(i).intent;
Nimrod Gileadif2122f52016-10-06 19:25:11 +0100232 if (intent.filterEquals(curIntent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800233 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800234 "***** DROPPING PARALLEL ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700235 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800236 mParallelBroadcasts.set(i, r);
237 return true;
238 }
239 }
240 return false;
241 }
242
243 public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700244 final Intent intent = r.intent;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -0700245 for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700246 if (intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800247 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800248 "***** DROPPING ORDERED ["
Erik Wolsheimer5d34f002016-07-28 13:51:39 -0700249 + mQueueName + "]: " + intent);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800250 mOrderedBroadcasts.set(i, r);
251 return true;
252 }
253 }
254 return false;
255 }
256
257 private final void processCurBroadcastLocked(BroadcastRecord r,
258 ProcessRecord app) throws RemoteException {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800259 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800260 "Process cur broadcast " + r + " for app " + app);
261 if (app.thread == null) {
262 throw new RemoteException();
263 }
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700264 if (app.inFullBackup) {
265 skipReceiverLocked(r);
266 return;
267 }
268
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800269 r.receiver = app.thread.asBinder();
270 r.curApp = app;
271 app.curReceiver = r;
Dianne Hackborna413dc02013-07-12 12:02:55 -0700272 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborndb926082013-10-31 16:32:44 -0700273 mService.updateLruProcessLocked(app, false, null);
274 mService.updateOomAdjLocked();
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800275
276 // Tell the application to launch this receiver.
277 r.intent.setComponent(r.curComponent);
278
279 boolean started = false;
280 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800281 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800282 "Delivering to component " + r.curComponent
283 + ": " + r);
Brian Carlstromca82e612016-04-19 23:16:08 -0700284 mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
285 PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800286 app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
287 mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
Dianne Hackborna413dc02013-07-12 12:02:55 -0700288 r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
289 app.repProcState);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800290 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800291 "Process cur broadcast " + r + " DELIVERED for app " + app);
292 started = true;
293 } finally {
294 if (!started) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800295 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 "Process cur broadcast " + r + ": NOT STARTED!");
297 r.receiver = null;
298 r.curApp = null;
299 app.curReceiver = null;
300 }
301 }
302 }
303
304 public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
305 boolean didSomething = false;
306 final BroadcastRecord br = mPendingBroadcast;
307 if (br != null && br.curApp.pid == app.pid) {
Amith Yamasanid86e14e2016-08-05 15:25:03 -0700308 if (br.curApp != app) {
309 Slog.e(TAG, "App mismatch when sending pending broadcast to "
310 + app.processName + ", intended target is " + br.curApp.processName);
311 return false;
312 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800313 try {
314 mPendingBroadcast = null;
315 processCurBroadcastLocked(br, app);
316 didSomething = true;
317 } catch (Exception e) {
318 Slog.w(TAG, "Exception in new application when starting receiver "
319 + br.curComponent.flattenToShortString(), e);
320 logBroadcastReceiverDiscardLocked(br);
321 finishReceiverLocked(br, br.resultCode, br.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700322 br.resultExtras, br.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800323 scheduleBroadcastsLocked();
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700324 // We need to reset the state if we failed to start the receiver.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800325 br.state = BroadcastRecord.IDLE;
326 throw new RuntimeException(e.getMessage());
327 }
328 }
329 return didSomething;
330 }
331
332 public void skipPendingBroadcastLocked(int pid) {
333 final BroadcastRecord br = mPendingBroadcast;
334 if (br != null && br.curApp.pid == pid) {
335 br.state = BroadcastRecord.IDLE;
336 br.nextReceiver = mPendingBroadcastRecvIndex;
337 mPendingBroadcast = null;
338 scheduleBroadcastsLocked();
339 }
340 }
341
342 public void skipCurrentReceiverLocked(ProcessRecord app) {
Wale Ogunwale24b243d2015-07-17 07:20:57 -0700343 BroadcastRecord r = null;
344 if (mOrderedBroadcasts.size() > 0) {
345 BroadcastRecord br = mOrderedBroadcasts.get(0);
346 if (br.curApp == app) {
347 r = br;
348 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800349 }
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800350 if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800351 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800352 "[" + mQueueName + "] skip & discard pending app " + r);
riddle_hsu01eb7fa2015-03-04 17:27:05 +0800353 r = mPendingBroadcast;
354 }
355
356 if (r != null) {
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700357 skipReceiverLocked(r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800358 }
359 }
360
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700361 private void skipReceiverLocked(BroadcastRecord r) {
362 logBroadcastReceiverDiscardLocked(r);
363 finishReceiverLocked(r, r.resultCode, r.resultData,
364 r.resultExtras, r.resultAbort, false);
365 scheduleBroadcastsLocked();
366 }
367
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800368 public void scheduleBroadcastsLocked() {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800369 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800370 + mQueueName + "]: current="
371 + mBroadcastsScheduled);
372
373 if (mBroadcastsScheduled) {
374 return;
375 }
376 mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
377 mBroadcastsScheduled = true;
378 }
379
380 public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
381 if (mOrderedBroadcasts.size() > 0) {
382 final BroadcastRecord r = mOrderedBroadcasts.get(0);
383 if (r != null && r.receiver == receiver) {
384 return r;
385 }
386 }
387 return null;
388 }
389
390 public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
Dianne Hackborn6285a322013-09-18 12:09:47 -0700391 String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
392 final int state = r.state;
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700393 final ActivityInfo receiver = r.curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800394 r.state = BroadcastRecord.IDLE;
395 if (state == BroadcastRecord.IDLE) {
Dianne Hackborn6285a322013-09-18 12:09:47 -0700396 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800397 }
398 r.receiver = null;
399 r.intent.setComponent(null);
Guobin Zhang04d0bb62014-03-07 17:47:10 +0800400 if (r.curApp != null && r.curApp.curReceiver == r) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800401 r.curApp.curReceiver = null;
402 }
403 if (r.curFilter != null) {
404 r.curFilter.receiverList.curBroadcast = null;
405 }
406 r.curFilter = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800407 r.curReceiver = null;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700408 r.curApp = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800409 mPendingBroadcast = null;
410
411 r.resultCode = resultCode;
412 r.resultData = resultData;
413 r.resultExtras = resultExtras;
Dianne Hackborn6285a322013-09-18 12:09:47 -0700414 if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
415 r.resultAbort = resultAbort;
416 } else {
417 r.resultAbort = false;
418 }
419
420 if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
421 && r.queue.mOrderedBroadcasts.size() > 0
422 && r.queue.mOrderedBroadcasts.get(0) == r) {
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700423 ActivityInfo nextReceiver;
424 if (r.nextReceiver < r.receivers.size()) {
425 Object obj = r.receivers.get(r.nextReceiver);
426 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
427 } else {
428 nextReceiver = null;
429 }
430 // Don't do this if the next receive is in the same process as the current one.
431 if (receiver == null || nextReceiver == null
432 || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
433 || !receiver.processName.equals(nextReceiver.processName)) {
434 // In this case, we are ready to process the next receiver for the current broadcast,
435 // but are on a queue that would like to wait for services to finish before moving
436 // on. If there are background services currently starting, then we will go into a
437 // special state where we hold off on continuing this broadcast until they are done.
438 if (mService.mServices.hasBackgroundServices(r.userId)) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800439 Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700440 r.state = BroadcastRecord.WAITING_SERVICES;
441 return false;
442 }
Dianne Hackborn6285a322013-09-18 12:09:47 -0700443 }
444 }
445
446 r.curComponent = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800447
448 // We will process the next receiver right now if this is finishing
449 // an app receiver (which is always asynchronous) or after we have
450 // come back from calling a receiver.
451 return state == BroadcastRecord.APP_RECEIVE
452 || state == BroadcastRecord.CALL_DONE_RECEIVE;
453 }
454
Dianne Hackborn6285a322013-09-18 12:09:47 -0700455 public void backgroundServicesFinishedLocked(int userId) {
456 if (mOrderedBroadcasts.size() > 0) {
457 BroadcastRecord br = mOrderedBroadcasts.get(0);
458 if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800459 Slog.i(TAG, "Resuming delayed broadcast");
Dianne Hackborn6285a322013-09-18 12:09:47 -0700460 br.curComponent = null;
461 br.state = BroadcastRecord.IDLE;
462 processNextBroadcast(false);
463 }
464 }
465 }
466
Dianne Hackbornea05cd52016-06-20 11:22:40 -0700467 void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800468 Intent intent, int resultCode, String data, Bundle extras,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700469 boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800470 // Send the intent to the receiver asynchronously using one-way binder calls.
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000471 if (app != null) {
472 if (app.thread != null) {
473 // If we have an app thread, do the call through that so it is
474 // correctly ordered with other one-way calls.
Joe Onorato5869d1c2016-04-20 15:38:07 -0700475 try {
476 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
477 data, extras, ordered, sticky, sendingUser, app.repProcState);
478 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
479 // DeadObjectException when the process isn't actually dead.
480 //} catch (DeadObjectException ex) {
481 // Failed to call into the process. It's dying so just let it die and move on.
482 // throw ex;
483 } catch (RemoteException ex) {
484 // Failed to call into the process. It's either dying or wedged. Kill it gently.
485 synchronized (mService) {
486 Slog.w(TAG, "Can't deliver broadcast to " + app.processName
487 + " (pid " + app.pid + "). Crashing it.");
488 app.scheduleCrash("can't deliver broadcast");
489 }
490 throw ex;
491 }
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000492 } else {
493 // Application has died. Receiver doesn't exist.
494 throw new RemoteException("app.thread must not be null");
495 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800496 } else {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700497 receiver.performReceive(intent, resultCode, data, extras, ordered,
498 sticky, sendingUser);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800499 }
500 }
501
Svet Ganov99b60432015-06-27 13:15:22 -0700502 private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800503 BroadcastFilter filter, boolean ordered, int index) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800504 boolean skip = false;
Amith Yamasani8bf06ed2012-08-27 19:30:30 -0700505 if (filter.requiredPermission != null) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800506 int perm = mService.checkComponentPermission(filter.requiredPermission,
507 r.callingPid, r.callingUid, -1, true);
508 if (perm != PackageManager.PERMISSION_GRANTED) {
509 Slog.w(TAG, "Permission Denial: broadcasting "
510 + r.intent.toString()
511 + " from " + r.callerPackage + " (pid="
512 + r.callingPid + ", uid=" + r.callingUid + ")"
513 + " requires " + filter.requiredPermission
514 + " due to registered receiver " + filter);
515 skip = true;
Svet Ganov99b60432015-06-27 13:15:22 -0700516 } else {
517 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
518 if (opCode != AppOpsManager.OP_NONE
519 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
520 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
521 Slog.w(TAG, "Appop Denial: broadcasting "
522 + r.intent.toString()
523 + " from " + r.callerPackage + " (pid="
524 + r.callingPid + ", uid=" + r.callingUid + ")"
525 + " requires appop " + AppOpsManager.permissionToOp(
526 filter.requiredPermission)
527 + " due to registered receiver " + filter);
528 skip = true;
529 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800530 }
531 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700532 if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
533 for (int i = 0; i < r.requiredPermissions.length; i++) {
534 String requiredPermission = r.requiredPermissions[i];
535 int perm = mService.checkComponentPermission(requiredPermission,
536 filter.receiverList.pid, filter.receiverList.uid, -1, true);
537 if (perm != PackageManager.PERMISSION_GRANTED) {
538 Slog.w(TAG, "Permission Denial: receiving "
539 + r.intent.toString()
540 + " to " + filter.receiverList.app
541 + " (pid=" + filter.receiverList.pid
542 + ", uid=" + filter.receiverList.uid + ")"
543 + " requires " + requiredPermission
544 + " due to sender " + r.callerPackage
545 + " (uid " + r.callingUid + ")");
546 skip = true;
547 break;
548 }
549 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
Svetoslavfb9ec502015-09-01 14:45:18 -0700550 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700551 && mService.mAppOpsService.noteOperation(appOp,
552 filter.receiverList.uid, filter.packageName)
553 != AppOpsManager.MODE_ALLOWED) {
554 Slog.w(TAG, "Appop Denial: receiving "
555 + r.intent.toString()
556 + " to " + filter.receiverList.app
557 + " (pid=" + filter.receiverList.pid
558 + ", uid=" + filter.receiverList.uid + ")"
559 + " requires appop " + AppOpsManager.permissionToOp(
560 requiredPermission)
561 + " due to sender " + r.callerPackage
562 + " (uid " + r.callingUid + ")");
563 skip = true;
564 break;
565 }
566 }
567 }
568 if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
569 int perm = mService.checkComponentPermission(null,
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000570 filter.receiverList.pid, filter.receiverList.uid, -1, true);
571 if (perm != PackageManager.PERMISSION_GRANTED) {
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700572 Slog.w(TAG, "Permission Denial: security check failed when receiving "
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000573 + r.intent.toString()
574 + " to " + filter.receiverList.app
575 + " (pid=" + filter.receiverList.pid
576 + ", uid=" + filter.receiverList.uid + ")"
Fyodor Kupolove37520b2015-07-14 22:29:21 +0000577 + " due to sender " + r.callerPackage
578 + " (uid " + r.callingUid + ")");
579 skip = true;
580 }
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700581 }
582 if (!skip && r.appOp != AppOpsManager.OP_NONE
583 && mService.mAppOpsService.noteOperation(r.appOp,
584 filter.receiverList.uid, filter.packageName)
585 != AppOpsManager.MODE_ALLOWED) {
586 Slog.w(TAG, "Appop Denial: receiving "
587 + r.intent.toString()
588 + " to " + filter.receiverList.app
589 + " (pid=" + filter.receiverList.pid
590 + ", uid=" + filter.receiverList.uid + ")"
591 + " requires appop " + AppOpsManager.opToName(r.appOp)
592 + " due to sender " + r.callerPackage
593 + " (uid " + r.callingUid + ")");
594 skip = true;
Fyodor Kupolovb4e72832015-07-13 19:19:25 -0700595 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700596 if (!skip) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800597 final int allowed = mService.checkAllowBackgroundLocked(filter.receiverList.uid,
Dianne Hackborne91f3e72016-03-25 18:48:15 -0700598 filter.packageName, -1, true);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -0800599 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700600 Slog.w(TAG, "Background execution not allowed: receiving "
601 + r.intent
602 + " to " + filter.receiverList.app
603 + " (pid=" + filter.receiverList.pid
604 + ", uid=" + filter.receiverList.uid + ")");
605 skip = true;
606 }
607 }
Svet Ganov99b60432015-06-27 13:15:22 -0700608
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -0700609 if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
610 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800611 skip = true;
Ben Gruver49660c72013-08-06 19:54:08 -0700612 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800613
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800614 if (!skip && (filter.receiverList.app == null || filter.receiverList.app.crashing)) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700615 Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
616 + " to " + filter.receiverList + ": process crashing");
617 skip = true;
618 }
619
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800620 if (skip) {
621 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
622 return;
623 }
Svet Ganov9c165d72015-12-01 19:52:26 -0800624
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800625 // If permissions need a review before any of the app components can run, we drop
626 // the broadcast and if the calling app is in the foreground and the broadcast is
627 // explicit we launch the review UI passing it a pending intent to send the skipped
628 // broadcast.
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700629 if (mService.mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800630 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
631 filter.owningUserId)) {
632 r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
633 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800634 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800635 }
636
637 r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
638
639 // If this is not being sent as an ordered broadcast, then we
640 // don't want to touch the fields that keep track of the current
641 // state of ordered broadcasts.
642 if (ordered) {
643 r.receiver = filter.receiverList.receiver.asBinder();
644 r.curFilter = filter;
645 filter.receiverList.curBroadcast = r;
646 r.state = BroadcastRecord.CALL_IN_RECEIVE;
647 if (filter.receiverList.app != null) {
648 // Bump hosting application to no longer be in background
649 // scheduling class. Note that we can't do that if there
650 // isn't an app... but we can only be in that case for
651 // things that directly call the IActivityManager API, which
652 // are already core system stuff so don't matter for this.
653 r.curApp = filter.receiverList.app;
654 filter.receiverList.app.curReceiver = r;
655 mService.updateOomAdjLocked(r.curApp);
656 }
657 }
658 try {
659 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
660 "Delivering to " + filter + " : " + r);
Amith Yamasanib5f3b5c2016-05-16 14:23:04 -0700661 if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
662 // Skip delivery if full backup in progress
663 // If it's an ordered broadcast, we need to continue to the next receiver.
664 if (ordered) {
665 skipReceiverLocked(r);
666 }
667 } else {
668 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
669 new Intent(r.intent), r.resultCode, r.resultData,
670 r.resultExtras, r.ordered, r.initialSticky, r.userId);
671 }
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800672 if (ordered) {
673 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
674 }
675 } catch (RemoteException e) {
676 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
677 if (ordered) {
678 r.receiver = null;
679 r.curFilter = null;
680 filter.receiverList.curBroadcast = null;
681 if (filter.receiverList.app != null) {
682 filter.receiverList.app.curReceiver = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800683 }
684 }
685 }
686 }
687
Svet Ganov9c165d72015-12-01 19:52:26 -0800688 private boolean requestStartTargetPermissionsReviewIfNeededLocked(
689 BroadcastRecord receiverRecord, String receivingPackageName,
690 final int receivingUserId) {
691 if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
692 receivingPackageName, receivingUserId)) {
693 return true;
694 }
695
696 final boolean callerForeground = receiverRecord.callerApp != null
Dianne Hackborna49ad092016-03-03 13:39:10 -0800697 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
Svet Ganov9c165d72015-12-01 19:52:26 -0800698 : true;
699
700 // Show a permission review UI only for explicit broadcast from a foreground app
701 if (callerForeground && receiverRecord.intent.getComponent() != null) {
702 IIntentSender target = mService.getIntentSenderLocked(
703 ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
704 receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
705 new Intent[]{receiverRecord.intent},
706 new String[]{receiverRecord.intent.resolveType(mService.mContext
707 .getContentResolver())},
708 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
709 | PendingIntent.FLAG_IMMUTABLE, null);
710
711 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
712 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
713 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
714 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
715 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
716
717 if (DEBUG_PERMISSIONS_REVIEW) {
718 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
719 + receivingPackageName);
720 }
721
722 mHandler.post(new Runnable() {
723 @Override
724 public void run() {
725 mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
726 }
727 });
728 } else {
729 Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
730 + receivingPackageName + " requires a permissions review");
731 }
732
733 return false;
734 }
735
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700736 final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
Dianne Hackborna750a632015-06-16 17:18:23 -0700737 if (duration > Integer.MAX_VALUE) {
738 duration = Integer.MAX_VALUE;
739 }
740 // XXX ideally we should pause the broadcast until everything behind this is done,
741 // or else we will likely start dispatching the broadcast before we have opened
742 // access to the app (there is a lot of asynchronicity behind this). It is probably
743 // not that big a deal, however, because the main purpose here is to allow apps
744 // to hold wake locks, and they will be able to acquire their wake lock immediately
745 // it just won't be enabled until we get through this work.
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700746 StringBuilder b = new StringBuilder();
747 b.append("broadcast:");
748 UserHandle.formatUid(b, r.callingUid);
749 b.append(":");
750 if (r.intent.getAction() != null) {
751 b.append(r.intent.getAction());
752 } else if (r.intent.getComponent() != null) {
753 b.append(r.intent.getComponent().flattenToShortString());
754 } else if (r.intent.getData() != null) {
755 b.append(r.intent.getData());
756 }
757 mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
758 .sendToTarget();
Dianne Hackborna750a632015-06-16 17:18:23 -0700759 }
760
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800761 final void processNextBroadcast(boolean fromMsg) {
762 synchronized(mService) {
763 BroadcastRecord r;
764
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800765 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800766 + mQueueName + "]: "
767 + mParallelBroadcasts.size() + " broadcasts, "
768 + mOrderedBroadcasts.size() + " ordered broadcasts");
769
770 mService.updateCpuStats();
771
772 if (fromMsg) {
773 mBroadcastsScheduled = false;
774 }
775
776 // First, deliver any non-serialized broadcasts right away.
777 while (mParallelBroadcasts.size() > 0) {
778 r = mParallelBroadcasts.remove(0);
779 r.dispatchTime = SystemClock.uptimeMillis();
780 r.dispatchClockTime = System.currentTimeMillis();
781 final int N = r.receivers.size();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800782 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800783 + mQueueName + "] " + r);
784 for (int i=0; i<N; i++) {
785 Object target = r.receivers.get(i);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800786 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800787 "Delivering non-ordered on [" + mQueueName + "] to registered "
788 + target + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800789 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800790 }
791 addBroadcastToHistoryLocked(r);
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800792 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800793 + mQueueName + "] " + r);
794 }
795
796 // Now take care of the next serialized one...
797
798 // If we are waiting for a process to come up to handle the next
799 // broadcast, then do nothing at this point. Just in case, we
800 // check that the process we're waiting for still exists.
801 if (mPendingBroadcast != null) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700802 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
803 "processNextBroadcast [" + mQueueName + "]: waiting for "
804 + mPendingBroadcast.curApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800805
806 boolean isDead;
807 synchronized (mService.mPidsSelfLocked) {
Dianne Hackborn9357b112013-10-03 18:27:48 -0700808 ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
809 isDead = proc == null || proc.crashing;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800810 }
811 if (!isDead) {
812 // It's still alive, so keep waiting
813 return;
814 } else {
815 Slog.w(TAG, "pending app ["
816 + mQueueName + "]" + mPendingBroadcast.curApp
817 + " died before responding to broadcast");
818 mPendingBroadcast.state = BroadcastRecord.IDLE;
819 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
820 mPendingBroadcast = null;
821 }
822 }
823
824 boolean looped = false;
825
826 do {
827 if (mOrderedBroadcasts.size() == 0) {
828 // No more broadcasts pending, so all done!
829 mService.scheduleAppGcsLocked();
830 if (looped) {
831 // If we had finished the last ordered broadcast, then
832 // make sure all processes have correct oom and sched
833 // adjustments.
834 mService.updateOomAdjLocked();
835 }
836 return;
837 }
838 r = mOrderedBroadcasts.get(0);
839 boolean forceReceive = false;
840
841 // Ensure that even if something goes awry with the timeout
842 // detection, we catch "hung" broadcasts here, discard them,
843 // and continue to make progress.
844 //
845 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
846 // receivers don't get executed with timeouts. They're intended for
847 // one time heavy lifting after system upgrades and can take
848 // significant amounts of time.
849 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
850 if (mService.mProcessesReady && r.dispatchTime > 0) {
851 long now = SystemClock.uptimeMillis();
852 if ((numReceivers > 0) &&
853 (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
854 Slog.w(TAG, "Hung broadcast ["
855 + mQueueName + "] discarded after timeout failure:"
856 + " now=" + now
857 + " dispatchTime=" + r.dispatchTime
858 + " startTime=" + r.receiverTime
859 + " intent=" + r.intent
860 + " numReceivers=" + numReceivers
861 + " nextReceiver=" + r.nextReceiver
862 + " state=" + r.state);
863 broadcastTimeoutLocked(false); // forcibly finish this broadcast
864 forceReceive = true;
865 r.state = BroadcastRecord.IDLE;
866 }
867 }
868
869 if (r.state != BroadcastRecord.IDLE) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800870 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800871 "processNextBroadcast("
872 + mQueueName + ") called when not idle (state="
873 + r.state + ")");
874 return;
875 }
876
877 if (r.receivers == null || r.nextReceiver >= numReceivers
878 || r.resultAbort || forceReceive) {
879 // No more receivers for this broadcast! Send the final
880 // result if requested...
881 if (r.resultTo != null) {
882 try {
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800883 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
Todd Kennedyd2f15112015-01-21 15:25:56 -0800884 "Finishing broadcast [" + mQueueName + "] "
885 + r.intent.getAction() + " app=" + r.callerApp);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800886 performReceiveLocked(r.callerApp, r.resultTo,
887 new Intent(r.intent), r.resultCode,
Dianne Hackborn20e80982012-08-31 19:00:44 -0700888 r.resultData, r.resultExtras, false, false, r.userId);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800889 // Set this to null so that the reference
Dianne Hackborn9357b112013-10-03 18:27:48 -0700890 // (local and remote) isn't kept in the mBroadcastHistory.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800891 r.resultTo = null;
892 } catch (RemoteException e) {
Craig Mautner38c1a5f2014-07-21 15:36:37 +0000893 r.resultTo = null;
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800894 Slog.w(TAG, "Failure ["
895 + mQueueName + "] sending broadcast result of "
896 + r.intent, e);
Joe Onorato5869d1c2016-04-20 15:38:07 -0700897
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800898 }
899 }
900
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800901 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800902 cancelBroadcastTimeoutLocked();
903
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -0700904 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
905 "Finished with ordered broadcast " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800906
907 // ... and on to the next...
908 addBroadcastToHistoryLocked(r);
Dianne Hackbornbc02a392016-06-02 17:15:08 -0700909 if (r.intent.getComponent() == null && r.intent.getPackage() == null
910 && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
911 // This was an implicit broadcast... let's record it for posterity.
912 mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
913 r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
914 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800915 mOrderedBroadcasts.remove(0);
916 r = null;
917 looped = true;
918 continue;
919 }
920 } while (r == null);
921
922 // Get the next receiver...
923 int recIdx = r.nextReceiver++;
924
925 // Keep track of when this receiver started, and make sure there
926 // is a timeout message pending to kill it if need be.
927 r.receiverTime = SystemClock.uptimeMillis();
928 if (recIdx == 0) {
929 r.dispatchTime = r.receiverTime;
930 r.dispatchClockTime = System.currentTimeMillis();
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800931 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800932 + mQueueName + "] " + r);
933 }
934 if (! mPendingBroadcastTimeoutMessage) {
935 long timeoutTime = r.receiverTime + mTimeoutPeriod;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800936 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800937 "Submitting BROADCAST_TIMEOUT_MSG ["
938 + mQueueName + "] for " + r + " at " + timeoutTime);
939 setBroadcastTimeoutLocked(timeoutTime);
940 }
941
Dianne Hackborna750a632015-06-16 17:18:23 -0700942 final BroadcastOptions brOptions = r.options;
943 final Object nextReceiver = r.receivers.get(recIdx);
944
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800945 if (nextReceiver instanceof BroadcastFilter) {
946 // Simple case: this is a registered receiver who gets
947 // a direct call.
948 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800949 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800950 "Delivering ordered ["
951 + mQueueName + "] to registered "
952 + filter + ": " + r);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800953 deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800954 if (r.receiver == null || !r.ordered) {
955 // The receiver has already finished, so schedule to
956 // process the next one.
Wale Ogunwaled57969f2014-11-15 19:37:29 -0800957 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800958 + mQueueName + "]: ordered="
959 + r.ordered + " receiver=" + r.receiver);
960 r.state = BroadcastRecord.IDLE;
961 scheduleBroadcastsLocked();
Dianne Hackborna750a632015-06-16 17:18:23 -0700962 } else {
963 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
964 scheduleTempWhitelistLocked(filter.owningUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700965 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -0700966 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800967 }
968 return;
969 }
970
971 // Hard case: need to instantiate the receiver, possibly
972 // starting its application process to host it.
973
974 ResolveInfo info =
975 (ResolveInfo)nextReceiver;
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700976 ComponentName component = new ComponentName(
977 info.activityInfo.applicationInfo.packageName,
978 info.activityInfo.name);
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800979
980 boolean skip = false;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800981 if (brOptions != null &&
982 (info.activityInfo.applicationInfo.targetSdkVersion
983 < brOptions.getMinManifestReceiverApiLevel() ||
984 info.activityInfo.applicationInfo.targetSdkVersion
985 > brOptions.getMaxManifestReceiverApiLevel())) {
986 skip = true;
987 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800988 int perm = mService.checkComponentPermission(info.activityInfo.permission,
989 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
990 info.activityInfo.exported);
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800991 if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800992 if (!info.activityInfo.exported) {
993 Slog.w(TAG, "Permission Denial: broadcasting "
994 + r.intent.toString()
995 + " from " + r.callerPackage + " (pid=" + r.callingPid
996 + ", uid=" + r.callingUid + ")"
997 + " is not exported from uid " + info.activityInfo.applicationInfo.uid
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700998 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800999 } else {
1000 Slog.w(TAG, "Permission Denial: broadcasting "
1001 + r.intent.toString()
1002 + " from " + r.callerPackage + " (pid=" + r.callingPid
1003 + ", uid=" + r.callingUid + ")"
1004 + " requires " + info.activityInfo.permission
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001005 + " due to receiver " + component.flattenToShortString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001006 }
1007 skip = true;
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001008 } else if (!skip && info.activityInfo.permission != null) {
Svet Ganov99b60432015-06-27 13:15:22 -07001009 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1010 if (opCode != AppOpsManager.OP_NONE
1011 && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1012 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1013 Slog.w(TAG, "Appop Denial: broadcasting "
1014 + r.intent.toString()
1015 + " from " + r.callerPackage + " (pid="
1016 + r.callingPid + ", uid=" + r.callingUid + ")"
1017 + " requires appop " + AppOpsManager.permissionToOp(
1018 info.activityInfo.permission)
1019 + " due to registered receiver "
1020 + component.flattenToShortString());
1021 skip = true;
1022 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001023 }
Svet Ganov99b60432015-06-27 13:15:22 -07001024 if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001025 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1026 for (int i = 0; i < r.requiredPermissions.length; i++) {
1027 String requiredPermission = r.requiredPermissions[i];
1028 try {
1029 perm = AppGlobals.getPackageManager().
1030 checkPermission(requiredPermission,
1031 info.activityInfo.applicationInfo.packageName,
1032 UserHandle
1033 .getUserId(info.activityInfo.applicationInfo.uid));
1034 } catch (RemoteException e) {
1035 perm = PackageManager.PERMISSION_DENIED;
1036 }
1037 if (perm != PackageManager.PERMISSION_GRANTED) {
1038 Slog.w(TAG, "Permission Denial: receiving "
1039 + r.intent + " to "
1040 + component.flattenToShortString()
1041 + " requires " + requiredPermission
1042 + " due to sender " + r.callerPackage
1043 + " (uid " + r.callingUid + ")");
1044 skip = true;
1045 break;
1046 }
1047 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1048 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1049 && mService.mAppOpsService.noteOperation(appOp,
Fyodor Kupolove37520b2015-07-14 22:29:21 +00001050 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001051 != AppOpsManager.MODE_ALLOWED) {
1052 Slog.w(TAG, "Appop Denial: receiving "
1053 + r.intent + " to "
1054 + component.flattenToShortString()
1055 + " requires appop " + AppOpsManager.permissionToOp(
1056 requiredPermission)
1057 + " due to sender " + r.callerPackage
1058 + " (uid " + r.callingUid + ")");
1059 skip = true;
1060 break;
1061 }
1062 }
1063 }
1064 if (!skip && r.appOp != AppOpsManager.OP_NONE
1065 && mService.mAppOpsService.noteOperation(r.appOp,
1066 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1067 != AppOpsManager.MODE_ALLOWED) {
Svet Ganov99b60432015-06-27 13:15:22 -07001068 Slog.w(TAG, "Appop Denial: receiving "
1069 + r.intent + " to "
1070 + component.flattenToShortString()
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001071 + " requires appop " + AppOpsManager.opToName(r.appOp)
Svet Ganov99b60432015-06-27 13:15:22 -07001072 + " due to sender " + r.callerPackage
1073 + " (uid " + r.callingUid + ")");
1074 skip = true;
1075 }
Ben Gruver49660c72013-08-06 19:54:08 -07001076 if (!skip) {
1077 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1078 r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1079 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001080 boolean isSingleton = false;
1081 try {
1082 isSingleton = mService.isSingleton(info.activityInfo.processName,
1083 info.activityInfo.applicationInfo,
1084 info.activityInfo.name, info.activityInfo.flags);
1085 } catch (SecurityException e) {
1086 Slog.w(TAG, e.getMessage());
1087 skip = true;
1088 }
1089 if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1090 if (ActivityManager.checkUidPermission(
1091 android.Manifest.permission.INTERACT_ACROSS_USERS,
1092 info.activityInfo.applicationInfo.uid)
1093 != PackageManager.PERMISSION_GRANTED) {
1094 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1095 + " requests FLAG_SINGLE_USER, but app does not hold "
1096 + android.Manifest.permission.INTERACT_ACROSS_USERS);
1097 skip = true;
1098 }
1099 }
Dianne Hackbornbc02a392016-06-02 17:15:08 -07001100 if (!skip) {
1101 r.manifestCount++;
1102 } else {
1103 r.manifestSkipCount++;
1104 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001105 if (r.curApp != null && r.curApp.crashing) {
1106 // If the target process is crashing, just skip it.
Dianne Hackborn9357b112013-10-03 18:27:48 -07001107 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1108 + " to " + r.curApp + ": process crashing");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001109 skip = true;
1110 }
Christopher Tateba629da2013-11-13 17:42:28 -08001111 if (!skip) {
1112 boolean isAvailable = false;
1113 try {
1114 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1115 info.activityInfo.packageName,
1116 UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1117 } catch (Exception e) {
1118 // all such failures mean we skip this receiver
1119 Slog.w(TAG, "Exception getting recipient info for "
1120 + info.activityInfo.packageName, e);
1121 }
1122 if (!isAvailable) {
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001123 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1124 "Skipping delivery to " + info.activityInfo.packageName + " / "
1125 + info.activityInfo.applicationInfo.uid
1126 + " : package no longer available");
Christopher Tateba629da2013-11-13 17:42:28 -08001127 skip = true;
1128 }
1129 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001130
Svet Ganov9c165d72015-12-01 19:52:26 -08001131 // If permissions need a review before any of the app components can run, we drop
1132 // the broadcast and if the calling app is in the foreground and the broadcast is
1133 // explicit we launch the review UI passing it a pending intent to send the skipped
1134 // broadcast.
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -07001135 if ((mService.mPermissionReviewRequired
1136 || Build.PERMISSIONS_REVIEW_REQUIRED) && !skip) {
Svet Ganov9c165d72015-12-01 19:52:26 -08001137 if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1138 info.activityInfo.packageName, UserHandle.getUserId(
1139 info.activityInfo.applicationInfo.uid))) {
1140 skip = true;
1141 }
1142 }
1143
Dianne Hackborn76e80092015-12-09 14:15:34 -08001144 // This is safe to do even if we are skipping the broadcast, and we need
1145 // this information now to evaluate whether it is going to be allowed to run.
1146 final int receiverUid = info.activityInfo.applicationInfo.uid;
1147 // If it's a singleton, it needs to be the same app or a special app
1148 if (r.callingUid != Process.SYSTEM_UID && isSingleton
1149 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1150 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1151 }
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001152 String targetProcess = info.activityInfo.processName;
1153 ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1154 info.activityInfo.applicationInfo.uid, false);
Dianne Hackborn76e80092015-12-09 14:15:34 -08001155
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001156 if (!skip) {
1157 final int allowed = mService.checkAllowBackgroundLocked(
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001158 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, -1,
1159 false);
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001160 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1161 // We won't allow this receiver to be launched if the app has been
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001162 // completely disabled from launches, or it was not explicitly sent
1163 // to it and the app is in a state that should not receive it
1164 // (depending on how checkAllowBackgroundLocked has determined that).
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001165 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1166 Slog.w(TAG, "Background execution disabled: receiving "
1167 + r.intent + " to "
1168 + component.flattenToShortString());
1169 skip = true;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001170 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001171 || (r.intent.getComponent() == null
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001172 && r.intent.getPackage() == null
Dianne Hackborn6ac42ae2015-12-08 17:22:10 -08001173 && ((r.intent.getFlags()
1174 & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0))) {
Dianne Hackborn2639c4b2015-12-04 13:11:09 -08001175 Slog.w(TAG, "Background execution not allowed: receiving "
1176 + r.intent + " to "
1177 + component.flattenToShortString());
1178 skip = true;
1179 }
1180 }
1181 }
1182
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001183 if (skip) {
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001184 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Wale Ogunwale3c36b8e2015-03-09 10:18:51 -07001185 "Skipping delivery of ordered [" + mQueueName + "] "
1186 + r + " for whatever reason");
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001187 r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001188 r.receiver = null;
1189 r.curFilter = null;
1190 r.state = BroadcastRecord.IDLE;
1191 scheduleBroadcastsLocked();
1192 return;
1193 }
1194
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001195 r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001196 r.state = BroadcastRecord.APP_RECEIVE;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001197 r.curComponent = component;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001198 r.curReceiver = info.activityInfo;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001199 if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001200 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1201 + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1202 + info.activityInfo.applicationInfo.uid);
1203 }
1204
Dianne Hackborna750a632015-06-16 17:18:23 -07001205 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1206 scheduleTempWhitelistLocked(receiverUid,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001207 brOptions.getTemporaryAppWhitelistDuration(), r);
Dianne Hackborna750a632015-06-16 17:18:23 -07001208 }
1209
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001210 // Broadcast is being executed, its package can't be stopped.
1211 try {
1212 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001213 r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001214 } catch (RemoteException e) {
1215 } catch (IllegalArgumentException e) {
1216 Slog.w(TAG, "Failed trying to unstop package "
1217 + r.curComponent.getPackageName() + ": " + e);
1218 }
1219
1220 // Is this receiver's application already running?
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001221 if (app != null && app.thread != null) {
1222 try {
Dianne Hackbornf7097a52014-05-13 09:56:14 -07001223 app.addPackage(info.activityInfo.packageName,
1224 info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001225 processCurBroadcastLocked(r, app);
1226 return;
1227 } catch (RemoteException e) {
1228 Slog.w(TAG, "Exception when sending broadcast to "
1229 + r.curComponent, e);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001230 } catch (RuntimeException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07001231 Slog.wtf(TAG, "Failed sending broadcast to "
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001232 + r.curComponent + " with " + r.intent, e);
1233 // If some unexpected exception happened, just skip
1234 // this broadcast. At this point we are not in the call
1235 // from a client, so throwing an exception out from here
1236 // will crash the entire system instead of just whoever
1237 // sent the broadcast.
1238 logBroadcastReceiverDiscardLocked(r);
1239 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001240 r.resultExtras, r.resultAbort, false);
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001241 scheduleBroadcastsLocked();
1242 // We need to reset the state if we failed to start the receiver.
1243 r.state = BroadcastRecord.IDLE;
1244 return;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001245 }
1246
1247 // If a dead object exception was thrown -- fall through to
1248 // restart the application.
1249 }
1250
1251 // Not running -- get it started, to be executed when the app comes up.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001252 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001253 "Need to start app ["
1254 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1255 if ((r.curApp=mService.startProcessLocked(targetProcess,
1256 info.activityInfo.applicationInfo, true,
1257 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1258 "broadcast", r.curComponent,
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001259 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001260 == null) {
1261 // Ah, this recipient is unavailable. Finish it if necessary,
1262 // and mark the broadcast record as ready for the next.
1263 Slog.w(TAG, "Unable to launch app "
1264 + info.activityInfo.applicationInfo.packageName + "/"
1265 + info.activityInfo.applicationInfo.uid + " for broadcast "
1266 + r.intent + ": process is bad");
1267 logBroadcastReceiverDiscardLocked(r);
1268 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001269 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001270 scheduleBroadcastsLocked();
1271 r.state = BroadcastRecord.IDLE;
1272 return;
1273 }
1274
1275 mPendingBroadcast = r;
1276 mPendingBroadcastRecvIndex = recIdx;
1277 }
1278 }
1279
1280 final void setBroadcastTimeoutLocked(long timeoutTime) {
1281 if (! mPendingBroadcastTimeoutMessage) {
1282 Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1283 mHandler.sendMessageAtTime(msg, timeoutTime);
1284 mPendingBroadcastTimeoutMessage = true;
1285 }
1286 }
1287
1288 final void cancelBroadcastTimeoutLocked() {
1289 if (mPendingBroadcastTimeoutMessage) {
1290 mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1291 mPendingBroadcastTimeoutMessage = false;
1292 }
1293 }
1294
1295 final void broadcastTimeoutLocked(boolean fromMsg) {
1296 if (fromMsg) {
1297 mPendingBroadcastTimeoutMessage = false;
1298 }
1299
1300 if (mOrderedBroadcasts.size() == 0) {
1301 return;
1302 }
1303
1304 long now = SystemClock.uptimeMillis();
1305 BroadcastRecord r = mOrderedBroadcasts.get(0);
1306 if (fromMsg) {
1307 if (mService.mDidDexOpt) {
1308 // Delay timeouts until dexopt finishes.
1309 mService.mDidDexOpt = false;
1310 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1311 setBroadcastTimeoutLocked(timeoutTime);
1312 return;
1313 }
1314 if (!mService.mProcessesReady) {
1315 // Only process broadcast timeouts if the system is ready. That way
1316 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1317 // to do heavy lifting for system up.
1318 return;
1319 }
1320
1321 long timeoutTime = r.receiverTime + mTimeoutPeriod;
1322 if (timeoutTime > now) {
1323 // We can observe premature timeouts because we do not cancel and reset the
1324 // broadcast timeout message after each receiver finishes. Instead, we set up
1325 // an initial timeout then kick it down the road a little further as needed
1326 // when it expires.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001327 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001328 "Premature timeout ["
1329 + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1330 + timeoutTime);
1331 setBroadcastTimeoutLocked(timeoutTime);
1332 return;
1333 }
1334 }
1335
Dianne Hackborn6285a322013-09-18 12:09:47 -07001336 BroadcastRecord br = mOrderedBroadcasts.get(0);
1337 if (br.state == BroadcastRecord.WAITING_SERVICES) {
1338 // In this case the broadcast had already finished, but we had decided to wait
1339 // for started services to finish as well before going on. So if we have actually
1340 // waited long enough time timeout the broadcast, let's give up on the whole thing
1341 // and just move on to the next.
Wale Ogunwaled57969f2014-11-15 19:37:29 -08001342 Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
Dianne Hackborn6285a322013-09-18 12:09:47 -07001343 ? br.curComponent.flattenToShortString() : "(null)"));
1344 br.curComponent = null;
1345 br.state = BroadcastRecord.IDLE;
1346 processNextBroadcast(false);
1347 return;
1348 }
1349
1350 Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001351 + ", started " + (now - r.receiverTime) + "ms ago");
1352 r.receiverTime = now;
1353 r.anrCount++;
1354
1355 // Current receiver has passed its expiration date.
1356 if (r.nextReceiver <= 0) {
1357 Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1358 return;
1359 }
1360
1361 ProcessRecord app = null;
1362 String anrMessage = null;
1363
1364 Object curReceiver = r.receivers.get(r.nextReceiver-1);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001365 r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001366 Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1367 logBroadcastReceiverDiscardLocked(r);
1368 if (curReceiver instanceof BroadcastFilter) {
1369 BroadcastFilter bf = (BroadcastFilter)curReceiver;
1370 if (bf.receiverList.pid != 0
1371 && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1372 synchronized (mService.mPidsSelfLocked) {
1373 app = mService.mPidsSelfLocked.get(
1374 bf.receiverList.pid);
1375 }
1376 }
1377 } else {
1378 app = r.curApp;
1379 }
1380
1381 if (app != null) {
1382 anrMessage = "Broadcast of " + r.intent.toString();
1383 }
1384
1385 if (mPendingBroadcast == r) {
1386 mPendingBroadcast = null;
1387 }
1388
1389 // Move on to the next receiver.
1390 finishReceiverLocked(r, r.resultCode, r.resultData,
Dianne Hackborn6285a322013-09-18 12:09:47 -07001391 r.resultExtras, r.resultAbort, false);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001392 scheduleBroadcastsLocked();
1393
1394 if (anrMessage != null) {
1395 // Post the ANR to the handler since we do not want to process ANRs while
1396 // potentially holding our lock.
1397 mHandler.post(new AppNotResponding(app, anrMessage));
1398 }
1399 }
1400
Christopher Tatef278f122015-04-22 13:12:01 -07001401 private final int ringAdvance(int x, final int increment, final int ringSize) {
1402 x += increment;
1403 if (x < 0) return (ringSize - 1);
1404 else if (x >= ringSize) return 0;
1405 else return x;
1406 }
1407
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001408 private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1409 if (r.callingUid < 0) {
1410 // This was from a registerReceiver() call; ignore it.
1411 return;
1412 }
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001413 r.finishTime = SystemClock.uptimeMillis();
Christopher Tatef278f122015-04-22 13:12:01 -07001414
1415 mBroadcastHistory[mHistoryNext] = r;
1416 mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1417
1418 mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1419 mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1420 mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1421 mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1422 mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001423 }
1424
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001425 boolean cleanupDisabledPackageReceiversLocked(
1426 String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1427 boolean didSomething = false;
1428 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1429 didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1430 packageName, filterByClasses, userId, doit);
1431 if (!doit && didSomething) {
1432 return true;
1433 }
1434 }
1435
1436 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1437 didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1438 packageName, filterByClasses, userId, doit);
1439 if (!doit && didSomething) {
1440 return true;
1441 }
1442 }
1443
1444 return didSomething;
1445 }
1446
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001447 final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001448 final int logIndex = r.nextReceiver - 1;
1449 if (logIndex >= 0 && logIndex < r.receivers.size()) {
1450 Object curReceiver = r.receivers.get(logIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001451 if (curReceiver instanceof BroadcastFilter) {
1452 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1453 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001454 bf.owningUserId, System.identityHashCode(r),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001455 r.intent.getAction(), logIndex, System.identityHashCode(bf));
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001456 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001457 ResolveInfo ri = (ResolveInfo) curReceiver;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001458 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001459 UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001460 System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001461 }
1462 } else {
Wale Ogunwalea22c6322015-06-03 09:59:45 -07001463 if (logIndex < 0) Slog.w(TAG,
1464 "Discarding broadcast before first receiver is invoked: " + r);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001465 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001466 -1, System.identityHashCode(r),
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001467 r.intent.getAction(),
1468 r.nextReceiver,
1469 "NONE");
1470 }
1471 }
1472
1473 final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1474 int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001475 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001476 if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1477 || mPendingBroadcast != null) {
1478 boolean printed = false;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001479 for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001480 BroadcastRecord br = mParallelBroadcasts.get(i);
1481 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1482 continue;
1483 }
1484 if (!printed) {
1485 if (needSep) {
1486 pw.println();
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001488 needSep = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001489 printed = true;
1490 pw.println(" Active broadcasts [" + mQueueName + "]:");
1491 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001492 pw.println(" Active Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001493 br.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001494 }
1495 printed = false;
1496 needSep = true;
Wale Ogunwaleca1c1252015-05-15 12:49:13 -07001497 for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001498 BroadcastRecord br = mOrderedBroadcasts.get(i);
1499 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1500 continue;
1501 }
1502 if (!printed) {
1503 if (needSep) {
1504 pw.println();
1505 }
1506 needSep = true;
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001507 printed = true;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001508 pw.println(" Active ordered broadcasts [" + mQueueName + "]:");
1509 }
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001510 pw.println(" Active Ordered Broadcast " + mQueueName + " #" + i + ":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001511 mOrderedBroadcasts.get(i).dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001512 }
1513 if (dumpPackage == null || (mPendingBroadcast != null
1514 && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1515 if (needSep) {
1516 pw.println();
1517 }
1518 pw.println(" Pending broadcast [" + mQueueName + "]:");
1519 if (mPendingBroadcast != null) {
Dianne Hackborn865907d2015-10-21 17:12:53 -07001520 mPendingBroadcast.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001521 } else {
1522 pw.println(" (null)");
1523 }
1524 needSep = true;
1525 }
1526 }
1527
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001528 int i;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001529 boolean printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001530
1531 i = -1;
1532 int lastIndex = mHistoryNext;
1533 int ringIndex = lastIndex;
1534 do {
1535 // increasing index = more recent entry, and we want to print the most
1536 // recent first and work backwards, so we roll through the ring backwards.
1537 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1538 BroadcastRecord r = mBroadcastHistory[ringIndex];
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001539 if (r == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001540 continue;
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001541 }
Christopher Tatef278f122015-04-22 13:12:01 -07001542
1543 i++; // genuine record of some sort even if we're filtering it out
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001544 if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1545 continue;
1546 }
1547 if (!printed) {
1548 if (needSep) {
1549 pw.println();
1550 }
1551 needSep = true;
1552 pw.println(" Historical broadcasts [" + mQueueName + "]:");
1553 printed = true;
1554 }
1555 if (dumpAll) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -07001556 pw.print(" Historical Broadcast " + mQueueName + " #");
1557 pw.print(i); pw.println(":");
Dianne Hackborn865907d2015-10-21 17:12:53 -07001558 r.dump(pw, " ", sdf);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001559 } else {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001560 pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r);
1561 pw.print(" ");
1562 pw.println(r.intent.toShortString(false, true, true, false));
Dianne Hackborna40cfeb2013-03-25 17:49:36 -07001563 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1564 pw.print(" targetComp: "); pw.println(r.targetComp.toShortString());
1565 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001566 Bundle bundle = r.intent.getExtras();
1567 if (bundle != null) {
1568 pw.print(" extras: "); pw.println(bundle.toString());
1569 }
1570 }
Christopher Tatef278f122015-04-22 13:12:01 -07001571 } while (ringIndex != lastIndex);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001572
1573 if (dumpPackage == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001574 lastIndex = ringIndex = mSummaryHistoryNext;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001575 if (dumpAll) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001576 printed = false;
Christopher Tatef278f122015-04-22 13:12:01 -07001577 i = -1;
1578 } else {
1579 // roll over the 'i' full dumps that have already been issued
1580 for (int j = i;
1581 j > 0 && ringIndex != lastIndex;) {
1582 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1583 BroadcastRecord r = mBroadcastHistory[ringIndex];
1584 if (r == null) {
1585 continue;
1586 }
1587 j--;
1588 }
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001589 }
Christopher Tatef278f122015-04-22 13:12:01 -07001590 // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1591 // the overall broadcast history.
Christopher Tatef278f122015-04-22 13:12:01 -07001592 do {
1593 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1594 Intent intent = mBroadcastSummaryHistory[ringIndex];
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001595 if (intent == null) {
Christopher Tatef278f122015-04-22 13:12:01 -07001596 continue;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001597 }
1598 if (!printed) {
1599 if (needSep) {
1600 pw.println();
1601 }
1602 needSep = true;
1603 pw.println(" Historical broadcasts summary [" + mQueueName + "]:");
1604 printed = true;
1605 }
1606 if (!dumpAll && i >= 50) {
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001607 pw.println(" ...");
1608 break;
1609 }
Christopher Tatef278f122015-04-22 13:12:01 -07001610 i++;
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001611 pw.print(" #"); pw.print(i); pw.print(": ");
1612 pw.println(intent.toShortString(false, true, true, false));
Dianne Hackborn865907d2015-10-21 17:12:53 -07001613 pw.print(" ");
1614 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
1615 - mSummaryHistoryEnqueueTime[ringIndex], pw);
1616 pw.print(" dispatch ");
1617 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
1618 - mSummaryHistoryDispatchTime[ringIndex], pw);
1619 pw.println(" finish");
1620 pw.print(" enq=");
1621 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1622 pw.print(" disp=");
1623 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1624 pw.print(" fin=");
1625 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001626 Bundle bundle = intent.getExtras();
1627 if (bundle != null) {
1628 pw.print(" extras: "); pw.println(bundle.toString());
1629 }
Christopher Tatef278f122015-04-22 13:12:01 -07001630 } while (ringIndex != lastIndex);
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001631 }
1632
1633 return needSep;
1634 }
1635}