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