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