• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 package com.android.server.am;
18 
19 import static com.android.server.am.ActivityManagerDebugConfig.*;
20 
21 import android.app.ActivityManager;
22 import android.app.AppGlobals;
23 import android.app.AppOpsManager;
24 import android.app.BroadcastOptions;
25 import android.app.PendingIntent;
26 import android.content.ComponentName;
27 import android.content.ContentResolver;
28 import android.content.IIntentReceiver;
29 import android.content.IIntentSender;
30 import android.content.Intent;
31 import android.content.IntentSender;
32 import android.content.pm.ActivityInfo;
33 import android.content.pm.IPackageManager;
34 import android.content.pm.PackageManager;
35 import android.content.pm.PermissionInfo;
36 import android.content.pm.ResolveInfo;
37 import android.os.Bundle;
38 import android.os.Handler;
39 import android.os.IBinder;
40 import android.os.Looper;
41 import android.os.Message;
42 import android.os.Process;
43 import android.os.RemoteException;
44 import android.os.SystemClock;
45 import android.os.Trace;
46 import android.os.UserHandle;
47 import android.util.EventLog;
48 import android.util.Slog;
49 import android.util.SparseIntArray;
50 import android.util.StatsLog;
51 import android.util.TimeUtils;
52 import android.util.proto.ProtoOutputStream;
53 
54 import java.io.FileDescriptor;
55 import java.io.PrintWriter;
56 import java.text.SimpleDateFormat;
57 import java.util.ArrayList;
58 import java.util.Date;
59 import java.util.Set;
60 
61 /**
62  * BROADCASTS
63  *
64  * We keep three broadcast queues and associated bookkeeping, one for those at
65  * foreground priority, and one for normal (background-priority) broadcasts, and one to
66  * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED.
67  */
68 public final class BroadcastQueue {
69     private static final String TAG = "BroadcastQueue";
70     private static final String TAG_MU = TAG + POSTFIX_MU;
71     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
72 
73     static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
74     static final int MAX_BROADCAST_SUMMARY_HISTORY
75             = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
76 
77     final ActivityManagerService mService;
78 
79     /**
80      * Behavioral parameters such as timeouts and deferral policy, tracking Settings
81      * for runtime configurability
82      */
83     final BroadcastConstants mConstants;
84 
85     /**
86      * Recognizable moniker for this queue
87      */
88     final String mQueueName;
89 
90     /**
91      * If true, we can delay broadcasts while waiting services to finish in the previous
92      * receiver's process.
93      */
94     final boolean mDelayBehindServices;
95 
96     /**
97      * Lists of all active broadcasts that are to be executed immediately
98      * (without waiting for another broadcast to finish).  Currently this only
99      * contains broadcasts to registered receivers, to avoid spinning up
100      * a bunch of processes to execute IntentReceiver components.  Background-
101      * and foreground-priority broadcasts are queued separately.
102      */
103     final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
104 
105     /**
106      * Tracking of the ordered broadcast queue, including deferral policy and alarm
107      * prioritization.
108      */
109     final BroadcastDispatcher mDispatcher;
110 
111     /**
112      * Refcounting for completion callbacks of split/deferred broadcasts.  The key
113      * is an opaque integer token assigned lazily when a broadcast is first split
114      * into multiple BroadcastRecord objects.
115      */
116     final SparseIntArray mSplitRefcounts = new SparseIntArray();
117     private int mNextToken = 0;
118 
119     /**
120      * Historical data of past broadcasts, for debugging.  This is a ring buffer
121      * whose last element is at mHistoryNext.
122      */
123     final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
124     int mHistoryNext = 0;
125 
126     /**
127      * Summary of historical data of past broadcasts, for debugging.  This is a
128      * ring buffer whose last element is at mSummaryHistoryNext.
129      */
130     final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
131     int mSummaryHistoryNext = 0;
132 
133     /**
134      * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
135      * buffer, also tracked via the mSummaryHistoryNext index.  These are all in wall
136      * clock time, not elapsed.
137      */
138     final long[] mSummaryHistoryEnqueueTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
139     final long[] mSummaryHistoryDispatchTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
140     final long[] mSummaryHistoryFinishTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
141 
142     /**
143      * Set when we current have a BROADCAST_INTENT_MSG in flight.
144      */
145     boolean mBroadcastsScheduled = false;
146 
147     /**
148      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
149      */
150     boolean mPendingBroadcastTimeoutMessage;
151 
152     /**
153      * Intent broadcasts that we have tried to start, but are
154      * waiting for the application's process to be created.  We only
155      * need one per scheduling class (instead of a list) because we always
156      * process broadcasts one at a time, so no others can be started while
157      * waiting for this one.
158      */
159     BroadcastRecord mPendingBroadcast = null;
160 
161     /**
162      * The receiver index that is pending, to restart the broadcast if needed.
163      */
164     int mPendingBroadcastRecvIndex;
165 
166     static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
167     static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
168 
169     // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing
170     boolean mLogLatencyMetrics = true;
171 
172     final BroadcastHandler mHandler;
173 
174     private final class BroadcastHandler extends Handler {
BroadcastHandler(Looper looper)175         public BroadcastHandler(Looper looper) {
176             super(looper, null, true);
177         }
178 
179         @Override
handleMessage(Message msg)180         public void handleMessage(Message msg) {
181             switch (msg.what) {
182                 case BROADCAST_INTENT_MSG: {
183                     if (DEBUG_BROADCAST) Slog.v(
184                             TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
185                             + mQueueName + "]");
186                     processNextBroadcast(true);
187                 } break;
188                 case BROADCAST_TIMEOUT_MSG: {
189                     synchronized (mService) {
190                         broadcastTimeoutLocked(true);
191                     }
192                 } break;
193             }
194         }
195     }
196 
197     private final class AppNotResponding implements Runnable {
198         private final ProcessRecord mApp;
199         private final String mAnnotation;
200 
AppNotResponding(ProcessRecord app, String annotation)201         public AppNotResponding(ProcessRecord app, String annotation) {
202             mApp = app;
203             mAnnotation = annotation;
204         }
205 
206         @Override
run()207         public void run() {
208             mApp.appNotResponding(null, null, null, null, false, mAnnotation);
209         }
210     }
211 
BroadcastQueue(ActivityManagerService service, Handler handler, String name, BroadcastConstants constants, boolean allowDelayBehindServices)212     BroadcastQueue(ActivityManagerService service, Handler handler,
213             String name, BroadcastConstants constants, boolean allowDelayBehindServices) {
214         mService = service;
215         mHandler = new BroadcastHandler(handler.getLooper());
216         mQueueName = name;
217         mDelayBehindServices = allowDelayBehindServices;
218 
219         mConstants = constants;
220         mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService);
221     }
222 
start(ContentResolver resolver)223     void start(ContentResolver resolver) {
224         mDispatcher.start();
225         mConstants.startObserving(mHandler, resolver);
226     }
227 
228     @Override
toString()229     public String toString() {
230         return mQueueName;
231     }
232 
isPendingBroadcastProcessLocked(int pid)233     public boolean isPendingBroadcastProcessLocked(int pid) {
234         return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
235     }
236 
enqueueParallelBroadcastLocked(BroadcastRecord r)237     public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
238         mParallelBroadcasts.add(r);
239         enqueueBroadcastHelper(r);
240     }
241 
enqueueOrderedBroadcastLocked(BroadcastRecord r)242     public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
243         mDispatcher.enqueueOrderedBroadcastLocked(r);
244         enqueueBroadcastHelper(r);
245     }
246 
247     /**
248      * Don't call this method directly; call enqueueParallelBroadcastLocked or
249      * enqueueOrderedBroadcastLocked.
250      */
enqueueBroadcastHelper(BroadcastRecord r)251     private void enqueueBroadcastHelper(BroadcastRecord r) {
252         r.enqueueClockTime = System.currentTimeMillis();
253 
254         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
255             Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
256                 createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
257                 System.identityHashCode(r));
258         }
259     }
260 
261     /**
262      * Find the same intent from queued parallel broadcast, replace with a new one and return
263      * the old one.
264      */
replaceParallelBroadcastLocked(BroadcastRecord r)265     public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) {
266         return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL");
267     }
268 
269     /**
270      * Find the same intent from queued ordered broadcast, replace with a new one and return
271      * the old one.
272      */
replaceOrderedBroadcastLocked(BroadcastRecord r)273     public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) {
274         return mDispatcher.replaceBroadcastLocked(r, "ORDERED");
275     }
276 
replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, BroadcastRecord r, String typeForLogging)277     private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue,
278             BroadcastRecord r, String typeForLogging) {
279         final Intent intent = r.intent;
280         for (int i = queue.size() - 1; i > 0; i--) {
281             final BroadcastRecord old = queue.get(i);
282             if (old.userId == r.userId && intent.filterEquals(old.intent)) {
283                 if (DEBUG_BROADCAST) {
284                     Slog.v(TAG_BROADCAST, "***** DROPPING "
285                             + typeForLogging + " [" + mQueueName + "]: " + intent);
286                 }
287                 queue.set(i, r);
288                 return old;
289             }
290         }
291         return null;
292     }
293 
processCurBroadcastLocked(BroadcastRecord r, ProcessRecord app, boolean skipOomAdj)294     private final void processCurBroadcastLocked(BroadcastRecord r,
295             ProcessRecord app, boolean skipOomAdj) throws RemoteException {
296         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
297                 "Process cur broadcast " + r + " for app " + app);
298         if (app.thread == null) {
299             throw new RemoteException();
300         }
301         if (app.inFullBackup) {
302             skipReceiverLocked(r);
303             return;
304         }
305 
306         r.receiver = app.thread.asBinder();
307         r.curApp = app;
308         app.curReceivers.add(r);
309         app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
310         mService.mProcessList.updateLruProcessLocked(app, false, null);
311         if (!skipOomAdj) {
312             mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
313         }
314 
315         // Tell the application to launch this receiver.
316         r.intent.setComponent(r.curComponent);
317 
318         boolean started = false;
319         try {
320             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
321                     "Delivering to component " + r.curComponent
322                     + ": " + r);
323             mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
324                                       PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER);
325             app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
326                     mService.compatibilityInfoForPackage(r.curReceiver.applicationInfo),
327                     r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
328                     app.getReportedProcState());
329             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
330                     "Process cur broadcast " + r + " DELIVERED for app " + app);
331             started = true;
332         } finally {
333             if (!started) {
334                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
335                         "Process cur broadcast " + r + ": NOT STARTED!");
336                 r.receiver = null;
337                 r.curApp = null;
338                 app.curReceivers.remove(r);
339             }
340         }
341     }
342 
sendPendingBroadcastsLocked(ProcessRecord app)343     public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
344         boolean didSomething = false;
345         final BroadcastRecord br = mPendingBroadcast;
346         if (br != null && br.curApp.pid > 0 && br.curApp.pid == app.pid) {
347             if (br.curApp != app) {
348                 Slog.e(TAG, "App mismatch when sending pending broadcast to "
349                         + app.processName + ", intended target is " + br.curApp.processName);
350                 return false;
351             }
352             try {
353                 mPendingBroadcast = null;
354                 processCurBroadcastLocked(br, app, false);
355                 didSomething = true;
356             } catch (Exception e) {
357                 Slog.w(TAG, "Exception in new application when starting receiver "
358                         + br.curComponent.flattenToShortString(), e);
359                 logBroadcastReceiverDiscardLocked(br);
360                 finishReceiverLocked(br, br.resultCode, br.resultData,
361                         br.resultExtras, br.resultAbort, false);
362                 scheduleBroadcastsLocked();
363                 // We need to reset the state if we failed to start the receiver.
364                 br.state = BroadcastRecord.IDLE;
365                 throw new RuntimeException(e.getMessage());
366             }
367         }
368         return didSomething;
369     }
370 
skipPendingBroadcastLocked(int pid)371     public void skipPendingBroadcastLocked(int pid) {
372         final BroadcastRecord br = mPendingBroadcast;
373         if (br != null && br.curApp.pid == pid) {
374             br.state = BroadcastRecord.IDLE;
375             br.nextReceiver = mPendingBroadcastRecvIndex;
376             mPendingBroadcast = null;
377             scheduleBroadcastsLocked();
378         }
379     }
380 
381     // Skip the current receiver, if any, that is in flight to the given process
skipCurrentReceiverLocked(ProcessRecord app)382     public void skipCurrentReceiverLocked(ProcessRecord app) {
383         BroadcastRecord r = null;
384         final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked();
385         if (curActive != null && curActive.curApp == app) {
386             // confirmed: the current active broadcast is to the given app
387             r = curActive;
388         }
389 
390         // If the current active broadcast isn't this BUT we're waiting for
391         // mPendingBroadcast to spin up the target app, that's what we use.
392         if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
393             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
394                     "[" + mQueueName + "] skip & discard pending app " + r);
395             r = mPendingBroadcast;
396         }
397 
398         if (r != null) {
399             skipReceiverLocked(r);
400         }
401     }
402 
skipReceiverLocked(BroadcastRecord r)403     private void skipReceiverLocked(BroadcastRecord r) {
404         logBroadcastReceiverDiscardLocked(r);
405         finishReceiverLocked(r, r.resultCode, r.resultData,
406                 r.resultExtras, r.resultAbort, false);
407         scheduleBroadcastsLocked();
408     }
409 
scheduleBroadcastsLocked()410     public void scheduleBroadcastsLocked() {
411         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
412                 + mQueueName + "]: current="
413                 + mBroadcastsScheduled);
414 
415         if (mBroadcastsScheduled) {
416             return;
417         }
418         mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
419         mBroadcastsScheduled = true;
420     }
421 
getMatchingOrderedReceiver(IBinder receiver)422     public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
423         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
424         if (br != null && br.receiver == receiver) {
425             return br;
426         }
427         return null;
428     }
429 
430     // > 0 only, no worry about "eventual" recycling
nextSplitTokenLocked()431     private int nextSplitTokenLocked() {
432         int next = mNextToken + 1;
433         if (next <= 0) {
434             next = 1;
435         }
436         mNextToken = next;
437         return next;
438     }
439 
postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r)440     private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) {
441         // the receiver had run for less than allowed bg activity start timeout,
442         // so allow the process to still start activities from bg for some more time
443         String msgToken = (app.toShortString() + r.toString()).intern();
444         // first, if there exists a past scheduled request to remove this token, drop
445         // that request - we don't want the token to be swept from under our feet...
446         mHandler.removeCallbacksAndMessages(msgToken);
447         // ...then schedule the removal of the token after the extended timeout
448         mHandler.postAtTime(() -> {
449             app.removeAllowBackgroundActivityStartsToken(r);
450         }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT));
451     }
452 
finishReceiverLocked(BroadcastRecord r, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)453     public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
454             String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
455         final int state = r.state;
456         final ActivityInfo receiver = r.curReceiver;
457         final long finishTime = SystemClock.uptimeMillis();
458         final long elapsed = finishTime - r.receiverTime;
459         r.state = BroadcastRecord.IDLE;
460         if (state == BroadcastRecord.IDLE) {
461             Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE");
462         }
463         if (r.allowBackgroundActivityStarts && r.curApp != null) {
464             if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) {
465                 // if the receiver has run for more than allowed bg activity start timeout,
466                 // just remove the token for this process now and we're done
467                 r.curApp.removeAllowBackgroundActivityStartsToken(r);
468             } else {
469                 // It gets more time; post the removal to happen at the appropriate moment
470                 postActivityStartTokenRemoval(r.curApp, r);
471             }
472         }
473         // If we're abandoning this broadcast before any receivers were actually spun up,
474         // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply.
475         if (r.nextReceiver > 0) {
476             r.duration[r.nextReceiver - 1] = elapsed;
477         }
478 
479         // if this receiver was slow, impose deferral policy on the app.  This will kick in
480         // when processNextBroadcastLocked() next finds this uid as a receiver identity.
481         if (!r.timeoutExempt) {
482             if (mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) {
483                 // Core system packages are exempt from deferral policy
484                 if (!UserHandle.isCore(r.curApp.uid)) {
485                     if (DEBUG_BROADCAST_DEFERRAL) {
486                         Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1)
487                                 + " was slow: " + receiver + " br=" + r);
488                     }
489                     if (r.curApp != null) {
490                         mDispatcher.startDeferring(r.curApp.uid);
491                     } else {
492                         Slog.d(TAG_BROADCAST, "finish receiver curApp is null? " + r);
493                     }
494                 } else {
495                     if (DEBUG_BROADCAST_DEFERRAL) {
496                         Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid
497                                 + " receiver was slow but not deferring: " + receiver + " br=" + r);
498                     }
499                 }
500             }
501         } else {
502             if (DEBUG_BROADCAST_DEFERRAL) {
503                 Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction()
504                         + " is exempt from deferral policy");
505             }
506         }
507 
508         r.receiver = null;
509         r.intent.setComponent(null);
510         if (r.curApp != null && r.curApp.curReceivers.contains(r)) {
511             r.curApp.curReceivers.remove(r);
512         }
513         if (r.curFilter != null) {
514             r.curFilter.receiverList.curBroadcast = null;
515         }
516         r.curFilter = null;
517         r.curReceiver = null;
518         r.curApp = null;
519         mPendingBroadcast = null;
520 
521         r.resultCode = resultCode;
522         r.resultData = resultData;
523         r.resultExtras = resultExtras;
524         if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
525             r.resultAbort = resultAbort;
526         } else {
527             r.resultAbort = false;
528         }
529 
530         // If we want to wait behind services *AND* we're finishing the head/
531         // active broadcast on its queue
532         if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
533                 && r.queue.mDispatcher.getActiveBroadcastLocked() == r) {
534             ActivityInfo nextReceiver;
535             if (r.nextReceiver < r.receivers.size()) {
536                 Object obj = r.receivers.get(r.nextReceiver);
537                 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
538             } else {
539                 nextReceiver = null;
540             }
541             // Don't do this if the next receive is in the same process as the current one.
542             if (receiver == null || nextReceiver == null
543                     || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
544                     || !receiver.processName.equals(nextReceiver.processName)) {
545                 // In this case, we are ready to process the next receiver for the current broadcast,
546                 // but are on a queue that would like to wait for services to finish before moving
547                 // on.  If there are background services currently starting, then we will go into a
548                 // special state where we hold off on continuing this broadcast until they are done.
549                 if (mService.mServices.hasBackgroundServicesLocked(r.userId)) {
550                     Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
551                     r.state = BroadcastRecord.WAITING_SERVICES;
552                     return false;
553                 }
554             }
555         }
556 
557         r.curComponent = null;
558 
559         // We will process the next receiver right now if this is finishing
560         // an app receiver (which is always asynchronous) or after we have
561         // come back from calling a receiver.
562         return state == BroadcastRecord.APP_RECEIVE
563                 || state == BroadcastRecord.CALL_DONE_RECEIVE;
564     }
565 
backgroundServicesFinishedLocked(int userId)566     public void backgroundServicesFinishedLocked(int userId) {
567         BroadcastRecord br = mDispatcher.getActiveBroadcastLocked();
568         if (br != null) {
569             if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
570                 Slog.i(TAG, "Resuming delayed broadcast");
571                 br.curComponent = null;
572                 br.state = BroadcastRecord.IDLE;
573                 processNextBroadcast(false);
574             }
575         }
576     }
577 
performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser)578     void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
579             Intent intent, int resultCode, String data, Bundle extras,
580             boolean ordered, boolean sticky, int sendingUser)
581             throws RemoteException {
582         // Send the intent to the receiver asynchronously using one-way binder calls.
583         if (app != null) {
584             if (app.thread != null) {
585                 // If we have an app thread, do the call through that so it is
586                 // correctly ordered with other one-way calls.
587                 try {
588                     app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
589                             data, extras, ordered, sticky, sendingUser, app.getReportedProcState());
590                 // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting
591                 // DeadObjectException when the process isn't actually dead.
592                 //} catch (DeadObjectException ex) {
593                 // Failed to call into the process.  It's dying so just let it die and move on.
594                 //    throw ex;
595                 } catch (RemoteException ex) {
596                     // Failed to call into the process. It's either dying or wedged. Kill it gently.
597                     synchronized (mService) {
598                         Slog.w(TAG, "Can't deliver broadcast to " + app.processName
599                                 + " (pid " + app.pid + "). Crashing it.");
600                         app.scheduleCrash("can't deliver broadcast");
601                     }
602                     throw ex;
603                 }
604             } else {
605                 // Application has died. Receiver doesn't exist.
606                 throw new RemoteException("app.thread must not be null");
607             }
608         } else {
609             receiver.performReceive(intent, resultCode, data, extras, ordered,
610                     sticky, sendingUser);
611         }
612     }
613 
deliverToRegisteredReceiverLocked(BroadcastRecord r, BroadcastFilter filter, boolean ordered, int index)614     private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
615             BroadcastFilter filter, boolean ordered, int index) {
616         boolean skip = false;
617         if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
618                 filter.packageName, filter.owningUid)) {
619             Slog.w(TAG, "Association not allowed: broadcasting "
620                     + r.intent.toString()
621                     + " from " + r.callerPackage + " (pid=" + r.callingPid
622                     + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
623                     + filter);
624             skip = true;
625         }
626         if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
627                 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
628             Slog.w(TAG, "Firewall blocked: broadcasting "
629                     + r.intent.toString()
630                     + " from " + r.callerPackage + " (pid=" + r.callingPid
631                     + ", uid=" + r.callingUid + ") to " + filter.packageName + " through "
632                     + filter);
633             skip = true;
634         }
635         if (filter.requiredPermission != null) {
636             int perm = mService.checkComponentPermission(filter.requiredPermission,
637                     r.callingPid, r.callingUid, -1, true);
638             if (perm != PackageManager.PERMISSION_GRANTED) {
639                 Slog.w(TAG, "Permission Denial: broadcasting "
640                         + r.intent.toString()
641                         + " from " + r.callerPackage + " (pid="
642                         + r.callingPid + ", uid=" + r.callingUid + ")"
643                         + " requires " + filter.requiredPermission
644                         + " due to registered receiver " + filter);
645                 skip = true;
646             } else {
647                 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
648                 if (opCode != AppOpsManager.OP_NONE
649                         && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
650                                 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
651                     Slog.w(TAG, "Appop Denial: broadcasting "
652                             + r.intent.toString()
653                             + " from " + r.callerPackage + " (pid="
654                             + r.callingPid + ", uid=" + r.callingUid + ")"
655                             + " requires appop " + AppOpsManager.permissionToOp(
656                                     filter.requiredPermission)
657                             + " due to registered receiver " + filter);
658                     skip = true;
659                 }
660             }
661         }
662         if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
663             for (int i = 0; i < r.requiredPermissions.length; i++) {
664                 String requiredPermission = r.requiredPermissions[i];
665                 int perm = mService.checkComponentPermission(requiredPermission,
666                         filter.receiverList.pid, filter.receiverList.uid, -1, true);
667                 if (perm != PackageManager.PERMISSION_GRANTED) {
668                     Slog.w(TAG, "Permission Denial: receiving "
669                             + r.intent.toString()
670                             + " to " + filter.receiverList.app
671                             + " (pid=" + filter.receiverList.pid
672                             + ", uid=" + filter.receiverList.uid + ")"
673                             + " requires " + requiredPermission
674                             + " due to sender " + r.callerPackage
675                             + " (uid " + r.callingUid + ")");
676                     skip = true;
677                     break;
678                 }
679                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
680                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
681                         && mService.mAppOpsService.noteOperation(appOp,
682                         filter.receiverList.uid, filter.packageName)
683                         != AppOpsManager.MODE_ALLOWED) {
684                     Slog.w(TAG, "Appop Denial: receiving "
685                             + r.intent.toString()
686                             + " to " + filter.receiverList.app
687                             + " (pid=" + filter.receiverList.pid
688                             + ", uid=" + filter.receiverList.uid + ")"
689                             + " requires appop " + AppOpsManager.permissionToOp(
690                             requiredPermission)
691                             + " due to sender " + r.callerPackage
692                             + " (uid " + r.callingUid + ")");
693                     skip = true;
694                     break;
695                 }
696             }
697         }
698         if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
699             int perm = mService.checkComponentPermission(null,
700                     filter.receiverList.pid, filter.receiverList.uid, -1, true);
701             if (perm != PackageManager.PERMISSION_GRANTED) {
702                 Slog.w(TAG, "Permission Denial: security check failed when receiving "
703                         + r.intent.toString()
704                         + " to " + filter.receiverList.app
705                         + " (pid=" + filter.receiverList.pid
706                         + ", uid=" + filter.receiverList.uid + ")"
707                         + " due to sender " + r.callerPackage
708                         + " (uid " + r.callingUid + ")");
709                 skip = true;
710             }
711         }
712         if (!skip && r.appOp != AppOpsManager.OP_NONE
713                 && mService.mAppOpsService.noteOperation(r.appOp,
714                 filter.receiverList.uid, filter.packageName)
715                 != AppOpsManager.MODE_ALLOWED) {
716             Slog.w(TAG, "Appop Denial: receiving "
717                     + r.intent.toString()
718                     + " to " + filter.receiverList.app
719                     + " (pid=" + filter.receiverList.pid
720                     + ", uid=" + filter.receiverList.uid + ")"
721                     + " requires appop " + AppOpsManager.opToName(r.appOp)
722                     + " due to sender " + r.callerPackage
723                     + " (uid " + r.callingUid + ")");
724             skip = true;
725         }
726 
727         if (!skip && (filter.receiverList.app == null || filter.receiverList.app.killed
728                 || filter.receiverList.app.isCrashing())) {
729             Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
730                     + " to " + filter.receiverList + ": process gone or crashing");
731             skip = true;
732         }
733 
734         // Ensure that broadcasts are only sent to other Instant Apps if they are marked as
735         // visible to Instant Apps.
736         final boolean visibleToInstantApps =
737                 (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
738 
739         if (!skip && !visibleToInstantApps && filter.instantApp
740                 && filter.receiverList.uid != r.callingUid) {
741             Slog.w(TAG, "Instant App Denial: receiving "
742                     + r.intent.toString()
743                     + " to " + filter.receiverList.app
744                     + " (pid=" + filter.receiverList.pid
745                     + ", uid=" + filter.receiverList.uid + ")"
746                     + " due to sender " + r.callerPackage
747                     + " (uid " + r.callingUid + ")"
748                     + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS");
749             skip = true;
750         }
751 
752         if (!skip && !filter.visibleToInstantApp && r.callerInstantApp
753                 && filter.receiverList.uid != r.callingUid) {
754             Slog.w(TAG, "Instant App Denial: receiving "
755                     + r.intent.toString()
756                     + " to " + filter.receiverList.app
757                     + " (pid=" + filter.receiverList.pid
758                     + ", uid=" + filter.receiverList.uid + ")"
759                     + " requires receiver be visible to instant apps"
760                     + " due to sender " + r.callerPackage
761                     + " (uid " + r.callingUid + ")");
762             skip = true;
763         }
764 
765         if (skip) {
766             r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
767             return;
768         }
769 
770         // If permissions need a review before any of the app components can run, we drop
771         // the broadcast and if the calling app is in the foreground and the broadcast is
772         // explicit we launch the review UI passing it a pending intent to send the skipped
773         // broadcast.
774         if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName,
775                 filter.owningUserId)) {
776             r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED;
777             return;
778         }
779 
780         r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED;
781 
782         // If this is not being sent as an ordered broadcast, then we
783         // don't want to touch the fields that keep track of the current
784         // state of ordered broadcasts.
785         if (ordered) {
786             r.receiver = filter.receiverList.receiver.asBinder();
787             r.curFilter = filter;
788             filter.receiverList.curBroadcast = r;
789             r.state = BroadcastRecord.CALL_IN_RECEIVE;
790             if (filter.receiverList.app != null) {
791                 // Bump hosting application to no longer be in background
792                 // scheduling class.  Note that we can't do that if there
793                 // isn't an app...  but we can only be in that case for
794                 // things that directly call the IActivityManager API, which
795                 // are already core system stuff so don't matter for this.
796                 r.curApp = filter.receiverList.app;
797                 filter.receiverList.app.curReceivers.add(r);
798                 mService.updateOomAdjLocked(r.curApp, true,
799                         OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
800             }
801         }
802         try {
803             if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
804                     "Delivering to " + filter + " : " + r);
805             if (filter.receiverList.app != null && filter.receiverList.app.inFullBackup) {
806                 // Skip delivery if full backup in progress
807                 // If it's an ordered broadcast, we need to continue to the next receiver.
808                 if (ordered) {
809                     skipReceiverLocked(r);
810                 }
811             } else {
812                 r.receiverTime = SystemClock.uptimeMillis();
813                 maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
814                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
815                         new Intent(r.intent), r.resultCode, r.resultData,
816                         r.resultExtras, r.ordered, r.initialSticky, r.userId);
817                 // parallel broadcasts are fire-and-forget, not bookended by a call to
818                 // finishReceiverLocked(), so we manage their activity-start token here
819                 if (r.allowBackgroundActivityStarts && !r.ordered) {
820                     postActivityStartTokenRemoval(filter.receiverList.app, r);
821                 }
822             }
823             if (ordered) {
824                 r.state = BroadcastRecord.CALL_DONE_RECEIVE;
825             }
826         } catch (RemoteException e) {
827             Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
828             // Clean up ProcessRecord state related to this broadcast attempt
829             if (filter.receiverList.app != null) {
830                 filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r);
831                 if (ordered) {
832                     filter.receiverList.app.curReceivers.remove(r);
833                 }
834             }
835             // And BroadcastRecord state related to ordered delivery, if appropriate
836             if (ordered) {
837                 r.receiver = null;
838                 r.curFilter = null;
839                 filter.receiverList.curBroadcast = null;
840             }
841         }
842     }
843 
requestStartTargetPermissionsReviewIfNeededLocked( BroadcastRecord receiverRecord, String receivingPackageName, final int receivingUserId)844     private boolean requestStartTargetPermissionsReviewIfNeededLocked(
845             BroadcastRecord receiverRecord, String receivingPackageName,
846             final int receivingUserId) {
847         if (!mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
848                 receivingPackageName, receivingUserId)) {
849             return true;
850         }
851 
852         final boolean callerForeground = receiverRecord.callerApp != null
853                 ? receiverRecord.callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND
854                 : true;
855 
856         // Show a permission review UI only for explicit broadcast from a foreground app
857         if (callerForeground && receiverRecord.intent.getComponent() != null) {
858             IIntentSender target = mService.mPendingIntentController.getIntentSender(
859                     ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage,
860                     receiverRecord.callingUid, receiverRecord.userId, null, null, 0,
861                     new Intent[]{receiverRecord.intent},
862                     new String[]{receiverRecord.intent.resolveType(mService.mContext
863                             .getContentResolver())},
864                     PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
865                             | PendingIntent.FLAG_IMMUTABLE, null);
866 
867             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
868             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
869                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
870                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
871             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName);
872             intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
873 
874             if (DEBUG_PERMISSIONS_REVIEW) {
875                 Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package "
876                         + receivingPackageName);
877             }
878 
879             mHandler.post(new Runnable() {
880                 @Override
881                 public void run() {
882                     mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId));
883                 }
884             });
885         } else {
886             Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package"
887                     + receivingPackageName + " requires a permissions review");
888         }
889 
890         return false;
891     }
892 
scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r)893     final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
894         if (duration > Integer.MAX_VALUE) {
895             duration = Integer.MAX_VALUE;
896         }
897         // XXX ideally we should pause the broadcast until everything behind this is done,
898         // or else we will likely start dispatching the broadcast before we have opened
899         // access to the app (there is a lot of asynchronicity behind this).  It is probably
900         // not that big a deal, however, because the main purpose here is to allow apps
901         // to hold wake locks, and they will be able to acquire their wake lock immediately
902         // it just won't be enabled until we get through this work.
903         StringBuilder b = new StringBuilder();
904         b.append("broadcast:");
905         UserHandle.formatUid(b, r.callingUid);
906         b.append(":");
907         if (r.intent.getAction() != null) {
908             b.append(r.intent.getAction());
909         } else if (r.intent.getComponent() != null) {
910             r.intent.getComponent().appendShortString(b);
911         } else if (r.intent.getData() != null) {
912             b.append(r.intent.getData());
913         }
914         mService.tempWhitelistUidLocked(uid, duration, b.toString());
915     }
916 
917     /**
918      * Return true if all given permissions are signature-only perms.
919      */
isSignaturePerm(String[] perms)920     final boolean isSignaturePerm(String[] perms) {
921         if (perms == null) {
922             return false;
923         }
924         IPackageManager pm = AppGlobals.getPackageManager();
925         for (int i = perms.length-1; i >= 0; i--) {
926             try {
927                 PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
928                 if (pi == null) {
929                     // a required permission that no package has actually
930                     // defined cannot be signature-required.
931                     return false;
932                 }
933                 if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
934                         | PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
935                         != PermissionInfo.PROTECTION_SIGNATURE) {
936                     // If this a signature permission and NOT allowed for privileged apps, it
937                     // is okay...  otherwise, nope!
938                     return false;
939                 }
940             } catch (RemoteException e) {
941                 return false;
942             }
943         }
944         return true;
945     }
946 
processNextBroadcast(boolean fromMsg)947     final void processNextBroadcast(boolean fromMsg) {
948         synchronized (mService) {
949             processNextBroadcastLocked(fromMsg, false);
950         }
951     }
952 
processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj)953     final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) {
954         BroadcastRecord r;
955 
956         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
957                 + mQueueName + "]: "
958                 + mParallelBroadcasts.size() + " parallel broadcasts; "
959                 + mDispatcher.describeStateLocked());
960 
961         mService.updateCpuStats();
962 
963         if (fromMsg) {
964             mBroadcastsScheduled = false;
965         }
966 
967         // First, deliver any non-serialized broadcasts right away.
968         while (mParallelBroadcasts.size() > 0) {
969             r = mParallelBroadcasts.remove(0);
970             r.dispatchTime = SystemClock.uptimeMillis();
971             r.dispatchClockTime = System.currentTimeMillis();
972 
973             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
974                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
975                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
976                     System.identityHashCode(r));
977                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
978                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
979                     System.identityHashCode(r));
980             }
981 
982             final int N = r.receivers.size();
983             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
984                     + mQueueName + "] " + r);
985             for (int i=0; i<N; i++) {
986                 Object target = r.receivers.get(i);
987                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
988                         "Delivering non-ordered on [" + mQueueName + "] to registered "
989                         + target + ": " + r);
990                 deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false, i);
991             }
992             addBroadcastToHistoryLocked(r);
993             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
994                     + mQueueName + "] " + r);
995         }
996 
997         // Now take care of the next serialized one...
998 
999         // If we are waiting for a process to come up to handle the next
1000         // broadcast, then do nothing at this point.  Just in case, we
1001         // check that the process we're waiting for still exists.
1002         if (mPendingBroadcast != null) {
1003             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1004                     "processNextBroadcast [" + mQueueName + "]: waiting for "
1005                     + mPendingBroadcast.curApp);
1006 
1007             boolean isDead;
1008             if (mPendingBroadcast.curApp.pid > 0) {
1009                 synchronized (mService.mPidsSelfLocked) {
1010                     ProcessRecord proc = mService.mPidsSelfLocked.get(
1011                             mPendingBroadcast.curApp.pid);
1012                     isDead = proc == null || proc.isCrashing();
1013                 }
1014             } else {
1015                 final ProcessRecord proc = mService.mProcessList.mProcessNames.get(
1016                         mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid);
1017                 isDead = proc == null || !proc.pendingStart;
1018             }
1019             if (!isDead) {
1020                 // It's still alive, so keep waiting
1021                 return;
1022             } else {
1023                 Slog.w(TAG, "pending app  ["
1024                         + mQueueName + "]" + mPendingBroadcast.curApp
1025                         + " died before responding to broadcast");
1026                 mPendingBroadcast.state = BroadcastRecord.IDLE;
1027                 mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
1028                 mPendingBroadcast = null;
1029             }
1030         }
1031 
1032         boolean looped = false;
1033 
1034         do {
1035             final long now = SystemClock.uptimeMillis();
1036             r = mDispatcher.getNextBroadcastLocked(now);
1037 
1038             if (r == null) {
1039                 // No more broadcasts are deliverable right now, so all done!
1040                 mDispatcher.scheduleDeferralCheckLocked(false);
1041                 mService.scheduleAppGcsLocked();
1042                 if (looped) {
1043                     // If we had finished the last ordered broadcast, then
1044                     // make sure all processes have correct oom and sched
1045                     // adjustments.
1046                     mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_START_RECEIVER);
1047                 }
1048 
1049                 // when we have no more ordered broadcast on this queue, stop logging
1050                 if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) {
1051                     mLogLatencyMetrics = false;
1052                 }
1053 
1054                 return;
1055             }
1056 
1057             boolean forceReceive = false;
1058 
1059             // Ensure that even if something goes awry with the timeout
1060             // detection, we catch "hung" broadcasts here, discard them,
1061             // and continue to make progress.
1062             //
1063             // This is only done if the system is ready so that early-stage receivers
1064             // don't get executed with timeouts; and of course other timeout-
1065             // exempt broadcasts are ignored.
1066             int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
1067             if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) {
1068                 if ((numReceivers > 0) &&
1069                         (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) {
1070                     Slog.w(TAG, "Hung broadcast ["
1071                             + mQueueName + "] discarded after timeout failure:"
1072                             + " now=" + now
1073                             + " dispatchTime=" + r.dispatchTime
1074                             + " startTime=" + r.receiverTime
1075                             + " intent=" + r.intent
1076                             + " numReceivers=" + numReceivers
1077                             + " nextReceiver=" + r.nextReceiver
1078                             + " state=" + r.state);
1079                     broadcastTimeoutLocked(false); // forcibly finish this broadcast
1080                     forceReceive = true;
1081                     r.state = BroadcastRecord.IDLE;
1082                 }
1083             }
1084 
1085             if (r.state != BroadcastRecord.IDLE) {
1086                 if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
1087                         "processNextBroadcast("
1088                         + mQueueName + ") called when not idle (state="
1089                         + r.state + ")");
1090                 return;
1091             }
1092 
1093             // Is the current broadcast is done for any reason?
1094             if (r.receivers == null || r.nextReceiver >= numReceivers
1095                     || r.resultAbort || forceReceive) {
1096                 // Send the final result if requested
1097                 if (r.resultTo != null) {
1098                     boolean sendResult = true;
1099 
1100                     // if this was part of a split/deferral complex, update the refcount and only
1101                     // send the completion when we clear all of them
1102                     if (r.splitToken != 0) {
1103                         int newCount = mSplitRefcounts.get(r.splitToken) - 1;
1104                         if (newCount == 0) {
1105                             // done!  clear out this record's bookkeeping and deliver
1106                             if (DEBUG_BROADCAST_DEFERRAL) {
1107                                 Slog.i(TAG_BROADCAST,
1108                                         "Sending broadcast completion for split token "
1109                                         + r.splitToken + " : " + r.intent.getAction());
1110                             }
1111                             mSplitRefcounts.delete(r.splitToken);
1112                         } else {
1113                             // still have some split broadcast records in flight; update refcount
1114                             // and hold off on the callback
1115                             if (DEBUG_BROADCAST_DEFERRAL) {
1116                                 Slog.i(TAG_BROADCAST,
1117                                         "Result refcount now " + newCount + " for split token "
1118                                         + r.splitToken + " : " + r.intent.getAction()
1119                                         + " - not sending completion yet");
1120                             }
1121                             sendResult = false;
1122                             mSplitRefcounts.put(r.splitToken, newCount);
1123                         }
1124                     }
1125                     if (sendResult) {
1126                         try {
1127                             if (DEBUG_BROADCAST) {
1128                                 Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] "
1129                                         + r.intent.getAction() + " app=" + r.callerApp);
1130                             }
1131                             performReceiveLocked(r.callerApp, r.resultTo,
1132                                     new Intent(r.intent), r.resultCode,
1133                                     r.resultData, r.resultExtras, false, false, r.userId);
1134                             // Set this to null so that the reference
1135                             // (local and remote) isn't kept in the mBroadcastHistory.
1136                             r.resultTo = null;
1137                         } catch (RemoteException e) {
1138                             r.resultTo = null;
1139                             Slog.w(TAG, "Failure ["
1140                                     + mQueueName + "] sending broadcast result of "
1141                                     + r.intent, e);
1142                         }
1143                     }
1144                 }
1145 
1146                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
1147                 cancelBroadcastTimeoutLocked();
1148 
1149                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
1150                         "Finished with ordered broadcast " + r);
1151 
1152                 // ... and on to the next...
1153                 addBroadcastToHistoryLocked(r);
1154                 if (r.intent.getComponent() == null && r.intent.getPackage() == null
1155                         && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
1156                     // This was an implicit broadcast... let's record it for posterity.
1157                     mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage,
1158                             r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime);
1159                 }
1160                 mDispatcher.retireBroadcastLocked(r);
1161                 r = null;
1162                 looped = true;
1163                 continue;
1164             }
1165 
1166             // Check whether the next receiver is under deferral policy, and handle that
1167             // accordingly.  If the current broadcast was already part of deferred-delivery
1168             // tracking, we know that it must now be deliverable as-is without re-deferral.
1169             if (!r.deferred) {
1170                 final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver));
1171                 if (mDispatcher.isDeferringLocked(receiverUid)) {
1172                     if (DEBUG_BROADCAST_DEFERRAL) {
1173                         Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid
1174                                 + " at " + r.nextReceiver + " is under deferral");
1175                     }
1176                     // If this is the only (remaining) receiver in the broadcast, "splitting"
1177                     // doesn't make sense -- just defer it as-is and retire it as the
1178                     // currently active outgoing broadcast.
1179                     BroadcastRecord defer;
1180                     if (r.nextReceiver + 1 == numReceivers) {
1181                         if (DEBUG_BROADCAST_DEFERRAL) {
1182                             Slog.i(TAG_BROADCAST, "Sole receiver of " + r
1183                                     + " is under deferral; setting aside and proceeding");
1184                         }
1185                         defer = r;
1186                         mDispatcher.retireBroadcastLocked(r);
1187                     } else {
1188                         // Nontrivial case; split out 'uid's receivers to a new broadcast record
1189                         // and defer that, then loop and pick up continuing delivery of the current
1190                         // record (now absent those receivers).
1191 
1192                         // The split operation is guaranteed to match at least at 'nextReceiver'
1193                         defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver);
1194                         if (DEBUG_BROADCAST_DEFERRAL) {
1195                             Slog.i(TAG_BROADCAST, "Post split:");
1196                             Slog.i(TAG_BROADCAST, "Original broadcast receivers:");
1197                             for (int i = 0; i < r.receivers.size(); i++) {
1198                                 Slog.i(TAG_BROADCAST, "  " + r.receivers.get(i));
1199                             }
1200                             Slog.i(TAG_BROADCAST, "Split receivers:");
1201                             for (int i = 0; i < defer.receivers.size(); i++) {
1202                                 Slog.i(TAG_BROADCAST, "  " + defer.receivers.get(i));
1203                             }
1204                         }
1205                         // Track completion refcount as well if relevant
1206                         if (r.resultTo != null) {
1207                             int token = r.splitToken;
1208                             if (token == 0) {
1209                                 // first split of this record; refcount for 'r' and 'deferred'
1210                                 r.splitToken = defer.splitToken = nextSplitTokenLocked();
1211                                 mSplitRefcounts.put(r.splitToken, 2);
1212                                 if (DEBUG_BROADCAST_DEFERRAL) {
1213                                     Slog.i(TAG_BROADCAST,
1214                                             "Broadcast needs split refcount; using new token "
1215                                             + r.splitToken);
1216                                 }
1217                             } else {
1218                                 // new split from an already-refcounted situation; increment count
1219                                 final int curCount = mSplitRefcounts.get(token);
1220                                 if (DEBUG_BROADCAST_DEFERRAL) {
1221                                     if (curCount == 0) {
1222                                         Slog.wtf(TAG_BROADCAST,
1223                                                 "Split refcount is zero with token for " + r);
1224                                     }
1225                                 }
1226                                 mSplitRefcounts.put(token, curCount + 1);
1227                                 if (DEBUG_BROADCAST_DEFERRAL) {
1228                                     Slog.i(TAG_BROADCAST, "New split count for token " + token
1229                                             + " is " + (curCount + 1));
1230                                 }
1231                             }
1232                         }
1233                     }
1234                     mDispatcher.addDeferredBroadcast(receiverUid, defer);
1235                     r = null;
1236                     looped = true;
1237                     continue;
1238                 }
1239             }
1240         } while (r == null);
1241 
1242         // Get the next receiver...
1243         int recIdx = r.nextReceiver++;
1244 
1245         // Keep track of when this receiver started, and make sure there
1246         // is a timeout message pending to kill it if need be.
1247         r.receiverTime = SystemClock.uptimeMillis();
1248         if (recIdx == 0) {
1249             r.dispatchTime = r.receiverTime;
1250             r.dispatchClockTime = System.currentTimeMillis();
1251 
1252             if (mLogLatencyMetrics) {
1253                 StatsLog.write(
1254                         StatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED,
1255                         r.dispatchClockTime - r.enqueueClockTime);
1256             }
1257 
1258             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1259                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1260                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING),
1261                     System.identityHashCode(r));
1262                 Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1263                     createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED),
1264                     System.identityHashCode(r));
1265             }
1266             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
1267                     + mQueueName + "] " + r);
1268         }
1269         if (! mPendingBroadcastTimeoutMessage) {
1270             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1271             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1272                     "Submitting BROADCAST_TIMEOUT_MSG ["
1273                     + mQueueName + "] for " + r + " at " + timeoutTime);
1274             setBroadcastTimeoutLocked(timeoutTime);
1275         }
1276 
1277         final BroadcastOptions brOptions = r.options;
1278         final Object nextReceiver = r.receivers.get(recIdx);
1279 
1280         if (nextReceiver instanceof BroadcastFilter) {
1281             // Simple case: this is a registered receiver who gets
1282             // a direct call.
1283             BroadcastFilter filter = (BroadcastFilter)nextReceiver;
1284             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1285                     "Delivering ordered ["
1286                     + mQueueName + "] to registered "
1287                     + filter + ": " + r);
1288             deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx);
1289             if (r.receiver == null || !r.ordered) {
1290                 // The receiver has already finished, so schedule to
1291                 // process the next one.
1292                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
1293                         + mQueueName + "]: ordered="
1294                         + r.ordered + " receiver=" + r.receiver);
1295                 r.state = BroadcastRecord.IDLE;
1296                 scheduleBroadcastsLocked();
1297             } else {
1298                 if (filter.receiverList != null) {
1299                     maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r);
1300                     // r is guaranteed ordered at this point, so we know finishReceiverLocked()
1301                     // will get a callback and handle the activity start token lifecycle.
1302                 }
1303                 if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1304                     scheduleTempWhitelistLocked(filter.owningUid,
1305                             brOptions.getTemporaryAppWhitelistDuration(), r);
1306                 }
1307             }
1308             return;
1309         }
1310 
1311         // Hard case: need to instantiate the receiver, possibly
1312         // starting its application process to host it.
1313 
1314         ResolveInfo info =
1315             (ResolveInfo)nextReceiver;
1316         ComponentName component = new ComponentName(
1317                 info.activityInfo.applicationInfo.packageName,
1318                 info.activityInfo.name);
1319 
1320         boolean skip = false;
1321         if (brOptions != null &&
1322                 (info.activityInfo.applicationInfo.targetSdkVersion
1323                         < brOptions.getMinManifestReceiverApiLevel() ||
1324                 info.activityInfo.applicationInfo.targetSdkVersion
1325                         > brOptions.getMaxManifestReceiverApiLevel())) {
1326             skip = true;
1327         }
1328         if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid,
1329                 component.getPackageName(), info.activityInfo.applicationInfo.uid)) {
1330             Slog.w(TAG, "Association not allowed: broadcasting "
1331                     + r.intent.toString()
1332                     + " from " + r.callerPackage + " (pid=" + r.callingPid
1333                     + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1334             skip = true;
1335         }
1336         if (!skip) {
1337             skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
1338                     r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
1339             if (skip) {
1340                 Slog.w(TAG, "Firewall blocked: broadcasting "
1341                         + r.intent.toString()
1342                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1343                         + ", uid=" + r.callingUid + ") to " + component.flattenToShortString());
1344             }
1345         }
1346         int perm = mService.checkComponentPermission(info.activityInfo.permission,
1347                 r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
1348                 info.activityInfo.exported);
1349         if (!skip && perm != PackageManager.PERMISSION_GRANTED) {
1350             if (!info.activityInfo.exported) {
1351                 Slog.w(TAG, "Permission Denial: broadcasting "
1352                         + r.intent.toString()
1353                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1354                         + ", uid=" + r.callingUid + ")"
1355                         + " is not exported from uid " + info.activityInfo.applicationInfo.uid
1356                         + " due to receiver " + component.flattenToShortString());
1357             } else {
1358                 Slog.w(TAG, "Permission Denial: broadcasting "
1359                         + r.intent.toString()
1360                         + " from " + r.callerPackage + " (pid=" + r.callingPid
1361                         + ", uid=" + r.callingUid + ")"
1362                         + " requires " + info.activityInfo.permission
1363                         + " due to receiver " + component.flattenToShortString());
1364             }
1365             skip = true;
1366         } else if (!skip && info.activityInfo.permission != null) {
1367             final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
1368             if (opCode != AppOpsManager.OP_NONE
1369                     && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
1370                             r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
1371                 Slog.w(TAG, "Appop Denial: broadcasting "
1372                         + r.intent.toString()
1373                         + " from " + r.callerPackage + " (pid="
1374                         + r.callingPid + ", uid=" + r.callingUid + ")"
1375                         + " requires appop " + AppOpsManager.permissionToOp(
1376                                 info.activityInfo.permission)
1377                         + " due to registered receiver "
1378                         + component.flattenToShortString());
1379                 skip = true;
1380             }
1381         }
1382         if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
1383             r.requiredPermissions != null && r.requiredPermissions.length > 0) {
1384             for (int i = 0; i < r.requiredPermissions.length; i++) {
1385                 String requiredPermission = r.requiredPermissions[i];
1386                 try {
1387                     perm = AppGlobals.getPackageManager().
1388                             checkPermission(requiredPermission,
1389                                     info.activityInfo.applicationInfo.packageName,
1390                                     UserHandle
1391                                             .getUserId(info.activityInfo.applicationInfo.uid));
1392                 } catch (RemoteException e) {
1393                     perm = PackageManager.PERMISSION_DENIED;
1394                 }
1395                 if (perm != PackageManager.PERMISSION_GRANTED) {
1396                     Slog.w(TAG, "Permission Denial: receiving "
1397                             + r.intent + " to "
1398                             + component.flattenToShortString()
1399                             + " requires " + requiredPermission
1400                             + " due to sender " + r.callerPackage
1401                             + " (uid " + r.callingUid + ")");
1402                     skip = true;
1403                     break;
1404                 }
1405                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
1406                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
1407                         && mService.mAppOpsService.noteOperation(appOp,
1408                         info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1409                         != AppOpsManager.MODE_ALLOWED) {
1410                     Slog.w(TAG, "Appop Denial: receiving "
1411                             + r.intent + " to "
1412                             + component.flattenToShortString()
1413                             + " requires appop " + AppOpsManager.permissionToOp(
1414                             requiredPermission)
1415                             + " due to sender " + r.callerPackage
1416                             + " (uid " + r.callingUid + ")");
1417                     skip = true;
1418                     break;
1419                 }
1420             }
1421         }
1422         if (!skip && r.appOp != AppOpsManager.OP_NONE
1423                 && mService.mAppOpsService.noteOperation(r.appOp,
1424                 info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
1425                 != AppOpsManager.MODE_ALLOWED) {
1426             Slog.w(TAG, "Appop Denial: receiving "
1427                     + r.intent + " to "
1428                     + component.flattenToShortString()
1429                     + " requires appop " + AppOpsManager.opToName(r.appOp)
1430                     + " due to sender " + r.callerPackage
1431                     + " (uid " + r.callingUid + ")");
1432             skip = true;
1433         }
1434         boolean isSingleton = false;
1435         try {
1436             isSingleton = mService.isSingleton(info.activityInfo.processName,
1437                     info.activityInfo.applicationInfo,
1438                     info.activityInfo.name, info.activityInfo.flags);
1439         } catch (SecurityException e) {
1440             Slog.w(TAG, e.getMessage());
1441             skip = true;
1442         }
1443         if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
1444             if (ActivityManager.checkUidPermission(
1445                     android.Manifest.permission.INTERACT_ACROSS_USERS,
1446                     info.activityInfo.applicationInfo.uid)
1447                             != PackageManager.PERMISSION_GRANTED) {
1448                 Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
1449                         + " requests FLAG_SINGLE_USER, but app does not hold "
1450                         + android.Manifest.permission.INTERACT_ACROSS_USERS);
1451                 skip = true;
1452             }
1453         }
1454         if (!skip && info.activityInfo.applicationInfo.isInstantApp()
1455                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1456             Slog.w(TAG, "Instant App Denial: receiving "
1457                     + r.intent
1458                     + " to " + component.flattenToShortString()
1459                     + " due to sender " + r.callerPackage
1460                     + " (uid " + r.callingUid + ")"
1461                     + " Instant Apps do not support manifest receivers");
1462             skip = true;
1463         }
1464         if (!skip && r.callerInstantApp
1465                 && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0
1466                 && r.callingUid != info.activityInfo.applicationInfo.uid) {
1467             Slog.w(TAG, "Instant App Denial: receiving "
1468                     + r.intent
1469                     + " to " + component.flattenToShortString()
1470                     + " requires receiver have visibleToInstantApps set"
1471                     + " due to sender " + r.callerPackage
1472                     + " (uid " + r.callingUid + ")");
1473             skip = true;
1474         }
1475         if (r.curApp != null && r.curApp.isCrashing()) {
1476             // If the target process is crashing, just skip it.
1477             Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
1478                     + " to " + r.curApp + ": process crashing");
1479             skip = true;
1480         }
1481         if (!skip) {
1482             boolean isAvailable = false;
1483             try {
1484                 isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
1485                         info.activityInfo.packageName,
1486                         UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
1487             } catch (Exception e) {
1488                 // all such failures mean we skip this receiver
1489                 Slog.w(TAG, "Exception getting recipient info for "
1490                         + info.activityInfo.packageName, e);
1491             }
1492             if (!isAvailable) {
1493                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1494                         "Skipping delivery to " + info.activityInfo.packageName + " / "
1495                         + info.activityInfo.applicationInfo.uid
1496                         + " : package no longer available");
1497                 skip = true;
1498             }
1499         }
1500 
1501         // If permissions need a review before any of the app components can run, we drop
1502         // the broadcast and if the calling app is in the foreground and the broadcast is
1503         // explicit we launch the review UI passing it a pending intent to send the skipped
1504         // broadcast.
1505         if (!skip) {
1506             if (!requestStartTargetPermissionsReviewIfNeededLocked(r,
1507                     info.activityInfo.packageName, UserHandle.getUserId(
1508                             info.activityInfo.applicationInfo.uid))) {
1509                 skip = true;
1510             }
1511         }
1512 
1513         // This is safe to do even if we are skipping the broadcast, and we need
1514         // this information now to evaluate whether it is going to be allowed to run.
1515         final int receiverUid = info.activityInfo.applicationInfo.uid;
1516         // If it's a singleton, it needs to be the same app or a special app
1517         if (r.callingUid != Process.SYSTEM_UID && isSingleton
1518                 && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1519             info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1520         }
1521         String targetProcess = info.activityInfo.processName;
1522         ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1523                 info.activityInfo.applicationInfo.uid, false);
1524 
1525         if (!skip) {
1526             final int allowed = mService.getAppStartModeLocked(
1527                     info.activityInfo.applicationInfo.uid, info.activityInfo.packageName,
1528                     info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false);
1529             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1530                 // We won't allow this receiver to be launched if the app has been
1531                 // completely disabled from launches, or it was not explicitly sent
1532                 // to it and the app is in a state that should not receive it
1533                 // (depending on how getAppStartModeLocked has determined that).
1534                 if (allowed == ActivityManager.APP_START_MODE_DISABLED) {
1535                     Slog.w(TAG, "Background execution disabled: receiving "
1536                             + r.intent + " to "
1537                             + component.flattenToShortString());
1538                     skip = true;
1539                 } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0)
1540                         || (r.intent.getComponent() == null
1541                             && r.intent.getPackage() == null
1542                             && ((r.intent.getFlags()
1543                                     & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0)
1544                             && !isSignaturePerm(r.requiredPermissions))) {
1545                     mService.addBackgroundCheckViolationLocked(r.intent.getAction(),
1546                             component.getPackageName());
1547                     Slog.w(TAG, "Background execution not allowed: receiving "
1548                             + r.intent + " to "
1549                             + component.flattenToShortString());
1550                     skip = true;
1551                 }
1552             }
1553         }
1554 
1555         if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction())
1556                 && !mService.mUserController
1557                 .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid),
1558                         0 /* flags */)) {
1559             skip = true;
1560             Slog.w(TAG,
1561                     "Skipping delivery to " + info.activityInfo.packageName + " / "
1562                             + info.activityInfo.applicationInfo.uid + " : user is not running");
1563         }
1564 
1565         if (skip) {
1566             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1567                     "Skipping delivery of ordered [" + mQueueName + "] "
1568                     + r + " for reason described above");
1569             r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED;
1570             r.receiver = null;
1571             r.curFilter = null;
1572             r.state = BroadcastRecord.IDLE;
1573             r.manifestSkipCount++;
1574             scheduleBroadcastsLocked();
1575             return;
1576         }
1577         r.manifestCount++;
1578 
1579         r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED;
1580         r.state = BroadcastRecord.APP_RECEIVE;
1581         r.curComponent = component;
1582         r.curReceiver = info.activityInfo;
1583         if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1584             Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1585                     + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1586                     + receiverUid);
1587         }
1588 
1589         if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1590             scheduleTempWhitelistLocked(receiverUid,
1591                     brOptions.getTemporaryAppWhitelistDuration(), r);
1592         }
1593 
1594         // Broadcast is being executed, its package can't be stopped.
1595         try {
1596             AppGlobals.getPackageManager().setPackageStoppedState(
1597                     r.curComponent.getPackageName(), false, r.userId);
1598         } catch (RemoteException e) {
1599         } catch (IllegalArgumentException e) {
1600             Slog.w(TAG, "Failed trying to unstop package "
1601                     + r.curComponent.getPackageName() + ": " + e);
1602         }
1603 
1604         // Is this receiver's application already running?
1605         if (app != null && app.thread != null && !app.killed) {
1606             try {
1607                 app.addPackage(info.activityInfo.packageName,
1608                         info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats);
1609                 maybeAddAllowBackgroundActivityStartsToken(app, r);
1610                 processCurBroadcastLocked(r, app, skipOomAdj);
1611                 return;
1612             } catch (RemoteException e) {
1613                 Slog.w(TAG, "Exception when sending broadcast to "
1614                       + r.curComponent, e);
1615             } catch (RuntimeException e) {
1616                 Slog.wtf(TAG, "Failed sending broadcast to "
1617                         + r.curComponent + " with " + r.intent, e);
1618                 // If some unexpected exception happened, just skip
1619                 // this broadcast.  At this point we are not in the call
1620                 // from a client, so throwing an exception out from here
1621                 // will crash the entire system instead of just whoever
1622                 // sent the broadcast.
1623                 logBroadcastReceiverDiscardLocked(r);
1624                 finishReceiverLocked(r, r.resultCode, r.resultData,
1625                         r.resultExtras, r.resultAbort, false);
1626                 scheduleBroadcastsLocked();
1627                 // We need to reset the state if we failed to start the receiver.
1628                 r.state = BroadcastRecord.IDLE;
1629                 return;
1630             }
1631 
1632             // If a dead object exception was thrown -- fall through to
1633             // restart the application.
1634         }
1635 
1636         // Not running -- get it started, to be executed when the app comes up.
1637         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1638                 "Need to start app ["
1639                 + mQueueName + "] " + targetProcess + " for broadcast " + r);
1640         if ((r.curApp=mService.startProcessLocked(targetProcess,
1641                 info.activityInfo.applicationInfo, true,
1642                 r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1643                 new HostingRecord("broadcast", r.curComponent),
1644                 (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1645                         == null) {
1646             // Ah, this recipient is unavailable.  Finish it if necessary,
1647             // and mark the broadcast record as ready for the next.
1648             Slog.w(TAG, "Unable to launch app "
1649                     + info.activityInfo.applicationInfo.packageName + "/"
1650                     + receiverUid + " for broadcast "
1651                     + r.intent + ": process is bad");
1652             logBroadcastReceiverDiscardLocked(r);
1653             finishReceiverLocked(r, r.resultCode, r.resultData,
1654                     r.resultExtras, r.resultAbort, false);
1655             scheduleBroadcastsLocked();
1656             r.state = BroadcastRecord.IDLE;
1657             return;
1658         }
1659 
1660         maybeAddAllowBackgroundActivityStartsToken(r.curApp, r);
1661         mPendingBroadcast = r;
1662         mPendingBroadcastRecvIndex = recIdx;
1663     }
1664 
maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r)1665     private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) {
1666         if (r == null || proc == null || !r.allowBackgroundActivityStarts) {
1667             return;
1668         }
1669         String msgToken = (proc.toShortString() + r.toString()).intern();
1670         // first, if there exists a past scheduled request to remove this token, drop
1671         // that request - we don't want the token to be swept from under our feet...
1672         mHandler.removeCallbacksAndMessages(msgToken);
1673         // ...then add the token
1674         proc.addAllowBackgroundActivityStartsToken(r);
1675     }
1676 
setBroadcastTimeoutLocked(long timeoutTime)1677     final void setBroadcastTimeoutLocked(long timeoutTime) {
1678         if (! mPendingBroadcastTimeoutMessage) {
1679             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1680             mHandler.sendMessageAtTime(msg, timeoutTime);
1681             mPendingBroadcastTimeoutMessage = true;
1682         }
1683     }
1684 
cancelBroadcastTimeoutLocked()1685     final void cancelBroadcastTimeoutLocked() {
1686         if (mPendingBroadcastTimeoutMessage) {
1687             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1688             mPendingBroadcastTimeoutMessage = false;
1689         }
1690     }
1691 
broadcastTimeoutLocked(boolean fromMsg)1692     final void broadcastTimeoutLocked(boolean fromMsg) {
1693         if (fromMsg) {
1694             mPendingBroadcastTimeoutMessage = false;
1695         }
1696 
1697         if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) {
1698             return;
1699         }
1700 
1701         long now = SystemClock.uptimeMillis();
1702         BroadcastRecord r = mDispatcher.getActiveBroadcastLocked();
1703         if (fromMsg) {
1704             if (!mService.mProcessesReady) {
1705                 // Only process broadcast timeouts if the system is ready; some early
1706                 // broadcasts do heavy work setting up system facilities
1707                 return;
1708             }
1709 
1710             // If the broadcast is generally exempt from timeout tracking, we're done
1711             if (r.timeoutExempt) {
1712                 if (DEBUG_BROADCAST) {
1713                     Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: "
1714                             + r.intent.getAction());
1715                 }
1716                 return;
1717             }
1718 
1719             long timeoutTime = r.receiverTime + mConstants.TIMEOUT;
1720             if (timeoutTime > now) {
1721                 // We can observe premature timeouts because we do not cancel and reset the
1722                 // broadcast timeout message after each receiver finishes.  Instead, we set up
1723                 // an initial timeout then kick it down the road a little further as needed
1724                 // when it expires.
1725                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1726                         "Premature timeout ["
1727                         + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1728                         + timeoutTime);
1729                 setBroadcastTimeoutLocked(timeoutTime);
1730                 return;
1731             }
1732         }
1733 
1734         if (r.state == BroadcastRecord.WAITING_SERVICES) {
1735             // In this case the broadcast had already finished, but we had decided to wait
1736             // for started services to finish as well before going on.  So if we have actually
1737             // waited long enough time timeout the broadcast, let's give up on the whole thing
1738             // and just move on to the next.
1739             Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null
1740                     ? r.curComponent.flattenToShortString() : "(null)"));
1741             r.curComponent = null;
1742             r.state = BroadcastRecord.IDLE;
1743             processNextBroadcast(false);
1744             return;
1745         }
1746 
1747         // If the receiver app is being debugged we quietly ignore unresponsiveness, just
1748         // tidying up and moving on to the next broadcast without crashing or ANRing this
1749         // app just because it's stopped at a breakpoint.
1750         final boolean debugging = (r.curApp != null && r.curApp.isDebugging());
1751 
1752         Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
1753                 + ", started " + (now - r.receiverTime) + "ms ago");
1754         r.receiverTime = now;
1755         if (!debugging) {
1756             r.anrCount++;
1757         }
1758 
1759         ProcessRecord app = null;
1760         String anrMessage = null;
1761 
1762         Object curReceiver;
1763         if (r.nextReceiver > 0) {
1764             curReceiver = r.receivers.get(r.nextReceiver-1);
1765             r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT;
1766         } else {
1767             curReceiver = r.curReceiver;
1768         }
1769         Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver);
1770         logBroadcastReceiverDiscardLocked(r);
1771         if (curReceiver != null && curReceiver instanceof BroadcastFilter) {
1772             BroadcastFilter bf = (BroadcastFilter)curReceiver;
1773             if (bf.receiverList.pid != 0
1774                     && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1775                 synchronized (mService.mPidsSelfLocked) {
1776                     app = mService.mPidsSelfLocked.get(
1777                             bf.receiverList.pid);
1778                 }
1779             }
1780         } else {
1781             app = r.curApp;
1782         }
1783 
1784         if (app != null) {
1785             anrMessage = "Broadcast of " + r.intent.toString();
1786         }
1787 
1788         if (mPendingBroadcast == r) {
1789             mPendingBroadcast = null;
1790         }
1791 
1792         // Move on to the next receiver.
1793         finishReceiverLocked(r, r.resultCode, r.resultData,
1794                 r.resultExtras, r.resultAbort, false);
1795         scheduleBroadcastsLocked();
1796 
1797         if (!debugging && anrMessage != null) {
1798             // Post the ANR to the handler since we do not want to process ANRs while
1799             // potentially holding our lock.
1800             mHandler.post(new AppNotResponding(app, anrMessage));
1801         }
1802     }
1803 
ringAdvance(int x, final int increment, final int ringSize)1804     private final int ringAdvance(int x, final int increment, final int ringSize) {
1805         x += increment;
1806         if (x < 0) return (ringSize - 1);
1807         else if (x >= ringSize) return 0;
1808         else return x;
1809     }
1810 
addBroadcastToHistoryLocked(BroadcastRecord original)1811     private final void addBroadcastToHistoryLocked(BroadcastRecord original) {
1812         if (original.callingUid < 0) {
1813             // This was from a registerReceiver() call; ignore it.
1814             return;
1815         }
1816         original.finishTime = SystemClock.uptimeMillis();
1817 
1818         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
1819             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER,
1820                 createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED),
1821                 System.identityHashCode(original));
1822         }
1823 
1824         // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords,
1825         // So don't change the incoming record directly.
1826         final BroadcastRecord historyRecord = original.maybeStripForHistory();
1827 
1828         mBroadcastHistory[mHistoryNext] = historyRecord;
1829         mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1830 
1831         mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent;
1832         mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime;
1833         mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime;
1834         mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1835         mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1836     }
1837 
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)1838     boolean cleanupDisabledPackageReceiversLocked(
1839             String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1840         boolean didSomething = false;
1841         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1842             didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1843                     packageName, filterByClasses, userId, doit);
1844             if (!doit && didSomething) {
1845                 return true;
1846             }
1847         }
1848 
1849         didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName,
1850                 filterByClasses, userId, doit);
1851 
1852         return didSomething;
1853     }
1854 
logBroadcastReceiverDiscardLocked(BroadcastRecord r)1855     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1856         final int logIndex = r.nextReceiver - 1;
1857         if (logIndex >= 0 && logIndex < r.receivers.size()) {
1858             Object curReceiver = r.receivers.get(logIndex);
1859             if (curReceiver instanceof BroadcastFilter) {
1860                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1861                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1862                         bf.owningUserId, System.identityHashCode(r),
1863                         r.intent.getAction(), logIndex, System.identityHashCode(bf));
1864             } else {
1865                 ResolveInfo ri = (ResolveInfo) curReceiver;
1866                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1867                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1868                         System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1869             }
1870         } else {
1871             if (logIndex < 0) Slog.w(TAG,
1872                     "Discarding broadcast before first receiver is invoked: " + r);
1873             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1874                     -1, System.identityHashCode(r),
1875                     r.intent.getAction(),
1876                     r.nextReceiver,
1877                     "NONE");
1878         }
1879     }
1880 
createBroadcastTraceTitle(BroadcastRecord record, int state)1881     private String createBroadcastTraceTitle(BroadcastRecord record, int state) {
1882         return String.format("Broadcast %s from %s (%s) %s",
1883                 state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched",
1884                 record.callerPackage == null ? "" : record.callerPackage,
1885                 record.callerApp == null ? "process unknown" : record.callerApp.toShortString(),
1886                 record.intent == null ? "" : record.intent.getAction());
1887     }
1888 
isIdle()1889     boolean isIdle() {
1890         return mParallelBroadcasts.isEmpty() && mDispatcher.isEmpty()
1891                 && (mPendingBroadcast == null);
1892     }
1893 
1894     // Used by wait-for-broadcast-idle : fast-forward all current deferrals to
1895     // be immediately deliverable.
cancelDeferrals()1896     void cancelDeferrals() {
1897         synchronized (mService) {
1898             mDispatcher.cancelDeferralsLocked();
1899             scheduleBroadcastsLocked();
1900         }
1901     }
1902 
describeState()1903     String describeState() {
1904         synchronized (mService) {
1905             return mParallelBroadcasts.size() + " parallel; "
1906                     + mDispatcher.describeStateLocked();
1907         }
1908     }
1909 
writeToProto(ProtoOutputStream proto, long fieldId)1910     void writeToProto(ProtoOutputStream proto, long fieldId) {
1911         long token = proto.start(fieldId);
1912         proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName);
1913         int N;
1914         N = mParallelBroadcasts.size();
1915         for (int i = N - 1; i >= 0; i--) {
1916             mParallelBroadcasts.get(i).writeToProto(proto, BroadcastQueueProto.PARALLEL_BROADCASTS);
1917         }
1918         mDispatcher.writeToProto(proto, BroadcastQueueProto.ORDERED_BROADCASTS);
1919         if (mPendingBroadcast != null) {
1920             mPendingBroadcast.writeToProto(proto, BroadcastQueueProto.PENDING_BROADCAST);
1921         }
1922 
1923         int lastIndex = mHistoryNext;
1924         int ringIndex = lastIndex;
1925         do {
1926             // increasing index = more recent entry, and we want to print the most
1927             // recent first and work backwards, so we roll through the ring backwards.
1928             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1929             BroadcastRecord r = mBroadcastHistory[ringIndex];
1930             if (r != null) {
1931                 r.writeToProto(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS);
1932             }
1933         } while (ringIndex != lastIndex);
1934 
1935         lastIndex = ringIndex = mSummaryHistoryNext;
1936         do {
1937             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1938             Intent intent = mBroadcastSummaryHistory[ringIndex];
1939             if (intent == null) {
1940                 continue;
1941             }
1942             long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY);
1943             intent.writeToProto(proto, BroadcastQueueProto.BroadcastSummary.INTENT,
1944                     false, true, true, false);
1945             proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS,
1946                     mSummaryHistoryEnqueueTime[ringIndex]);
1947             proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS,
1948                     mSummaryHistoryDispatchTime[ringIndex]);
1949             proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS,
1950                     mSummaryHistoryFinishTime[ringIndex]);
1951             proto.end(summaryToken);
1952         } while (ringIndex != lastIndex);
1953         proto.end(token);
1954     }
1955 
dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean needSep)1956     final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1957             int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1958         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
1959         if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty()
1960                 || mPendingBroadcast != null) {
1961             boolean printed = false;
1962             for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1963                 BroadcastRecord br = mParallelBroadcasts.get(i);
1964                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1965                     continue;
1966                 }
1967                 if (!printed) {
1968                     if (needSep) {
1969                         pw.println();
1970                     }
1971                     needSep = true;
1972                     printed = true;
1973                     pw.println("  Active broadcasts [" + mQueueName + "]:");
1974                 }
1975                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1976                 br.dump(pw, "    ", sdf);
1977             }
1978 
1979             mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf);
1980 
1981             if (dumpPackage == null || (mPendingBroadcast != null
1982                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1983                 pw.println();
1984                 pw.println("  Pending broadcast [" + mQueueName + "]:");
1985                 if (mPendingBroadcast != null) {
1986                     mPendingBroadcast.dump(pw, "    ", sdf);
1987                 } else {
1988                     pw.println("    (null)");
1989                 }
1990                 needSep = true;
1991             }
1992         }
1993 
1994         mConstants.dump(pw);
1995 
1996         int i;
1997         boolean printed = false;
1998 
1999         i = -1;
2000         int lastIndex = mHistoryNext;
2001         int ringIndex = lastIndex;
2002         do {
2003             // increasing index = more recent entry, and we want to print the most
2004             // recent first and work backwards, so we roll through the ring backwards.
2005             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
2006             BroadcastRecord r = mBroadcastHistory[ringIndex];
2007             if (r == null) {
2008                 continue;
2009             }
2010 
2011             i++; // genuine record of some sort even if we're filtering it out
2012             if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
2013                 continue;
2014             }
2015             if (!printed) {
2016                 if (needSep) {
2017                     pw.println();
2018                 }
2019                 needSep = true;
2020                 pw.println("  Historical broadcasts [" + mQueueName + "]:");
2021                 printed = true;
2022             }
2023             if (dumpAll) {
2024                 pw.print("  Historical Broadcast " + mQueueName + " #");
2025                         pw.print(i); pw.println(":");
2026                 r.dump(pw, "    ", sdf);
2027             } else {
2028                 pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
2029                 pw.print("    ");
2030                 pw.println(r.intent.toShortString(false, true, true, false));
2031                 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
2032                     pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
2033                 }
2034                 Bundle bundle = r.intent.getExtras();
2035                 if (bundle != null) {
2036                     pw.print("    extras: "); pw.println(bundle.toString());
2037                 }
2038             }
2039         } while (ringIndex != lastIndex);
2040 
2041         if (dumpPackage == null) {
2042             lastIndex = ringIndex = mSummaryHistoryNext;
2043             if (dumpAll) {
2044                 printed = false;
2045                 i = -1;
2046             } else {
2047                 // roll over the 'i' full dumps that have already been issued
2048                 for (int j = i;
2049                         j > 0 && ringIndex != lastIndex;) {
2050                     ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2051                     BroadcastRecord r = mBroadcastHistory[ringIndex];
2052                     if (r == null) {
2053                         continue;
2054                     }
2055                     j--;
2056                 }
2057             }
2058             // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
2059             // the overall broadcast history.
2060             do {
2061                 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
2062                 Intent intent = mBroadcastSummaryHistory[ringIndex];
2063                 if (intent == null) {
2064                     continue;
2065                 }
2066                 if (!printed) {
2067                     if (needSep) {
2068                         pw.println();
2069                     }
2070                     needSep = true;
2071                     pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
2072                     printed = true;
2073                 }
2074                 if (!dumpAll && i >= 50) {
2075                     pw.println("  ...");
2076                     break;
2077                 }
2078                 i++;
2079                 pw.print("  #"); pw.print(i); pw.print(": ");
2080                 pw.println(intent.toShortString(false, true, true, false));
2081                 pw.print("    ");
2082                 TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex]
2083                         - mSummaryHistoryEnqueueTime[ringIndex], pw);
2084                 pw.print(" dispatch ");
2085                 TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex]
2086                         - mSummaryHistoryDispatchTime[ringIndex], pw);
2087                 pw.println(" finish");
2088                 pw.print("    enq=");
2089                 pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
2090                 pw.print(" disp=");
2091                 pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
2092                 pw.print(" fin=");
2093                 pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
2094                 Bundle bundle = intent.getExtras();
2095                 if (bundle != null) {
2096                     pw.print("    extras: "); pw.println(bundle.toString());
2097                 }
2098             } while (ringIndex != lastIndex);
2099         }
2100 
2101         return needSep;
2102     }
2103 }
2104