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