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 java.io.FileDescriptor;
20 import java.io.PrintWriter;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Date;
24 import java.util.Set;
25 
26 import android.app.ActivityManager;
27 import android.app.AppGlobals;
28 import android.app.AppOpsManager;
29 import android.app.BroadcastOptions;
30 import android.content.ComponentName;
31 import android.content.IIntentReceiver;
32 import android.content.Intent;
33 import android.content.pm.ActivityInfo;
34 import android.content.pm.PackageManager;
35 import android.content.pm.ResolveInfo;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.IBinder;
39 import android.os.Looper;
40 import android.os.Message;
41 import android.os.Process;
42 import android.os.RemoteException;
43 import android.os.SystemClock;
44 import android.os.UserHandle;
45 import android.util.EventLog;
46 import android.util.Slog;
47 import com.android.server.DeviceIdleController;
48 
49 import static com.android.server.am.ActivityManagerDebugConfig.*;
50 
51 /**
52  * BROADCASTS
53  *
54  * We keep two broadcast queues and associated bookkeeping, one for those at
55  * foreground priority, and one for normal (background-priority) broadcasts.
56  */
57 public final class BroadcastQueue {
58     private static final String TAG = "BroadcastQueue";
59     private static final String TAG_MU = TAG + POSTFIX_MU;
60     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
61 
62     static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50;
63     static final int MAX_BROADCAST_SUMMARY_HISTORY
64             = ActivityManager.isLowRamDeviceStatic() ? 25 : 300;
65 
66     final ActivityManagerService mService;
67 
68     /**
69      * Recognizable moniker for this queue
70      */
71     final String mQueueName;
72 
73     /**
74      * Timeout period for this queue's broadcasts
75      */
76     final long mTimeoutPeriod;
77 
78     /**
79      * If true, we can delay broadcasts while waiting services to finish in the previous
80      * receiver's process.
81      */
82     final boolean mDelayBehindServices;
83 
84     /**
85      * Lists of all active broadcasts that are to be executed immediately
86      * (without waiting for another broadcast to finish).  Currently this only
87      * contains broadcasts to registered receivers, to avoid spinning up
88      * a bunch of processes to execute IntentReceiver components.  Background-
89      * and foreground-priority broadcasts are queued separately.
90      */
91     final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>();
92 
93     /**
94      * List of all active broadcasts that are to be executed one at a time.
95      * The object at the top of the list is the currently activity broadcasts;
96      * those after it are waiting for the top to finish.  As with parallel
97      * broadcasts, separate background- and foreground-priority queues are
98      * maintained.
99      */
100     final ArrayList<BroadcastRecord> mOrderedBroadcasts = new ArrayList<>();
101 
102     /**
103      * Historical data of past broadcasts, for debugging.  This is a ring buffer
104      * whose last element is at mHistoryNext.
105      */
106     final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY];
107     int mHistoryNext = 0;
108 
109     /**
110      * Summary of historical data of past broadcasts, for debugging.  This is a
111      * ring buffer whose last element is at mSummaryHistoryNext.
112      */
113     final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
114     int mSummaryHistoryNext = 0;
115 
116     /**
117      * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring
118      * buffer, also tracked via the mSummaryHistoryNext index.  These are all in wall
119      * clock time, not elapsed.
120      */
121     final long[] mSummaryHistoryEnqueueTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
122     final long[] mSummaryHistoryDispatchTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
123     final long[] mSummaryHistoryFinishTime = new  long[MAX_BROADCAST_SUMMARY_HISTORY];
124 
125     /**
126      * Set when we current have a BROADCAST_INTENT_MSG in flight.
127      */
128     boolean mBroadcastsScheduled = false;
129 
130     /**
131      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
132      */
133     boolean mPendingBroadcastTimeoutMessage;
134 
135     /**
136      * Intent broadcasts that we have tried to start, but are
137      * waiting for the application's process to be created.  We only
138      * need one per scheduling class (instead of a list) because we always
139      * process broadcasts one at a time, so no others can be started while
140      * waiting for this one.
141      */
142     BroadcastRecord mPendingBroadcast = null;
143 
144     /**
145      * The receiver index that is pending, to restart the broadcast if needed.
146      */
147     int mPendingBroadcastRecvIndex;
148 
149     static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
150     static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
151     static final int SCHEDULE_TEMP_WHITELIST_MSG
152             = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 2;
153 
154     final BroadcastHandler mHandler;
155 
156     private final class BroadcastHandler extends Handler {
BroadcastHandler(Looper looper)157         public BroadcastHandler(Looper looper) {
158             super(looper, null, true);
159         }
160 
161         @Override
handleMessage(Message msg)162         public void handleMessage(Message msg) {
163             switch (msg.what) {
164                 case BROADCAST_INTENT_MSG: {
165                     if (DEBUG_BROADCAST) Slog.v(
166                             TAG_BROADCAST, "Received BROADCAST_INTENT_MSG");
167                     processNextBroadcast(true);
168                 } break;
169                 case BROADCAST_TIMEOUT_MSG: {
170                     synchronized (mService) {
171                         broadcastTimeoutLocked(true);
172                     }
173                 } break;
174                 case SCHEDULE_TEMP_WHITELIST_MSG: {
175                     DeviceIdleController.LocalService dic = mService.mLocalDeviceIdleController;
176                     if (dic != null) {
177                         dic.addPowerSaveTempWhitelistAppDirect(UserHandle.getAppId(msg.arg1),
178                                 msg.arg2, true, (String)msg.obj);
179                     }
180                 } break;
181             }
182         }
183     };
184 
185     private final class AppNotResponding implements Runnable {
186         private final ProcessRecord mApp;
187         private final String mAnnotation;
188 
AppNotResponding(ProcessRecord app, String annotation)189         public AppNotResponding(ProcessRecord app, String annotation) {
190             mApp = app;
191             mAnnotation = annotation;
192         }
193 
194         @Override
run()195         public void run() {
196             mService.appNotResponding(mApp, null, null, false, mAnnotation);
197         }
198     }
199 
BroadcastQueue(ActivityManagerService service, Handler handler, String name, long timeoutPeriod, boolean allowDelayBehindServices)200     BroadcastQueue(ActivityManagerService service, Handler handler,
201             String name, long timeoutPeriod, boolean allowDelayBehindServices) {
202         mService = service;
203         mHandler = new BroadcastHandler(handler.getLooper());
204         mQueueName = name;
205         mTimeoutPeriod = timeoutPeriod;
206         mDelayBehindServices = allowDelayBehindServices;
207     }
208 
isPendingBroadcastProcessLocked(int pid)209     public boolean isPendingBroadcastProcessLocked(int pid) {
210         return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
211     }
212 
enqueueParallelBroadcastLocked(BroadcastRecord r)213     public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
214         mParallelBroadcasts.add(r);
215         r.enqueueClockTime = System.currentTimeMillis();
216     }
217 
enqueueOrderedBroadcastLocked(BroadcastRecord r)218     public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
219         mOrderedBroadcasts.add(r);
220         r.enqueueClockTime = System.currentTimeMillis();
221     }
222 
replaceParallelBroadcastLocked(BroadcastRecord r)223     public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
224         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
225             if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
226                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
227                         "***** DROPPING PARALLEL ["
228                 + mQueueName + "]: " + r.intent);
229                 mParallelBroadcasts.set(i, r);
230                 return true;
231             }
232         }
233         return false;
234     }
235 
replaceOrderedBroadcastLocked(BroadcastRecord r)236     public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
237         for (int i = mOrderedBroadcasts.size() - 1; i > 0; i--) {
238             if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
239                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
240                         "***** DROPPING ORDERED ["
241                         + mQueueName + "]: " + r.intent);
242                 mOrderedBroadcasts.set(i, r);
243                 return true;
244             }
245         }
246         return false;
247     }
248 
processCurBroadcastLocked(BroadcastRecord r, ProcessRecord app)249     private final void processCurBroadcastLocked(BroadcastRecord r,
250             ProcessRecord app) throws RemoteException {
251         if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
252                 "Process cur broadcast " + r + " for app " + app);
253         if (app.thread == null) {
254             throw new RemoteException();
255         }
256         r.receiver = app.thread.asBinder();
257         r.curApp = app;
258         app.curReceiver = r;
259         app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
260         mService.updateLruProcessLocked(app, false, null);
261         mService.updateOomAdjLocked();
262 
263         // Tell the application to launch this receiver.
264         r.intent.setComponent(r.curComponent);
265 
266         boolean started = false;
267         try {
268             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
269                     "Delivering to component " + r.curComponent
270                     + ": " + r);
271             mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
272             app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
273                     mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
274                     r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
275                     app.repProcState);
276             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
277                     "Process cur broadcast " + r + " DELIVERED for app " + app);
278             started = true;
279         } finally {
280             if (!started) {
281                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
282                         "Process cur broadcast " + r + ": NOT STARTED!");
283                 r.receiver = null;
284                 r.curApp = null;
285                 app.curReceiver = null;
286             }
287         }
288     }
289 
sendPendingBroadcastsLocked(ProcessRecord app)290     public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
291         boolean didSomething = false;
292         final BroadcastRecord br = mPendingBroadcast;
293         if (br != null && br.curApp.pid == app.pid) {
294             try {
295                 mPendingBroadcast = null;
296                 processCurBroadcastLocked(br, app);
297                 didSomething = true;
298             } catch (Exception e) {
299                 Slog.w(TAG, "Exception in new application when starting receiver "
300                         + br.curComponent.flattenToShortString(), e);
301                 logBroadcastReceiverDiscardLocked(br);
302                 finishReceiverLocked(br, br.resultCode, br.resultData,
303                         br.resultExtras, br.resultAbort, false);
304                 scheduleBroadcastsLocked();
305                 // We need to reset the state if we failed to start the receiver.
306                 br.state = BroadcastRecord.IDLE;
307                 throw new RuntimeException(e.getMessage());
308             }
309         }
310         return didSomething;
311     }
312 
skipPendingBroadcastLocked(int pid)313     public void skipPendingBroadcastLocked(int pid) {
314         final BroadcastRecord br = mPendingBroadcast;
315         if (br != null && br.curApp.pid == pid) {
316             br.state = BroadcastRecord.IDLE;
317             br.nextReceiver = mPendingBroadcastRecvIndex;
318             mPendingBroadcast = null;
319             scheduleBroadcastsLocked();
320         }
321     }
322 
skipCurrentReceiverLocked(ProcessRecord app)323     public void skipCurrentReceiverLocked(ProcessRecord app) {
324         BroadcastRecord r = null;
325         if (mOrderedBroadcasts.size() > 0) {
326             BroadcastRecord br = mOrderedBroadcasts.get(0);
327             if (br.curApp == app) {
328                 r = br;
329             }
330         }
331         if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
332             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
333                     "[" + mQueueName + "] skip & discard pending app " + r);
334             r = mPendingBroadcast;
335         }
336 
337         if (r != null) {
338             logBroadcastReceiverDiscardLocked(r);
339             finishReceiverLocked(r, r.resultCode, r.resultData,
340                     r.resultExtras, r.resultAbort, false);
341             scheduleBroadcastsLocked();
342         }
343     }
344 
scheduleBroadcastsLocked()345     public void scheduleBroadcastsLocked() {
346         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
347                 + mQueueName + "]: current="
348                 + mBroadcastsScheduled);
349 
350         if (mBroadcastsScheduled) {
351             return;
352         }
353         mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
354         mBroadcastsScheduled = true;
355     }
356 
getMatchingOrderedReceiver(IBinder receiver)357     public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
358         if (mOrderedBroadcasts.size() > 0) {
359             final BroadcastRecord r = mOrderedBroadcasts.get(0);
360             if (r != null && r.receiver == receiver) {
361                 return r;
362             }
363         }
364         return null;
365     }
366 
finishReceiverLocked(BroadcastRecord r, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices)367     public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
368             String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) {
369         final int state = r.state;
370         final ActivityInfo receiver = r.curReceiver;
371         r.state = BroadcastRecord.IDLE;
372         if (state == BroadcastRecord.IDLE) {
373             Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
374         }
375         r.receiver = null;
376         r.intent.setComponent(null);
377         if (r.curApp != null && r.curApp.curReceiver == r) {
378             r.curApp.curReceiver = null;
379         }
380         if (r.curFilter != null) {
381             r.curFilter.receiverList.curBroadcast = null;
382         }
383         r.curFilter = null;
384         r.curReceiver = null;
385         r.curApp = null;
386         mPendingBroadcast = null;
387 
388         r.resultCode = resultCode;
389         r.resultData = resultData;
390         r.resultExtras = resultExtras;
391         if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) {
392             r.resultAbort = resultAbort;
393         } else {
394             r.resultAbort = false;
395         }
396 
397         if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices
398                 && r.queue.mOrderedBroadcasts.size() > 0
399                 && r.queue.mOrderedBroadcasts.get(0) == r) {
400             ActivityInfo nextReceiver;
401             if (r.nextReceiver < r.receivers.size()) {
402                 Object obj = r.receivers.get(r.nextReceiver);
403                 nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null;
404             } else {
405                 nextReceiver = null;
406             }
407             // Don't do this if the next receive is in the same process as the current one.
408             if (receiver == null || nextReceiver == null
409                     || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid
410                     || !receiver.processName.equals(nextReceiver.processName)) {
411                 // In this case, we are ready to process the next receiver for the current broadcast,
412                 // but are on a queue that would like to wait for services to finish before moving
413                 // on.  If there are background services currently starting, then we will go into a
414                 // special state where we hold off on continuing this broadcast until they are done.
415                 if (mService.mServices.hasBackgroundServices(r.userId)) {
416                     Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString());
417                     r.state = BroadcastRecord.WAITING_SERVICES;
418                     return false;
419                 }
420             }
421         }
422 
423         r.curComponent = null;
424 
425         // We will process the next receiver right now if this is finishing
426         // an app receiver (which is always asynchronous) or after we have
427         // come back from calling a receiver.
428         return state == BroadcastRecord.APP_RECEIVE
429                 || state == BroadcastRecord.CALL_DONE_RECEIVE;
430     }
431 
backgroundServicesFinishedLocked(int userId)432     public void backgroundServicesFinishedLocked(int userId) {
433         if (mOrderedBroadcasts.size() > 0) {
434             BroadcastRecord br = mOrderedBroadcasts.get(0);
435             if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) {
436                 Slog.i(TAG, "Resuming delayed broadcast");
437                 br.curComponent = null;
438                 br.state = BroadcastRecord.IDLE;
439                 processNextBroadcast(false);
440             }
441         }
442     }
443 
performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser)444     private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
445             Intent intent, int resultCode, String data, Bundle extras,
446             boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
447         // Send the intent to the receiver asynchronously using one-way binder calls.
448         if (app != null) {
449             if (app.thread != null) {
450                 // If we have an app thread, do the call through that so it is
451                 // correctly ordered with other one-way calls.
452                 app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
453                         data, extras, ordered, sticky, sendingUser, app.repProcState);
454             } else {
455                 // Application has died. Receiver doesn't exist.
456                 throw new RemoteException("app.thread must not be null");
457             }
458         } else {
459             receiver.performReceive(intent, resultCode, data, extras, ordered,
460                     sticky, sendingUser);
461         }
462     }
463 
deliverToRegisteredReceiverLocked(BroadcastRecord r, BroadcastFilter filter, boolean ordered)464     private void deliverToRegisteredReceiverLocked(BroadcastRecord r,
465             BroadcastFilter filter, boolean ordered) {
466         boolean skip = false;
467         if (filter.requiredPermission != null) {
468             int perm = mService.checkComponentPermission(filter.requiredPermission,
469                     r.callingPid, r.callingUid, -1, true);
470             if (perm != PackageManager.PERMISSION_GRANTED) {
471                 Slog.w(TAG, "Permission Denial: broadcasting "
472                         + r.intent.toString()
473                         + " from " + r.callerPackage + " (pid="
474                         + r.callingPid + ", uid=" + r.callingUid + ")"
475                         + " requires " + filter.requiredPermission
476                         + " due to registered receiver " + filter);
477                 skip = true;
478             } else {
479                 final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission);
480                 if (opCode != AppOpsManager.OP_NONE
481                         && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
482                                 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
483                     Slog.w(TAG, "Appop Denial: broadcasting "
484                             + r.intent.toString()
485                             + " from " + r.callerPackage + " (pid="
486                             + r.callingPid + ", uid=" + r.callingUid + ")"
487                             + " requires appop " + AppOpsManager.permissionToOp(
488                                     filter.requiredPermission)
489                             + " due to registered receiver " + filter);
490                     skip = true;
491                 }
492             }
493         }
494         if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) {
495             for (int i = 0; i < r.requiredPermissions.length; i++) {
496                 String requiredPermission = r.requiredPermissions[i];
497                 int perm = mService.checkComponentPermission(requiredPermission,
498                         filter.receiverList.pid, filter.receiverList.uid, -1, true);
499                 if (perm != PackageManager.PERMISSION_GRANTED) {
500                     Slog.w(TAG, "Permission Denial: receiving "
501                             + r.intent.toString()
502                             + " to " + filter.receiverList.app
503                             + " (pid=" + filter.receiverList.pid
504                             + ", uid=" + filter.receiverList.uid + ")"
505                             + " requires " + requiredPermission
506                             + " due to sender " + r.callerPackage
507                             + " (uid " + r.callingUid + ")");
508                     skip = true;
509                     break;
510                 }
511                 int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
512                 if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
513                         && mService.mAppOpsService.noteOperation(appOp,
514                         filter.receiverList.uid, filter.packageName)
515                         != AppOpsManager.MODE_ALLOWED) {
516                     Slog.w(TAG, "Appop Denial: receiving "
517                             + r.intent.toString()
518                             + " to " + filter.receiverList.app
519                             + " (pid=" + filter.receiverList.pid
520                             + ", uid=" + filter.receiverList.uid + ")"
521                             + " requires appop " + AppOpsManager.permissionToOp(
522                             requiredPermission)
523                             + " due to sender " + r.callerPackage
524                             + " (uid " + r.callingUid + ")");
525                     skip = true;
526                     break;
527                 }
528             }
529         }
530         if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) {
531             int perm = mService.checkComponentPermission(null,
532                     filter.receiverList.pid, filter.receiverList.uid, -1, true);
533             if (perm != PackageManager.PERMISSION_GRANTED) {
534                 Slog.w(TAG, "Permission Denial: security check failed when receiving "
535                         + r.intent.toString()
536                         + " to " + filter.receiverList.app
537                         + " (pid=" + filter.receiverList.pid
538                         + ", uid=" + filter.receiverList.uid + ")"
539                         + " due to sender " + r.callerPackage
540                         + " (uid " + r.callingUid + ")");
541                 skip = true;
542             }
543         }
544         if (!skip && r.appOp != AppOpsManager.OP_NONE
545                 && mService.mAppOpsService.noteOperation(r.appOp,
546                 filter.receiverList.uid, filter.packageName)
547                 != AppOpsManager.MODE_ALLOWED) {
548             Slog.w(TAG, "Appop Denial: receiving "
549                     + r.intent.toString()
550                     + " to " + filter.receiverList.app
551                     + " (pid=" + filter.receiverList.pid
552                     + ", uid=" + filter.receiverList.uid + ")"
553                     + " requires appop " + AppOpsManager.opToName(r.appOp)
554                     + " due to sender " + r.callerPackage
555                     + " (uid " + r.callingUid + ")");
556             skip = true;
557         }
558 
559         if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
560                 r.callingPid, r.resolvedType, filter.receiverList.uid)) {
561             return;
562         }
563 
564         if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
565             Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r
566                     + " to " + filter.receiverList + ": process crashing");
567             skip = true;
568         }
569 
570         if (!skip) {
571             // If this is not being sent as an ordered broadcast, then we
572             // don't want to touch the fields that keep track of the current
573             // state of ordered broadcasts.
574             if (ordered) {
575                 r.receiver = filter.receiverList.receiver.asBinder();
576                 r.curFilter = filter;
577                 filter.receiverList.curBroadcast = r;
578                 r.state = BroadcastRecord.CALL_IN_RECEIVE;
579                 if (filter.receiverList.app != null) {
580                     // Bump hosting application to no longer be in background
581                     // scheduling class.  Note that we can't do that if there
582                     // isn't an app...  but we can only be in that case for
583                     // things that directly call the IActivityManager API, which
584                     // are already core system stuff so don't matter for this.
585                     r.curApp = filter.receiverList.app;
586                     filter.receiverList.app.curReceiver = r;
587                     mService.updateOomAdjLocked(r.curApp);
588                 }
589             }
590             try {
591                 if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST,
592                         "Delivering to " + filter + " : " + r);
593                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
594                         new Intent(r.intent), r.resultCode, r.resultData,
595                         r.resultExtras, r.ordered, r.initialSticky, r.userId);
596                 if (ordered) {
597                     r.state = BroadcastRecord.CALL_DONE_RECEIVE;
598                 }
599             } catch (RemoteException e) {
600                 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
601                 if (ordered) {
602                     r.receiver = null;
603                     r.curFilter = null;
604                     filter.receiverList.curBroadcast = null;
605                     if (filter.receiverList.app != null) {
606                         filter.receiverList.app.curReceiver = null;
607                     }
608                 }
609             }
610         }
611     }
612 
scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r)613     final void scheduleTempWhitelistLocked(int uid, long duration, BroadcastRecord r) {
614         if (duration > Integer.MAX_VALUE) {
615             duration = Integer.MAX_VALUE;
616         }
617         // XXX ideally we should pause the broadcast until everything behind this is done,
618         // or else we will likely start dispatching the broadcast before we have opened
619         // access to the app (there is a lot of asynchronicity behind this).  It is probably
620         // not that big a deal, however, because the main purpose here is to allow apps
621         // to hold wake locks, and they will be able to acquire their wake lock immediately
622         // it just won't be enabled until we get through this work.
623         StringBuilder b = new StringBuilder();
624         b.append("broadcast:");
625         UserHandle.formatUid(b, r.callingUid);
626         b.append(":");
627         if (r.intent.getAction() != null) {
628             b.append(r.intent.getAction());
629         } else if (r.intent.getComponent() != null) {
630             b.append(r.intent.getComponent().flattenToShortString());
631         } else if (r.intent.getData() != null) {
632             b.append(r.intent.getData());
633         }
634         mHandler.obtainMessage(SCHEDULE_TEMP_WHITELIST_MSG, uid, (int)duration, b.toString())
635                 .sendToTarget();
636     }
637 
processNextBroadcast(boolean fromMsg)638     final void processNextBroadcast(boolean fromMsg) {
639         synchronized(mService) {
640             BroadcastRecord r;
641 
642             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast ["
643                     + mQueueName + "]: "
644                     + mParallelBroadcasts.size() + " broadcasts, "
645                     + mOrderedBroadcasts.size() + " ordered broadcasts");
646 
647             mService.updateCpuStats();
648 
649             if (fromMsg) {
650                 mBroadcastsScheduled = false;
651             }
652 
653             // First, deliver any non-serialized broadcasts right away.
654             while (mParallelBroadcasts.size() > 0) {
655                 r = mParallelBroadcasts.remove(0);
656                 r.dispatchTime = SystemClock.uptimeMillis();
657                 r.dispatchClockTime = System.currentTimeMillis();
658                 final int N = r.receivers.size();
659                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast ["
660                         + mQueueName + "] " + r);
661                 for (int i=0; i<N; i++) {
662                     Object target = r.receivers.get(i);
663                     if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
664                             "Delivering non-ordered on [" + mQueueName + "] to registered "
665                             + target + ": " + r);
666                     deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
667                 }
668                 addBroadcastToHistoryLocked(r);
669                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast ["
670                         + mQueueName + "] " + r);
671             }
672 
673             // Now take care of the next serialized one...
674 
675             // If we are waiting for a process to come up to handle the next
676             // broadcast, then do nothing at this point.  Just in case, we
677             // check that the process we're waiting for still exists.
678             if (mPendingBroadcast != null) {
679                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
680                         "processNextBroadcast [" + mQueueName + "]: waiting for "
681                         + mPendingBroadcast.curApp);
682 
683                 boolean isDead;
684                 synchronized (mService.mPidsSelfLocked) {
685                     ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
686                     isDead = proc == null || proc.crashing;
687                 }
688                 if (!isDead) {
689                     // It's still alive, so keep waiting
690                     return;
691                 } else {
692                     Slog.w(TAG, "pending app  ["
693                             + mQueueName + "]" + mPendingBroadcast.curApp
694                             + " died before responding to broadcast");
695                     mPendingBroadcast.state = BroadcastRecord.IDLE;
696                     mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
697                     mPendingBroadcast = null;
698                 }
699             }
700 
701             boolean looped = false;
702 
703             do {
704                 if (mOrderedBroadcasts.size() == 0) {
705                     // No more broadcasts pending, so all done!
706                     mService.scheduleAppGcsLocked();
707                     if (looped) {
708                         // If we had finished the last ordered broadcast, then
709                         // make sure all processes have correct oom and sched
710                         // adjustments.
711                         mService.updateOomAdjLocked();
712                     }
713                     return;
714                 }
715                 r = mOrderedBroadcasts.get(0);
716                 boolean forceReceive = false;
717 
718                 // Ensure that even if something goes awry with the timeout
719                 // detection, we catch "hung" broadcasts here, discard them,
720                 // and continue to make progress.
721                 //
722                 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
723                 // receivers don't get executed with timeouts. They're intended for
724                 // one time heavy lifting after system upgrades and can take
725                 // significant amounts of time.
726                 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
727                 if (mService.mProcessesReady && r.dispatchTime > 0) {
728                     long now = SystemClock.uptimeMillis();
729                     if ((numReceivers > 0) &&
730                             (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
731                         Slog.w(TAG, "Hung broadcast ["
732                                 + mQueueName + "] discarded after timeout failure:"
733                                 + " now=" + now
734                                 + " dispatchTime=" + r.dispatchTime
735                                 + " startTime=" + r.receiverTime
736                                 + " intent=" + r.intent
737                                 + " numReceivers=" + numReceivers
738                                 + " nextReceiver=" + r.nextReceiver
739                                 + " state=" + r.state);
740                         broadcastTimeoutLocked(false); // forcibly finish this broadcast
741                         forceReceive = true;
742                         r.state = BroadcastRecord.IDLE;
743                     }
744                 }
745 
746                 if (r.state != BroadcastRecord.IDLE) {
747                     if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST,
748                             "processNextBroadcast("
749                             + mQueueName + ") called when not idle (state="
750                             + r.state + ")");
751                     return;
752                 }
753 
754                 if (r.receivers == null || r.nextReceiver >= numReceivers
755                         || r.resultAbort || forceReceive) {
756                     // No more receivers for this broadcast!  Send the final
757                     // result if requested...
758                     if (r.resultTo != null) {
759                         try {
760                             if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST,
761                                     "Finishing broadcast [" + mQueueName + "] "
762                                     + r.intent.getAction() + " app=" + r.callerApp);
763                             performReceiveLocked(r.callerApp, r.resultTo,
764                                 new Intent(r.intent), r.resultCode,
765                                 r.resultData, r.resultExtras, false, false, r.userId);
766                             // Set this to null so that the reference
767                             // (local and remote) isn't kept in the mBroadcastHistory.
768                             r.resultTo = null;
769                         } catch (RemoteException e) {
770                             r.resultTo = null;
771                             Slog.w(TAG, "Failure ["
772                                     + mQueueName + "] sending broadcast result of "
773                                     + r.intent, e);
774                         }
775                     }
776 
777                     if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG");
778                     cancelBroadcastTimeoutLocked();
779 
780                     if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
781                             "Finished with ordered broadcast " + r);
782 
783                     // ... and on to the next...
784                     addBroadcastToHistoryLocked(r);
785                     mOrderedBroadcasts.remove(0);
786                     r = null;
787                     looped = true;
788                     continue;
789                 }
790             } while (r == null);
791 
792             // Get the next receiver...
793             int recIdx = r.nextReceiver++;
794 
795             // Keep track of when this receiver started, and make sure there
796             // is a timeout message pending to kill it if need be.
797             r.receiverTime = SystemClock.uptimeMillis();
798             if (recIdx == 0) {
799                 r.dispatchTime = r.receiverTime;
800                 r.dispatchClockTime = System.currentTimeMillis();
801                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast ["
802                         + mQueueName + "] " + r);
803             }
804             if (! mPendingBroadcastTimeoutMessage) {
805                 long timeoutTime = r.receiverTime + mTimeoutPeriod;
806                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
807                         "Submitting BROADCAST_TIMEOUT_MSG ["
808                         + mQueueName + "] for " + r + " at " + timeoutTime);
809                 setBroadcastTimeoutLocked(timeoutTime);
810             }
811 
812             final BroadcastOptions brOptions = r.options;
813             final Object nextReceiver = r.receivers.get(recIdx);
814 
815             if (nextReceiver instanceof BroadcastFilter) {
816                 // Simple case: this is a registered receiver who gets
817                 // a direct call.
818                 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
819                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
820                         "Delivering ordered ["
821                         + mQueueName + "] to registered "
822                         + filter + ": " + r);
823                 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
824                 if (r.receiver == null || !r.ordered) {
825                     // The receiver has already finished, so schedule to
826                     // process the next one.
827                     if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing ["
828                             + mQueueName + "]: ordered="
829                             + r.ordered + " receiver=" + r.receiver);
830                     r.state = BroadcastRecord.IDLE;
831                     scheduleBroadcastsLocked();
832                 } else {
833                     if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
834                         scheduleTempWhitelistLocked(filter.owningUid,
835                                 brOptions.getTemporaryAppWhitelistDuration(), r);
836                     }
837                 }
838                 return;
839             }
840 
841             // Hard case: need to instantiate the receiver, possibly
842             // starting its application process to host it.
843 
844             ResolveInfo info =
845                 (ResolveInfo)nextReceiver;
846             ComponentName component = new ComponentName(
847                     info.activityInfo.applicationInfo.packageName,
848                     info.activityInfo.name);
849 
850             boolean skip = false;
851             int perm = mService.checkComponentPermission(info.activityInfo.permission,
852                     r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
853                     info.activityInfo.exported);
854             if (perm != PackageManager.PERMISSION_GRANTED) {
855                 if (!info.activityInfo.exported) {
856                     Slog.w(TAG, "Permission Denial: broadcasting "
857                             + r.intent.toString()
858                             + " from " + r.callerPackage + " (pid=" + r.callingPid
859                             + ", uid=" + r.callingUid + ")"
860                             + " is not exported from uid " + info.activityInfo.applicationInfo.uid
861                             + " due to receiver " + component.flattenToShortString());
862                 } else {
863                     Slog.w(TAG, "Permission Denial: broadcasting "
864                             + r.intent.toString()
865                             + " from " + r.callerPackage + " (pid=" + r.callingPid
866                             + ", uid=" + r.callingUid + ")"
867                             + " requires " + info.activityInfo.permission
868                             + " due to receiver " + component.flattenToShortString());
869                 }
870                 skip = true;
871             } else if (info.activityInfo.permission != null) {
872                 final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission);
873                 if (opCode != AppOpsManager.OP_NONE
874                         && mService.mAppOpsService.noteOperation(opCode, r.callingUid,
875                                 r.callerPackage) != AppOpsManager.MODE_ALLOWED) {
876                     Slog.w(TAG, "Appop Denial: broadcasting "
877                             + r.intent.toString()
878                             + " from " + r.callerPackage + " (pid="
879                             + r.callingPid + ", uid=" + r.callingUid + ")"
880                             + " requires appop " + AppOpsManager.permissionToOp(
881                                     info.activityInfo.permission)
882                             + " due to registered receiver "
883                             + component.flattenToShortString());
884                     skip = true;
885                 }
886             }
887             if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
888                 r.requiredPermissions != null && r.requiredPermissions.length > 0) {
889                 for (int i = 0; i < r.requiredPermissions.length; i++) {
890                     String requiredPermission = r.requiredPermissions[i];
891                     try {
892                         perm = AppGlobals.getPackageManager().
893                                 checkPermission(requiredPermission,
894                                         info.activityInfo.applicationInfo.packageName,
895                                         UserHandle
896                                                 .getUserId(info.activityInfo.applicationInfo.uid));
897                     } catch (RemoteException e) {
898                         perm = PackageManager.PERMISSION_DENIED;
899                     }
900                     if (perm != PackageManager.PERMISSION_GRANTED) {
901                         Slog.w(TAG, "Permission Denial: receiving "
902                                 + r.intent + " to "
903                                 + component.flattenToShortString()
904                                 + " requires " + requiredPermission
905                                 + " due to sender " + r.callerPackage
906                                 + " (uid " + r.callingUid + ")");
907                         skip = true;
908                         break;
909                     }
910                     int appOp = AppOpsManager.permissionToOpCode(requiredPermission);
911                     if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp
912                             && mService.mAppOpsService.noteOperation(appOp,
913                             info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
914                             != AppOpsManager.MODE_ALLOWED) {
915                         Slog.w(TAG, "Appop Denial: receiving "
916                                 + r.intent + " to "
917                                 + component.flattenToShortString()
918                                 + " requires appop " + AppOpsManager.permissionToOp(
919                                 requiredPermission)
920                                 + " due to sender " + r.callerPackage
921                                 + " (uid " + r.callingUid + ")");
922                         skip = true;
923                         break;
924                     }
925                 }
926             }
927             if (!skip && r.appOp != AppOpsManager.OP_NONE
928                     && mService.mAppOpsService.noteOperation(r.appOp,
929                     info.activityInfo.applicationInfo.uid, info.activityInfo.packageName)
930                     != AppOpsManager.MODE_ALLOWED) {
931                 Slog.w(TAG, "Appop Denial: receiving "
932                         + r.intent + " to "
933                         + component.flattenToShortString()
934                         + " requires appop " + AppOpsManager.opToName(r.appOp)
935                         + " due to sender " + r.callerPackage
936                         + " (uid " + r.callingUid + ")");
937                 skip = true;
938             }
939             if (!skip) {
940                 skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
941                         r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
942             }
943             boolean isSingleton = false;
944             try {
945                 isSingleton = mService.isSingleton(info.activityInfo.processName,
946                         info.activityInfo.applicationInfo,
947                         info.activityInfo.name, info.activityInfo.flags);
948             } catch (SecurityException e) {
949                 Slog.w(TAG, e.getMessage());
950                 skip = true;
951             }
952             if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
953                 if (ActivityManager.checkUidPermission(
954                         android.Manifest.permission.INTERACT_ACROSS_USERS,
955                         info.activityInfo.applicationInfo.uid)
956                                 != PackageManager.PERMISSION_GRANTED) {
957                     Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
958                             + " requests FLAG_SINGLE_USER, but app does not hold "
959                             + android.Manifest.permission.INTERACT_ACROSS_USERS);
960                     skip = true;
961                 }
962             }
963             if (r.curApp != null && r.curApp.crashing) {
964                 // If the target process is crashing, just skip it.
965                 Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
966                         + " to " + r.curApp + ": process crashing");
967                 skip = true;
968             }
969             if (!skip) {
970                 boolean isAvailable = false;
971                 try {
972                     isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
973                             info.activityInfo.packageName,
974                             UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
975                 } catch (Exception e) {
976                     // all such failures mean we skip this receiver
977                     Slog.w(TAG, "Exception getting recipient info for "
978                             + info.activityInfo.packageName, e);
979                 }
980                 if (!isAvailable) {
981                     if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
982                             "Skipping delivery to " + info.activityInfo.packageName + " / "
983                             + info.activityInfo.applicationInfo.uid
984                             + " : package no longer available");
985                     skip = true;
986                 }
987             }
988 
989             if (skip) {
990                 if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
991                         "Skipping delivery of ordered [" + mQueueName + "] "
992                         + r + " for whatever reason");
993                 r.receiver = null;
994                 r.curFilter = null;
995                 r.state = BroadcastRecord.IDLE;
996                 scheduleBroadcastsLocked();
997                 return;
998             }
999 
1000             r.state = BroadcastRecord.APP_RECEIVE;
1001             String targetProcess = info.activityInfo.processName;
1002             r.curComponent = component;
1003             final int receiverUid = info.activityInfo.applicationInfo.uid;
1004             // If it's a singleton, it needs to be the same app or a special app
1005             if (r.callingUid != Process.SYSTEM_UID && isSingleton
1006                     && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
1007                 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
1008             }
1009             r.curReceiver = info.activityInfo;
1010             if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
1011                 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
1012                         + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
1013                         + info.activityInfo.applicationInfo.uid);
1014             }
1015 
1016             if (brOptions != null && brOptions.getTemporaryAppWhitelistDuration() > 0) {
1017                 scheduleTempWhitelistLocked(receiverUid,
1018                         brOptions.getTemporaryAppWhitelistDuration(), r);
1019             }
1020 
1021             // Broadcast is being executed, its package can't be stopped.
1022             try {
1023                 AppGlobals.getPackageManager().setPackageStoppedState(
1024                         r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
1025             } catch (RemoteException e) {
1026             } catch (IllegalArgumentException e) {
1027                 Slog.w(TAG, "Failed trying to unstop package "
1028                         + r.curComponent.getPackageName() + ": " + e);
1029             }
1030 
1031             // Is this receiver's application already running?
1032             ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
1033                     info.activityInfo.applicationInfo.uid, false);
1034             if (app != null && app.thread != null) {
1035                 try {
1036                     app.addPackage(info.activityInfo.packageName,
1037                             info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
1038                     processCurBroadcastLocked(r, app);
1039                     return;
1040                 } catch (RemoteException e) {
1041                     Slog.w(TAG, "Exception when sending broadcast to "
1042                           + r.curComponent, e);
1043                 } catch (RuntimeException e) {
1044                     Slog.wtf(TAG, "Failed sending broadcast to "
1045                             + r.curComponent + " with " + r.intent, e);
1046                     // If some unexpected exception happened, just skip
1047                     // this broadcast.  At this point we are not in the call
1048                     // from a client, so throwing an exception out from here
1049                     // will crash the entire system instead of just whoever
1050                     // sent the broadcast.
1051                     logBroadcastReceiverDiscardLocked(r);
1052                     finishReceiverLocked(r, r.resultCode, r.resultData,
1053                             r.resultExtras, r.resultAbort, false);
1054                     scheduleBroadcastsLocked();
1055                     // We need to reset the state if we failed to start the receiver.
1056                     r.state = BroadcastRecord.IDLE;
1057                     return;
1058                 }
1059 
1060                 // If a dead object exception was thrown -- fall through to
1061                 // restart the application.
1062             }
1063 
1064             // Not running -- get it started, to be executed when the app comes up.
1065             if (DEBUG_BROADCAST)  Slog.v(TAG_BROADCAST,
1066                     "Need to start app ["
1067                     + mQueueName + "] " + targetProcess + " for broadcast " + r);
1068             if ((r.curApp=mService.startProcessLocked(targetProcess,
1069                     info.activityInfo.applicationInfo, true,
1070                     r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
1071                     "broadcast", r.curComponent,
1072                     (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
1073                             == null) {
1074                 // Ah, this recipient is unavailable.  Finish it if necessary,
1075                 // and mark the broadcast record as ready for the next.
1076                 Slog.w(TAG, "Unable to launch app "
1077                         + info.activityInfo.applicationInfo.packageName + "/"
1078                         + info.activityInfo.applicationInfo.uid + " for broadcast "
1079                         + r.intent + ": process is bad");
1080                 logBroadcastReceiverDiscardLocked(r);
1081                 finishReceiverLocked(r, r.resultCode, r.resultData,
1082                         r.resultExtras, r.resultAbort, false);
1083                 scheduleBroadcastsLocked();
1084                 r.state = BroadcastRecord.IDLE;
1085                 return;
1086             }
1087 
1088             mPendingBroadcast = r;
1089             mPendingBroadcastRecvIndex = recIdx;
1090         }
1091     }
1092 
setBroadcastTimeoutLocked(long timeoutTime)1093     final void setBroadcastTimeoutLocked(long timeoutTime) {
1094         if (! mPendingBroadcastTimeoutMessage) {
1095             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
1096             mHandler.sendMessageAtTime(msg, timeoutTime);
1097             mPendingBroadcastTimeoutMessage = true;
1098         }
1099     }
1100 
cancelBroadcastTimeoutLocked()1101     final void cancelBroadcastTimeoutLocked() {
1102         if (mPendingBroadcastTimeoutMessage) {
1103             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
1104             mPendingBroadcastTimeoutMessage = false;
1105         }
1106     }
1107 
broadcastTimeoutLocked(boolean fromMsg)1108     final void broadcastTimeoutLocked(boolean fromMsg) {
1109         if (fromMsg) {
1110             mPendingBroadcastTimeoutMessage = false;
1111         }
1112 
1113         if (mOrderedBroadcasts.size() == 0) {
1114             return;
1115         }
1116 
1117         long now = SystemClock.uptimeMillis();
1118         BroadcastRecord r = mOrderedBroadcasts.get(0);
1119         if (fromMsg) {
1120             if (mService.mDidDexOpt) {
1121                 // Delay timeouts until dexopt finishes.
1122                 mService.mDidDexOpt = false;
1123                 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
1124                 setBroadcastTimeoutLocked(timeoutTime);
1125                 return;
1126             }
1127             if (!mService.mProcessesReady) {
1128                 // Only process broadcast timeouts if the system is ready. That way
1129                 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
1130                 // to do heavy lifting for system up.
1131                 return;
1132             }
1133 
1134             long timeoutTime = r.receiverTime + mTimeoutPeriod;
1135             if (timeoutTime > now) {
1136                 // We can observe premature timeouts because we do not cancel and reset the
1137                 // broadcast timeout message after each receiver finishes.  Instead, we set up
1138                 // an initial timeout then kick it down the road a little further as needed
1139                 // when it expires.
1140                 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
1141                         "Premature timeout ["
1142                         + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
1143                         + timeoutTime);
1144                 setBroadcastTimeoutLocked(timeoutTime);
1145                 return;
1146             }
1147         }
1148 
1149         BroadcastRecord br = mOrderedBroadcasts.get(0);
1150         if (br.state == BroadcastRecord.WAITING_SERVICES) {
1151             // In this case the broadcast had already finished, but we had decided to wait
1152             // for started services to finish as well before going on.  So if we have actually
1153             // waited long enough time timeout the broadcast, let's give up on the whole thing
1154             // and just move on to the next.
1155             Slog.i(TAG, "Waited long enough for: " + (br.curComponent != null
1156                     ? br.curComponent.flattenToShortString() : "(null)"));
1157             br.curComponent = null;
1158             br.state = BroadcastRecord.IDLE;
1159             processNextBroadcast(false);
1160             return;
1161         }
1162 
1163         Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r. receiver
1164                 + ", started " + (now - r.receiverTime) + "ms ago");
1165         r.receiverTime = now;
1166         r.anrCount++;
1167 
1168         // Current receiver has passed its expiration date.
1169         if (r.nextReceiver <= 0) {
1170             Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
1171             return;
1172         }
1173 
1174         ProcessRecord app = null;
1175         String anrMessage = null;
1176 
1177         Object curReceiver = r.receivers.get(r.nextReceiver-1);
1178         Slog.w(TAG, "Receiver during timeout: " + curReceiver);
1179         logBroadcastReceiverDiscardLocked(r);
1180         if (curReceiver instanceof BroadcastFilter) {
1181             BroadcastFilter bf = (BroadcastFilter)curReceiver;
1182             if (bf.receiverList.pid != 0
1183                     && bf.receiverList.pid != ActivityManagerService.MY_PID) {
1184                 synchronized (mService.mPidsSelfLocked) {
1185                     app = mService.mPidsSelfLocked.get(
1186                             bf.receiverList.pid);
1187                 }
1188             }
1189         } else {
1190             app = r.curApp;
1191         }
1192 
1193         if (app != null) {
1194             anrMessage = "Broadcast of " + r.intent.toString();
1195         }
1196 
1197         if (mPendingBroadcast == r) {
1198             mPendingBroadcast = null;
1199         }
1200 
1201         // Move on to the next receiver.
1202         finishReceiverLocked(r, r.resultCode, r.resultData,
1203                 r.resultExtras, r.resultAbort, false);
1204         scheduleBroadcastsLocked();
1205 
1206         if (anrMessage != null) {
1207             // Post the ANR to the handler since we do not want to process ANRs while
1208             // potentially holding our lock.
1209             mHandler.post(new AppNotResponding(app, anrMessage));
1210         }
1211     }
1212 
ringAdvance(int x, final int increment, final int ringSize)1213     private final int ringAdvance(int x, final int increment, final int ringSize) {
1214         x += increment;
1215         if (x < 0) return (ringSize - 1);
1216         else if (x >= ringSize) return 0;
1217         else return x;
1218     }
1219 
addBroadcastToHistoryLocked(BroadcastRecord r)1220     private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
1221         if (r.callingUid < 0) {
1222             // This was from a registerReceiver() call; ignore it.
1223             return;
1224         }
1225         r.finishTime = SystemClock.uptimeMillis();
1226 
1227         mBroadcastHistory[mHistoryNext] = r;
1228         mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY);
1229 
1230         mBroadcastSummaryHistory[mSummaryHistoryNext] = r.intent;
1231         mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = r.enqueueClockTime;
1232         mSummaryHistoryDispatchTime[mSummaryHistoryNext] = r.dispatchClockTime;
1233         mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis();
1234         mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY);
1235     }
1236 
cleanupDisabledPackageReceiversLocked( String packageName, Set<String> filterByClasses, int userId, boolean doit)1237     boolean cleanupDisabledPackageReceiversLocked(
1238             String packageName, Set<String> filterByClasses, int userId, boolean doit) {
1239         boolean didSomething = false;
1240         for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1241             didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1242                     packageName, filterByClasses, userId, doit);
1243             if (!doit && didSomething) {
1244                 return true;
1245             }
1246         }
1247 
1248         for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1249             didSomething |= mOrderedBroadcasts.get(i).cleanupDisabledPackageReceiversLocked(
1250                     packageName, filterByClasses, userId, doit);
1251             if (!doit && didSomething) {
1252                 return true;
1253             }
1254         }
1255 
1256         return didSomething;
1257     }
1258 
logBroadcastReceiverDiscardLocked(BroadcastRecord r)1259     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
1260         final int logIndex = r.nextReceiver - 1;
1261         if (logIndex >= 0 && logIndex < r.receivers.size()) {
1262             Object curReceiver = r.receivers.get(logIndex);
1263             if (curReceiver instanceof BroadcastFilter) {
1264                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
1265                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
1266                         bf.owningUserId, System.identityHashCode(r),
1267                         r.intent.getAction(), logIndex, System.identityHashCode(bf));
1268             } else {
1269                 ResolveInfo ri = (ResolveInfo) curReceiver;
1270                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1271                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
1272                         System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
1273             }
1274         } else {
1275             if (logIndex < 0) Slog.w(TAG,
1276                     "Discarding broadcast before first receiver is invoked: " + r);
1277             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
1278                     -1, System.identityHashCode(r),
1279                     r.intent.getAction(),
1280                     r.nextReceiver,
1281                     "NONE");
1282         }
1283     }
1284 
dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean needSep)1285     final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
1286             int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
1287         if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
1288                 || mPendingBroadcast != null) {
1289             boolean printed = false;
1290             for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) {
1291                 BroadcastRecord br = mParallelBroadcasts.get(i);
1292                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1293                     continue;
1294                 }
1295                 if (!printed) {
1296                     if (needSep) {
1297                         pw.println();
1298                     }
1299                     needSep = true;
1300                     printed = true;
1301                     pw.println("  Active broadcasts [" + mQueueName + "]:");
1302                 }
1303                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
1304                 br.dump(pw, "    ");
1305             }
1306             printed = false;
1307             needSep = true;
1308             for (int i = mOrderedBroadcasts.size() - 1; i >= 0; i--) {
1309                 BroadcastRecord br = mOrderedBroadcasts.get(i);
1310                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
1311                     continue;
1312                 }
1313                 if (!printed) {
1314                     if (needSep) {
1315                         pw.println();
1316                     }
1317                     needSep = true;
1318                     printed = true;
1319                     pw.println("  Active ordered broadcasts [" + mQueueName + "]:");
1320                 }
1321                 pw.println("  Active Ordered Broadcast " + mQueueName + " #" + i + ":");
1322                 mOrderedBroadcasts.get(i).dump(pw, "    ");
1323             }
1324             if (dumpPackage == null || (mPendingBroadcast != null
1325                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
1326                 if (needSep) {
1327                     pw.println();
1328                 }
1329                 pw.println("  Pending broadcast [" + mQueueName + "]:");
1330                 if (mPendingBroadcast != null) {
1331                     mPendingBroadcast.dump(pw, "    ");
1332                 } else {
1333                     pw.println("    (null)");
1334                 }
1335                 needSep = true;
1336             }
1337         }
1338 
1339         int i;
1340         boolean printed = false;
1341 
1342         i = -1;
1343         int lastIndex = mHistoryNext;
1344         int ringIndex = lastIndex;
1345         do {
1346             // increasing index = more recent entry, and we want to print the most
1347             // recent first and work backwards, so we roll through the ring backwards.
1348             ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY);
1349             BroadcastRecord r = mBroadcastHistory[ringIndex];
1350             if (r == null) {
1351                 continue;
1352             }
1353 
1354             i++; // genuine record of some sort even if we're filtering it out
1355             if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
1356                 continue;
1357             }
1358             if (!printed) {
1359                 if (needSep) {
1360                     pw.println();
1361                 }
1362                 needSep = true;
1363                 pw.println("  Historical broadcasts [" + mQueueName + "]:");
1364                 printed = true;
1365             }
1366             if (dumpAll) {
1367                 pw.print("  Historical Broadcast " + mQueueName + " #");
1368                         pw.print(i); pw.println(":");
1369                 r.dump(pw, "    ");
1370             } else {
1371                 pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
1372                 pw.print("    ");
1373                 pw.println(r.intent.toShortString(false, true, true, false));
1374                 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
1375                     pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
1376                 }
1377                 Bundle bundle = r.intent.getExtras();
1378                 if (bundle != null) {
1379                     pw.print("    extras: "); pw.println(bundle.toString());
1380                 }
1381             }
1382         } while (ringIndex != lastIndex);
1383 
1384         if (dumpPackage == null) {
1385             lastIndex = ringIndex = mSummaryHistoryNext;
1386             if (dumpAll) {
1387                 printed = false;
1388                 i = -1;
1389             } else {
1390                 // roll over the 'i' full dumps that have already been issued
1391                 for (int j = i;
1392                         j > 0 && ringIndex != lastIndex;) {
1393                     ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1394                     BroadcastRecord r = mBroadcastHistory[ringIndex];
1395                     if (r == null) {
1396                         continue;
1397                     }
1398                     j--;
1399                 }
1400             }
1401             // done skipping; dump the remainder of the ring. 'i' is still the ordinal within
1402             // the overall broadcast history.
1403             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1404             do {
1405                 ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY);
1406                 Intent intent = mBroadcastSummaryHistory[ringIndex];
1407                 if (intent == null) {
1408                     continue;
1409                 }
1410                 if (!printed) {
1411                     if (needSep) {
1412                         pw.println();
1413                     }
1414                     needSep = true;
1415                     pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
1416                     printed = true;
1417                 }
1418                 if (!dumpAll && i >= 50) {
1419                     pw.println("  ...");
1420                     break;
1421                 }
1422                 i++;
1423                 pw.print("  #"); pw.print(i); pw.print(": ");
1424                 pw.println(intent.toShortString(false, true, true, false));
1425                 pw.print("    enq="); pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex])));
1426                 pw.print(" disp="); pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex])));
1427                 pw.print(" fin="); pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex])));
1428                 Bundle bundle = intent.getExtras();
1429                 if (bundle != null) {
1430                     pw.print("    extras: "); pw.println(bundle.toString());
1431                 }
1432             } while (ringIndex != lastIndex);
1433         }
1434 
1435         return needSep;
1436     }
1437 }
1438