Home | History | Annotate | Download | only in am
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.server.am;
     18 
     19 import java.io.FileDescriptor;
     20 import java.io.PrintWriter;
     21 import java.util.ArrayList;
     22 
     23 import android.app.ActivityManager;
     24 import android.app.AppGlobals;
     25 import android.app.AppOpsManager;
     26 import android.content.ComponentName;
     27 import android.content.IIntentReceiver;
     28 import android.content.Intent;
     29 import android.content.pm.ActivityInfo;
     30 import android.content.pm.PackageManager;
     31 import android.content.pm.ResolveInfo;
     32 import android.os.Bundle;
     33 import android.os.Handler;
     34 import android.os.IBinder;
     35 import android.os.Message;
     36 import android.os.Process;
     37 import android.os.RemoteException;
     38 import android.os.SystemClock;
     39 import android.os.UserHandle;
     40 import android.util.EventLog;
     41 import android.util.Log;
     42 import android.util.Slog;
     43 
     44 /**
     45  * BROADCASTS
     46  *
     47  * We keep two broadcast queues and associated bookkeeping, one for those at
     48  * foreground priority, and one for normal (background-priority) broadcasts.
     49  */
     50 public class BroadcastQueue {
     51     static final String TAG = "BroadcastQueue";
     52     static final String TAG_MU = ActivityManagerService.TAG_MU;
     53     static final boolean DEBUG_BROADCAST = ActivityManagerService.DEBUG_BROADCAST;
     54     static final boolean DEBUG_BROADCAST_LIGHT = ActivityManagerService.DEBUG_BROADCAST_LIGHT;
     55     static final boolean DEBUG_MU = ActivityManagerService.DEBUG_MU;
     56 
     57     static final int MAX_BROADCAST_HISTORY = 25;
     58     static final int MAX_BROADCAST_SUMMARY_HISTORY = 100;
     59 
     60     final ActivityManagerService mService;
     61 
     62     /**
     63      * Recognizable moniker for this queue
     64      */
     65     final String mQueueName;
     66 
     67     /**
     68      * Timeout period for this queue's broadcasts
     69      */
     70     final long mTimeoutPeriod;
     71 
     72     /**
     73      * Lists of all active broadcasts that are to be executed immediately
     74      * (without waiting for another broadcast to finish).  Currently this only
     75      * contains broadcasts to registered receivers, to avoid spinning up
     76      * a bunch of processes to execute IntentReceiver components.  Background-
     77      * and foreground-priority broadcasts are queued separately.
     78      */
     79     final ArrayList<BroadcastRecord> mParallelBroadcasts
     80             = new ArrayList<BroadcastRecord>();
     81     /**
     82      * List of all active broadcasts that are to be executed one at a time.
     83      * The object at the top of the list is the currently activity broadcasts;
     84      * those after it are waiting for the top to finish.  As with parallel
     85      * broadcasts, separate background- and foreground-priority queues are
     86      * maintained.
     87      */
     88     final ArrayList<BroadcastRecord> mOrderedBroadcasts
     89             = new ArrayList<BroadcastRecord>();
     90 
     91     /**
     92      * Historical data of past broadcasts, for debugging.
     93      */
     94     final BroadcastRecord[] mBroadcastHistory
     95             = new BroadcastRecord[MAX_BROADCAST_HISTORY];
     96 
     97     /**
     98      * Summary of historical data of past broadcasts, for debugging.
     99      */
    100     final Intent[] mBroadcastSummaryHistory
    101             = new Intent[MAX_BROADCAST_SUMMARY_HISTORY];
    102 
    103     /**
    104      * Set when we current have a BROADCAST_INTENT_MSG in flight.
    105      */
    106     boolean mBroadcastsScheduled = false;
    107 
    108     /**
    109      * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler.
    110      */
    111     boolean mPendingBroadcastTimeoutMessage;
    112 
    113     /**
    114      * Intent broadcasts that we have tried to start, but are
    115      * waiting for the application's process to be created.  We only
    116      * need one per scheduling class (instead of a list) because we always
    117      * process broadcasts one at a time, so no others can be started while
    118      * waiting for this one.
    119      */
    120     BroadcastRecord mPendingBroadcast = null;
    121 
    122     /**
    123      * The receiver index that is pending, to restart the broadcast if needed.
    124      */
    125     int mPendingBroadcastRecvIndex;
    126 
    127     static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG;
    128     static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1;
    129 
    130     final Handler mHandler = new Handler() {
    131         //public Handler() {
    132         //    if (localLOGV) Slog.v(TAG, "Handler started!");
    133         //}
    134 
    135         public void handleMessage(Message msg) {
    136             switch (msg.what) {
    137                 case BROADCAST_INTENT_MSG: {
    138                     if (DEBUG_BROADCAST) Slog.v(
    139                             TAG, "Received BROADCAST_INTENT_MSG");
    140                     processNextBroadcast(true);
    141                 } break;
    142                 case BROADCAST_TIMEOUT_MSG: {
    143                     synchronized (mService) {
    144                         broadcastTimeoutLocked(true);
    145                     }
    146                 } break;
    147             }
    148         }
    149     };
    150 
    151     private final class AppNotResponding implements Runnable {
    152         private final ProcessRecord mApp;
    153         private final String mAnnotation;
    154 
    155         public AppNotResponding(ProcessRecord app, String annotation) {
    156             mApp = app;
    157             mAnnotation = annotation;
    158         }
    159 
    160         @Override
    161         public void run() {
    162             mService.appNotResponding(mApp, null, null, false, mAnnotation);
    163         }
    164     }
    165 
    166     BroadcastQueue(ActivityManagerService service, String name, long timeoutPeriod) {
    167         mService = service;
    168         mQueueName = name;
    169         mTimeoutPeriod = timeoutPeriod;
    170     }
    171 
    172     public boolean isPendingBroadcastProcessLocked(int pid) {
    173         return mPendingBroadcast != null && mPendingBroadcast.curApp.pid == pid;
    174     }
    175 
    176     public void enqueueParallelBroadcastLocked(BroadcastRecord r) {
    177         mParallelBroadcasts.add(r);
    178     }
    179 
    180     public void enqueueOrderedBroadcastLocked(BroadcastRecord r) {
    181         mOrderedBroadcasts.add(r);
    182     }
    183 
    184     public final boolean replaceParallelBroadcastLocked(BroadcastRecord r) {
    185         for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
    186             if (r.intent.filterEquals(mParallelBroadcasts.get(i).intent)) {
    187                 if (DEBUG_BROADCAST) Slog.v(TAG,
    188                         "***** DROPPING PARALLEL ["
    189                 + mQueueName + "]: " + r.intent);
    190                 mParallelBroadcasts.set(i, r);
    191                 return true;
    192             }
    193         }
    194         return false;
    195     }
    196 
    197     public final boolean replaceOrderedBroadcastLocked(BroadcastRecord r) {
    198         for (int i=mOrderedBroadcasts.size()-1; i>0; i--) {
    199             if (r.intent.filterEquals(mOrderedBroadcasts.get(i).intent)) {
    200                 if (DEBUG_BROADCAST) Slog.v(TAG,
    201                         "***** DROPPING ORDERED ["
    202                         + mQueueName + "]: " + r.intent);
    203                 mOrderedBroadcasts.set(i, r);
    204                 return true;
    205             }
    206         }
    207         return false;
    208     }
    209 
    210     private final void processCurBroadcastLocked(BroadcastRecord r,
    211             ProcessRecord app) throws RemoteException {
    212         if (DEBUG_BROADCAST)  Slog.v(TAG,
    213                 "Process cur broadcast " + r + " for app " + app);
    214         if (app.thread == null) {
    215             throw new RemoteException();
    216         }
    217         r.receiver = app.thread.asBinder();
    218         r.curApp = app;
    219         app.curReceiver = r;
    220         mService.updateLruProcessLocked(app, true);
    221 
    222         // Tell the application to launch this receiver.
    223         r.intent.setComponent(r.curComponent);
    224 
    225         boolean started = false;
    226         try {
    227             if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG,
    228                     "Delivering to component " + r.curComponent
    229                     + ": " + r);
    230             mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
    231             app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
    232                     mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
    233                     r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId);
    234             if (DEBUG_BROADCAST)  Slog.v(TAG,
    235                     "Process cur broadcast " + r + " DELIVERED for app " + app);
    236             started = true;
    237         } finally {
    238             if (!started) {
    239                 if (DEBUG_BROADCAST)  Slog.v(TAG,
    240                         "Process cur broadcast " + r + ": NOT STARTED!");
    241                 r.receiver = null;
    242                 r.curApp = null;
    243                 app.curReceiver = null;
    244             }
    245         }
    246     }
    247 
    248     public boolean sendPendingBroadcastsLocked(ProcessRecord app) {
    249         boolean didSomething = false;
    250         final BroadcastRecord br = mPendingBroadcast;
    251         if (br != null && br.curApp.pid == app.pid) {
    252             try {
    253                 mPendingBroadcast = null;
    254                 processCurBroadcastLocked(br, app);
    255                 didSomething = true;
    256             } catch (Exception e) {
    257                 Slog.w(TAG, "Exception in new application when starting receiver "
    258                         + br.curComponent.flattenToShortString(), e);
    259                 logBroadcastReceiverDiscardLocked(br);
    260                 finishReceiverLocked(br, br.resultCode, br.resultData,
    261                         br.resultExtras, br.resultAbort, true);
    262                 scheduleBroadcastsLocked();
    263                 // We need to reset the state if we failed to start the receiver.
    264                 br.state = BroadcastRecord.IDLE;
    265                 throw new RuntimeException(e.getMessage());
    266             }
    267         }
    268         return didSomething;
    269     }
    270 
    271     public void skipPendingBroadcastLocked(int pid) {
    272         final BroadcastRecord br = mPendingBroadcast;
    273         if (br != null && br.curApp.pid == pid) {
    274             br.state = BroadcastRecord.IDLE;
    275             br.nextReceiver = mPendingBroadcastRecvIndex;
    276             mPendingBroadcast = null;
    277             scheduleBroadcastsLocked();
    278         }
    279     }
    280 
    281     public void skipCurrentReceiverLocked(ProcessRecord app) {
    282         boolean reschedule = false;
    283         BroadcastRecord r = app.curReceiver;
    284         if (r != null) {
    285             // The current broadcast is waiting for this app's receiver
    286             // to be finished.  Looks like that's not going to happen, so
    287             // let the broadcast continue.
    288             logBroadcastReceiverDiscardLocked(r);
    289             finishReceiverLocked(r, r.resultCode, r.resultData,
    290                     r.resultExtras, r.resultAbort, true);
    291             reschedule = true;
    292         }
    293 
    294         r = mPendingBroadcast;
    295         if (r != null && r.curApp == app) {
    296             if (DEBUG_BROADCAST) Slog.v(TAG,
    297                     "[" + mQueueName + "] skip & discard pending app " + r);
    298             logBroadcastReceiverDiscardLocked(r);
    299             finishReceiverLocked(r, r.resultCode, r.resultData,
    300                     r.resultExtras, r.resultAbort, true);
    301             reschedule = true;
    302         }
    303         if (reschedule) {
    304             scheduleBroadcastsLocked();
    305         }
    306     }
    307 
    308     public void scheduleBroadcastsLocked() {
    309         if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
    310                 + mQueueName + "]: current="
    311                 + mBroadcastsScheduled);
    312 
    313         if (mBroadcastsScheduled) {
    314             return;
    315         }
    316         mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
    317         mBroadcastsScheduled = true;
    318     }
    319 
    320     public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) {
    321         if (mOrderedBroadcasts.size() > 0) {
    322             final BroadcastRecord r = mOrderedBroadcasts.get(0);
    323             if (r != null && r.receiver == receiver) {
    324                 return r;
    325             }
    326         }
    327         return null;
    328     }
    329 
    330     public boolean finishReceiverLocked(BroadcastRecord r, int resultCode,
    331             String resultData, Bundle resultExtras, boolean resultAbort,
    332             boolean explicit) {
    333         int state = r.state;
    334         r.state = BroadcastRecord.IDLE;
    335         if (state == BroadcastRecord.IDLE) {
    336             if (explicit) {
    337                 Slog.w(TAG, "finishReceiver [" + mQueueName + "] called but state is IDLE");
    338             }
    339         }
    340         r.receiver = null;
    341         r.intent.setComponent(null);
    342         if (r.curApp != null) {
    343             r.curApp.curReceiver = null;
    344         }
    345         if (r.curFilter != null) {
    346             r.curFilter.receiverList.curBroadcast = null;
    347         }
    348         r.curFilter = null;
    349         r.curApp = null;
    350         r.curComponent = null;
    351         r.curReceiver = null;
    352         mPendingBroadcast = null;
    353 
    354         r.resultCode = resultCode;
    355         r.resultData = resultData;
    356         r.resultExtras = resultExtras;
    357         r.resultAbort = resultAbort;
    358 
    359         // We will process the next receiver right now if this is finishing
    360         // an app receiver (which is always asynchronous) or after we have
    361         // come back from calling a receiver.
    362         return state == BroadcastRecord.APP_RECEIVE
    363                 || state == BroadcastRecord.CALL_DONE_RECEIVE;
    364     }
    365 
    366     private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
    367             Intent intent, int resultCode, String data, Bundle extras,
    368             boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
    369         // Send the intent to the receiver asynchronously using one-way binder calls.
    370         if (app != null && app.thread != null) {
    371             // If we have an app thread, do the call through that so it is
    372             // correctly ordered with other one-way calls.
    373             app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
    374                     data, extras, ordered, sticky, sendingUser);
    375         } else {
    376             receiver.performReceive(intent, resultCode, data, extras, ordered,
    377                     sticky, sendingUser);
    378         }
    379     }
    380 
    381     private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
    382             BroadcastFilter filter, boolean ordered) {
    383         boolean skip = false;
    384         if (filter.requiredPermission != null) {
    385             int perm = mService.checkComponentPermission(filter.requiredPermission,
    386                     r.callingPid, r.callingUid, -1, true);
    387             if (perm != PackageManager.PERMISSION_GRANTED) {
    388                 Slog.w(TAG, "Permission Denial: broadcasting "
    389                         + r.intent.toString()
    390                         + " from " + r.callerPackage + " (pid="
    391                         + r.callingPid + ", uid=" + r.callingUid + ")"
    392                         + " requires " + filter.requiredPermission
    393                         + " due to registered receiver " + filter);
    394                 skip = true;
    395             }
    396         }
    397         if (!skip && r.requiredPermission != null) {
    398             int perm = mService.checkComponentPermission(r.requiredPermission,
    399                     filter.receiverList.pid, filter.receiverList.uid, -1, true);
    400             if (perm != PackageManager.PERMISSION_GRANTED) {
    401                 Slog.w(TAG, "Permission Denial: receiving "
    402                         + r.intent.toString()
    403                         + " to " + filter.receiverList.app
    404                         + " (pid=" + filter.receiverList.pid
    405                         + ", uid=" + filter.receiverList.uid + ")"
    406                         + " requires " + r.requiredPermission
    407                         + " due to sender " + r.callerPackage
    408                         + " (uid " + r.callingUid + ")");
    409                 skip = true;
    410             }
    411         }
    412         if (r.appOp != AppOpsManager.OP_NONE) {
    413             int mode = mService.mAppOpsService.checkOperation(r.appOp,
    414                     filter.receiverList.uid, filter.packageName);
    415             if (mode != AppOpsManager.MODE_ALLOWED) {
    416                 if (DEBUG_BROADCAST)  Slog.v(TAG,
    417                         "App op " + r.appOp + " not allowed for broadcast to uid "
    418                         + filter.receiverList.uid + " pkg " + filter.packageName);
    419                 skip = true;
    420             }
    421         }
    422 
    423         if (!skip) {
    424             // If this is not being sent as an ordered broadcast, then we
    425             // don't want to touch the fields that keep track of the current
    426             // state of ordered broadcasts.
    427             if (ordered) {
    428                 r.receiver = filter.receiverList.receiver.asBinder();
    429                 r.curFilter = filter;
    430                 filter.receiverList.curBroadcast = r;
    431                 r.state = BroadcastRecord.CALL_IN_RECEIVE;
    432                 if (filter.receiverList.app != null) {
    433                     // Bump hosting application to no longer be in background
    434                     // scheduling class.  Note that we can't do that if there
    435                     // isn't an app...  but we can only be in that case for
    436                     // things that directly call the IActivityManager API, which
    437                     // are already core system stuff so don't matter for this.
    438                     r.curApp = filter.receiverList.app;
    439                     filter.receiverList.app.curReceiver = r;
    440                     mService.updateOomAdjLocked();
    441                 }
    442             }
    443             try {
    444                 if (DEBUG_BROADCAST_LIGHT) {
    445                     int seq = r.intent.getIntExtra("seq", -1);
    446                     Slog.i(TAG, "Delivering to " + filter
    447                             + " (seq=" + seq + "): " + r);
    448                 }
    449                 performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
    450                     new Intent(r.intent), r.resultCode, r.resultData,
    451                     r.resultExtras, r.ordered, r.initialSticky, r.userId);
    452                 if (ordered) {
    453                     r.state = BroadcastRecord.CALL_DONE_RECEIVE;
    454                 }
    455             } catch (RemoteException e) {
    456                 Slog.w(TAG, "Failure sending broadcast " + r.intent, e);
    457                 if (ordered) {
    458                     r.receiver = null;
    459                     r.curFilter = null;
    460                     filter.receiverList.curBroadcast = null;
    461                     if (filter.receiverList.app != null) {
    462                         filter.receiverList.app.curReceiver = null;
    463                     }
    464                 }
    465             }
    466         }
    467     }
    468 
    469     final void processNextBroadcast(boolean fromMsg) {
    470         synchronized(mService) {
    471             BroadcastRecord r;
    472 
    473             if (DEBUG_BROADCAST) Slog.v(TAG, "processNextBroadcast ["
    474                     + mQueueName + "]: "
    475                     + mParallelBroadcasts.size() + " broadcasts, "
    476                     + mOrderedBroadcasts.size() + " ordered broadcasts");
    477 
    478             mService.updateCpuStats();
    479 
    480             if (fromMsg) {
    481                 mBroadcastsScheduled = false;
    482             }
    483 
    484             // First, deliver any non-serialized broadcasts right away.
    485             while (mParallelBroadcasts.size() > 0) {
    486                 r = mParallelBroadcasts.remove(0);
    487                 r.dispatchTime = SystemClock.uptimeMillis();
    488                 r.dispatchClockTime = System.currentTimeMillis();
    489                 final int N = r.receivers.size();
    490                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing parallel broadcast ["
    491                         + mQueueName + "] " + r);
    492                 for (int i=0; i<N; i++) {
    493                     Object target = r.receivers.get(i);
    494                     if (DEBUG_BROADCAST)  Slog.v(TAG,
    495                             "Delivering non-ordered on [" + mQueueName + "] to registered "
    496                             + target + ": " + r);
    497                     deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
    498                 }
    499                 addBroadcastToHistoryLocked(r);
    500                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Done with parallel broadcast ["
    501                         + mQueueName + "] " + r);
    502             }
    503 
    504             // Now take care of the next serialized one...
    505 
    506             // If we are waiting for a process to come up to handle the next
    507             // broadcast, then do nothing at this point.  Just in case, we
    508             // check that the process we're waiting for still exists.
    509             if (mPendingBroadcast != null) {
    510                 if (DEBUG_BROADCAST_LIGHT) {
    511                     Slog.v(TAG, "processNextBroadcast ["
    512                             + mQueueName + "]: waiting for "
    513                             + mPendingBroadcast.curApp);
    514                 }
    515 
    516                 boolean isDead;
    517                 synchronized (mService.mPidsSelfLocked) {
    518                     isDead = (mService.mPidsSelfLocked.get(
    519                             mPendingBroadcast.curApp.pid) == null);
    520                 }
    521                 if (!isDead) {
    522                     // It's still alive, so keep waiting
    523                     return;
    524                 } else {
    525                     Slog.w(TAG, "pending app  ["
    526                             + mQueueName + "]" + mPendingBroadcast.curApp
    527                             + " died before responding to broadcast");
    528                     mPendingBroadcast.state = BroadcastRecord.IDLE;
    529                     mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
    530                     mPendingBroadcast = null;
    531                 }
    532             }
    533 
    534             boolean looped = false;
    535 
    536             do {
    537                 if (mOrderedBroadcasts.size() == 0) {
    538                     // No more broadcasts pending, so all done!
    539                     mService.scheduleAppGcsLocked();
    540                     if (looped) {
    541                         // If we had finished the last ordered broadcast, then
    542                         // make sure all processes have correct oom and sched
    543                         // adjustments.
    544                         mService.updateOomAdjLocked();
    545                     }
    546                     return;
    547                 }
    548                 r = mOrderedBroadcasts.get(0);
    549                 boolean forceReceive = false;
    550 
    551                 // Ensure that even if something goes awry with the timeout
    552                 // detection, we catch "hung" broadcasts here, discard them,
    553                 // and continue to make progress.
    554                 //
    555                 // This is only done if the system is ready so that PRE_BOOT_COMPLETED
    556                 // receivers don't get executed with timeouts. They're intended for
    557                 // one time heavy lifting after system upgrades and can take
    558                 // significant amounts of time.
    559                 int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
    560                 if (mService.mProcessesReady && r.dispatchTime > 0) {
    561                     long now = SystemClock.uptimeMillis();
    562                     if ((numReceivers > 0) &&
    563                             (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
    564                         Slog.w(TAG, "Hung broadcast ["
    565                                 + mQueueName + "] discarded after timeout failure:"
    566                                 + " now=" + now
    567                                 + " dispatchTime=" + r.dispatchTime
    568                                 + " startTime=" + r.receiverTime
    569                                 + " intent=" + r.intent
    570                                 + " numReceivers=" + numReceivers
    571                                 + " nextReceiver=" + r.nextReceiver
    572                                 + " state=" + r.state);
    573                         broadcastTimeoutLocked(false); // forcibly finish this broadcast
    574                         forceReceive = true;
    575                         r.state = BroadcastRecord.IDLE;
    576                     }
    577                 }
    578 
    579                 if (r.state != BroadcastRecord.IDLE) {
    580                     if (DEBUG_BROADCAST) Slog.d(TAG,
    581                             "processNextBroadcast("
    582                             + mQueueName + ") called when not idle (state="
    583                             + r.state + ")");
    584                     return;
    585                 }
    586 
    587                 if (r.receivers == null || r.nextReceiver >= numReceivers
    588                         || r.resultAbort || forceReceive) {
    589                     // No more receivers for this broadcast!  Send the final
    590                     // result if requested...
    591                     if (r.resultTo != null) {
    592                         try {
    593                             if (DEBUG_BROADCAST) {
    594                                 int seq = r.intent.getIntExtra("seq", -1);
    595                                 Slog.i(TAG, "Finishing broadcast ["
    596                                         + mQueueName + "] " + r.intent.getAction()
    597                                         + " seq=" + seq + " app=" + r.callerApp);
    598                             }
    599                             performReceiveLocked(r.callerApp, r.resultTo,
    600                                 new Intent(r.intent), r.resultCode,
    601                                 r.resultData, r.resultExtras, false, false, r.userId);
    602                             // Set this to null so that the reference
    603                             // (local and remote) isnt kept in the mBroadcastHistory.
    604                             r.resultTo = null;
    605                         } catch (RemoteException e) {
    606                             Slog.w(TAG, "Failure ["
    607                                     + mQueueName + "] sending broadcast result of "
    608                                     + r.intent, e);
    609                         }
    610                     }
    611 
    612                     if (DEBUG_BROADCAST) Slog.v(TAG, "Cancelling BROADCAST_TIMEOUT_MSG");
    613                     cancelBroadcastTimeoutLocked();
    614 
    615                     if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Finished with ordered broadcast "
    616                             + r);
    617 
    618                     // ... and on to the next...
    619                     addBroadcastToHistoryLocked(r);
    620                     mOrderedBroadcasts.remove(0);
    621                     r = null;
    622                     looped = true;
    623                     continue;
    624                 }
    625             } while (r == null);
    626 
    627             // Get the next receiver...
    628             int recIdx = r.nextReceiver++;
    629 
    630             // Keep track of when this receiver started, and make sure there
    631             // is a timeout message pending to kill it if need be.
    632             r.receiverTime = SystemClock.uptimeMillis();
    633             if (recIdx == 0) {
    634                 r.dispatchTime = r.receiverTime;
    635                 r.dispatchClockTime = System.currentTimeMillis();
    636                 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
    637                         + mQueueName + "] " + r);
    638             }
    639             if (! mPendingBroadcastTimeoutMessage) {
    640                 long timeoutTime = r.receiverTime + mTimeoutPeriod;
    641                 if (DEBUG_BROADCAST) Slog.v(TAG,
    642                         "Submitting BROADCAST_TIMEOUT_MSG ["
    643                         + mQueueName + "] for " + r + " at " + timeoutTime);
    644                 setBroadcastTimeoutLocked(timeoutTime);
    645             }
    646 
    647             Object nextReceiver = r.receivers.get(recIdx);
    648             if (nextReceiver instanceof BroadcastFilter) {
    649                 // Simple case: this is a registered receiver who gets
    650                 // a direct call.
    651                 BroadcastFilter filter = (BroadcastFilter)nextReceiver;
    652                 if (DEBUG_BROADCAST)  Slog.v(TAG,
    653                         "Delivering ordered ["
    654                         + mQueueName + "] to registered "
    655                         + filter + ": " + r);
    656                 deliverToRegisteredReceiverLocked(r, filter, r.ordered);
    657                 if (r.receiver == null || !r.ordered) {
    658                     // The receiver has already finished, so schedule to
    659                     // process the next one.
    660                     if (DEBUG_BROADCAST) Slog.v(TAG, "Quick finishing ["
    661                             + mQueueName + "]: ordered="
    662                             + r.ordered + " receiver=" + r.receiver);
    663                     r.state = BroadcastRecord.IDLE;
    664                     scheduleBroadcastsLocked();
    665                 }
    666                 return;
    667             }
    668 
    669             // Hard case: need to instantiate the receiver, possibly
    670             // starting its application process to host it.
    671 
    672             ResolveInfo info =
    673                 (ResolveInfo)nextReceiver;
    674             ComponentName component = new ComponentName(
    675                     info.activityInfo.applicationInfo.packageName,
    676                     info.activityInfo.name);
    677 
    678             boolean skip = false;
    679             int perm = mService.checkComponentPermission(info.activityInfo.permission,
    680                     r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
    681                     info.activityInfo.exported);
    682             if (perm != PackageManager.PERMISSION_GRANTED) {
    683                 if (!info.activityInfo.exported) {
    684                     Slog.w(TAG, "Permission Denial: broadcasting "
    685                             + r.intent.toString()
    686                             + " from " + r.callerPackage + " (pid=" + r.callingPid
    687                             + ", uid=" + r.callingUid + ")"
    688                             + " is not exported from uid " + info.activityInfo.applicationInfo.uid
    689                             + " due to receiver " + component.flattenToShortString());
    690                 } else {
    691                     Slog.w(TAG, "Permission Denial: broadcasting "
    692                             + r.intent.toString()
    693                             + " from " + r.callerPackage + " (pid=" + r.callingPid
    694                             + ", uid=" + r.callingUid + ")"
    695                             + " requires " + info.activityInfo.permission
    696                             + " due to receiver " + component.flattenToShortString());
    697                 }
    698                 skip = true;
    699             }
    700             if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&
    701                 r.requiredPermission != null) {
    702                 try {
    703                     perm = AppGlobals.getPackageManager().
    704                             checkPermission(r.requiredPermission,
    705                                     info.activityInfo.applicationInfo.packageName);
    706                 } catch (RemoteException e) {
    707                     perm = PackageManager.PERMISSION_DENIED;
    708                 }
    709                 if (perm != PackageManager.PERMISSION_GRANTED) {
    710                     Slog.w(TAG, "Permission Denial: receiving "
    711                             + r.intent + " to "
    712                             + component.flattenToShortString()
    713                             + " requires " + r.requiredPermission
    714                             + " due to sender " + r.callerPackage
    715                             + " (uid " + r.callingUid + ")");
    716                     skip = true;
    717                 }
    718             }
    719             if (r.appOp != AppOpsManager.OP_NONE) {
    720                 int mode = mService.mAppOpsService.checkOperation(r.appOp,
    721                         info.activityInfo.applicationInfo.uid, info.activityInfo.packageName);
    722                 if (mode != AppOpsManager.MODE_ALLOWED) {
    723                     if (DEBUG_BROADCAST)  Slog.v(TAG,
    724                             "App op " + r.appOp + " not allowed for broadcast to uid "
    725                             + info.activityInfo.applicationInfo.uid + " pkg "
    726                             + info.activityInfo.packageName);
    727                     skip = true;
    728                 }
    729             }
    730             boolean isSingleton = false;
    731             try {
    732                 isSingleton = mService.isSingleton(info.activityInfo.processName,
    733                         info.activityInfo.applicationInfo,
    734                         info.activityInfo.name, info.activityInfo.flags);
    735             } catch (SecurityException e) {
    736                 Slog.w(TAG, e.getMessage());
    737                 skip = true;
    738             }
    739             if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
    740                 if (ActivityManager.checkUidPermission(
    741                         android.Manifest.permission.INTERACT_ACROSS_USERS,
    742                         info.activityInfo.applicationInfo.uid)
    743                                 != PackageManager.PERMISSION_GRANTED) {
    744                     Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
    745                             + " requests FLAG_SINGLE_USER, but app does not hold "
    746                             + android.Manifest.permission.INTERACT_ACROSS_USERS);
    747                     skip = true;
    748                 }
    749             }
    750             if (r.curApp != null && r.curApp.crashing) {
    751                 // If the target process is crashing, just skip it.
    752                 if (DEBUG_BROADCAST)  Slog.v(TAG,
    753                         "Skipping deliver ordered ["
    754                         + mQueueName + "] " + r + " to " + r.curApp
    755                         + ": process crashing");
    756                 skip = true;
    757             }
    758 
    759             if (skip) {
    760                 if (DEBUG_BROADCAST)  Slog.v(TAG,
    761                         "Skipping delivery of ordered ["
    762                         + mQueueName + "] " + r + " for whatever reason");
    763                 r.receiver = null;
    764                 r.curFilter = null;
    765                 r.state = BroadcastRecord.IDLE;
    766                 scheduleBroadcastsLocked();
    767                 return;
    768             }
    769 
    770             r.state = BroadcastRecord.APP_RECEIVE;
    771             String targetProcess = info.activityInfo.processName;
    772             r.curComponent = component;
    773             if (r.callingUid != Process.SYSTEM_UID && isSingleton) {
    774                 info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
    775             }
    776             r.curReceiver = info.activityInfo;
    777             if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) {
    778                 Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, "
    779                         + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = "
    780                         + info.activityInfo.applicationInfo.uid);
    781             }
    782 
    783             // Broadcast is being executed, its package can't be stopped.
    784             try {
    785                 AppGlobals.getPackageManager().setPackageStoppedState(
    786                         r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
    787             } catch (RemoteException e) {
    788             } catch (IllegalArgumentException e) {
    789                 Slog.w(TAG, "Failed trying to unstop package "
    790                         + r.curComponent.getPackageName() + ": " + e);
    791             }
    792 
    793             // Is this receiver's application already running?
    794             ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
    795                     info.activityInfo.applicationInfo.uid);
    796             if (app != null && app.thread != null) {
    797                 try {
    798                     app.addPackage(info.activityInfo.packageName);
    799                     processCurBroadcastLocked(r, app);
    800                     return;
    801                 } catch (RemoteException e) {
    802                     Slog.w(TAG, "Exception when sending broadcast to "
    803                           + r.curComponent, e);
    804                 } catch (RuntimeException e) {
    805                     Log.wtf(TAG, "Failed sending broadcast to "
    806                             + r.curComponent + " with " + r.intent, e);
    807                     // If some unexpected exception happened, just skip
    808                     // this broadcast.  At this point we are not in the call
    809                     // from a client, so throwing an exception out from here
    810                     // will crash the entire system instead of just whoever
    811                     // sent the broadcast.
    812                     logBroadcastReceiverDiscardLocked(r);
    813                     finishReceiverLocked(r, r.resultCode, r.resultData,
    814                             r.resultExtras, r.resultAbort, true);
    815                     scheduleBroadcastsLocked();
    816                     // We need to reset the state if we failed to start the receiver.
    817                     r.state = BroadcastRecord.IDLE;
    818                     return;
    819                 }
    820 
    821                 // If a dead object exception was thrown -- fall through to
    822                 // restart the application.
    823             }
    824 
    825             // Not running -- get it started, to be executed when the app comes up.
    826             if (DEBUG_BROADCAST)  Slog.v(TAG,
    827                     "Need to start app ["
    828                     + mQueueName + "] " + targetProcess + " for broadcast " + r);
    829             if ((r.curApp=mService.startProcessLocked(targetProcess,
    830                     info.activityInfo.applicationInfo, true,
    831                     r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
    832                     "broadcast", r.curComponent,
    833                     (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false))
    834                             == null) {
    835                 // Ah, this recipient is unavailable.  Finish it if necessary,
    836                 // and mark the broadcast record as ready for the next.
    837                 Slog.w(TAG, "Unable to launch app "
    838                         + info.activityInfo.applicationInfo.packageName + "/"
    839                         + info.activityInfo.applicationInfo.uid + " for broadcast "
    840                         + r.intent + ": process is bad");
    841                 logBroadcastReceiverDiscardLocked(r);
    842                 finishReceiverLocked(r, r.resultCode, r.resultData,
    843                         r.resultExtras, r.resultAbort, true);
    844                 scheduleBroadcastsLocked();
    845                 r.state = BroadcastRecord.IDLE;
    846                 return;
    847             }
    848 
    849             mPendingBroadcast = r;
    850             mPendingBroadcastRecvIndex = recIdx;
    851         }
    852     }
    853 
    854     final void setBroadcastTimeoutLocked(long timeoutTime) {
    855         if (! mPendingBroadcastTimeoutMessage) {
    856             Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this);
    857             mHandler.sendMessageAtTime(msg, timeoutTime);
    858             mPendingBroadcastTimeoutMessage = true;
    859         }
    860     }
    861 
    862     final void cancelBroadcastTimeoutLocked() {
    863         if (mPendingBroadcastTimeoutMessage) {
    864             mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this);
    865             mPendingBroadcastTimeoutMessage = false;
    866         }
    867     }
    868 
    869     final void broadcastTimeoutLocked(boolean fromMsg) {
    870         if (fromMsg) {
    871             mPendingBroadcastTimeoutMessage = false;
    872         }
    873 
    874         if (mOrderedBroadcasts.size() == 0) {
    875             return;
    876         }
    877 
    878         long now = SystemClock.uptimeMillis();
    879         BroadcastRecord r = mOrderedBroadcasts.get(0);
    880         if (fromMsg) {
    881             if (mService.mDidDexOpt) {
    882                 // Delay timeouts until dexopt finishes.
    883                 mService.mDidDexOpt = false;
    884                 long timeoutTime = SystemClock.uptimeMillis() + mTimeoutPeriod;
    885                 setBroadcastTimeoutLocked(timeoutTime);
    886                 return;
    887             }
    888             if (!mService.mProcessesReady) {
    889                 // Only process broadcast timeouts if the system is ready. That way
    890                 // PRE_BOOT_COMPLETED broadcasts can't timeout as they are intended
    891                 // to do heavy lifting for system up.
    892                 return;
    893             }
    894 
    895             long timeoutTime = r.receiverTime + mTimeoutPeriod;
    896             if (timeoutTime > now) {
    897                 // We can observe premature timeouts because we do not cancel and reset the
    898                 // broadcast timeout message after each receiver finishes.  Instead, we set up
    899                 // an initial timeout then kick it down the road a little further as needed
    900                 // when it expires.
    901                 if (DEBUG_BROADCAST) Slog.v(TAG,
    902                         "Premature timeout ["
    903                         + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for "
    904                         + timeoutTime);
    905                 setBroadcastTimeoutLocked(timeoutTime);
    906                 return;
    907             }
    908         }
    909 
    910         Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver
    911                 + ", started " + (now - r.receiverTime) + "ms ago");
    912         r.receiverTime = now;
    913         r.anrCount++;
    914 
    915         // Current receiver has passed its expiration date.
    916         if (r.nextReceiver <= 0) {
    917             Slog.w(TAG, "Timeout on receiver with nextReceiver <= 0");
    918             return;
    919         }
    920 
    921         ProcessRecord app = null;
    922         String anrMessage = null;
    923 
    924         Object curReceiver = r.receivers.get(r.nextReceiver-1);
    925         Slog.w(TAG, "Receiver during timeout: " + curReceiver);
    926         logBroadcastReceiverDiscardLocked(r);
    927         if (curReceiver instanceof BroadcastFilter) {
    928             BroadcastFilter bf = (BroadcastFilter)curReceiver;
    929             if (bf.receiverList.pid != 0
    930                     && bf.receiverList.pid != ActivityManagerService.MY_PID) {
    931                 synchronized (mService.mPidsSelfLocked) {
    932                     app = mService.mPidsSelfLocked.get(
    933                             bf.receiverList.pid);
    934                 }
    935             }
    936         } else {
    937             app = r.curApp;
    938         }
    939 
    940         if (app != null) {
    941             anrMessage = "Broadcast of " + r.intent.toString();
    942         }
    943 
    944         if (mPendingBroadcast == r) {
    945             mPendingBroadcast = null;
    946         }
    947 
    948         // Move on to the next receiver.
    949         finishReceiverLocked(r, r.resultCode, r.resultData,
    950                 r.resultExtras, r.resultAbort, true);
    951         scheduleBroadcastsLocked();
    952 
    953         if (anrMessage != null) {
    954             // Post the ANR to the handler since we do not want to process ANRs while
    955             // potentially holding our lock.
    956             mHandler.post(new AppNotResponding(app, anrMessage));
    957         }
    958     }
    959 
    960     private final void addBroadcastToHistoryLocked(BroadcastRecord r) {
    961         if (r.callingUid < 0) {
    962             // This was from a registerReceiver() call; ignore it.
    963             return;
    964         }
    965         System.arraycopy(mBroadcastHistory, 0, mBroadcastHistory, 1,
    966                 MAX_BROADCAST_HISTORY-1);
    967         r.finishTime = SystemClock.uptimeMillis();
    968         mBroadcastHistory[0] = r;
    969         System.arraycopy(mBroadcastSummaryHistory, 0, mBroadcastSummaryHistory, 1,
    970                 MAX_BROADCAST_SUMMARY_HISTORY-1);
    971         mBroadcastSummaryHistory[0] = r.intent;
    972     }
    973 
    974     final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
    975         if (r.nextReceiver > 0) {
    976             Object curReceiver = r.receivers.get(r.nextReceiver-1);
    977             if (curReceiver instanceof BroadcastFilter) {
    978                 BroadcastFilter bf = (BroadcastFilter) curReceiver;
    979                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
    980                         bf.owningUserId, System.identityHashCode(r),
    981                         r.intent.getAction(),
    982                         r.nextReceiver - 1,
    983                         System.identityHashCode(bf));
    984             } else {
    985                 ResolveInfo ri = (ResolveInfo)curReceiver;
    986                 EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
    987                         UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
    988                         System.identityHashCode(r), r.intent.getAction(),
    989                         r.nextReceiver - 1, ri.toString());
    990             }
    991         } else {
    992             Slog.w(TAG, "Discarding broadcast before first receiver is invoked: "
    993                     + r);
    994             EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
    995                     -1, System.identityHashCode(r),
    996                     r.intent.getAction(),
    997                     r.nextReceiver,
    998                     "NONE");
    999         }
   1000     }
   1001 
   1002     final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args,
   1003             int opti, boolean dumpAll, String dumpPackage, boolean needSep) {
   1004         if (mParallelBroadcasts.size() > 0 || mOrderedBroadcasts.size() > 0
   1005                 || mPendingBroadcast != null) {
   1006             boolean printed = false;
   1007             for (int i=mParallelBroadcasts.size()-1; i>=0; i--) {
   1008                 BroadcastRecord br = mParallelBroadcasts.get(i);
   1009                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
   1010                     continue;
   1011                 }
   1012                 if (!printed) {
   1013                     if (needSep) {
   1014                         pw.println();
   1015                     }
   1016                     needSep = true;
   1017                     printed = true;
   1018                     pw.println("  Active broadcasts [" + mQueueName + "]:");
   1019                 }
   1020                 pw.println("  Active Broadcast " + mQueueName + " #" + i + ":");
   1021                 br.dump(pw, "    ");
   1022             }
   1023             printed = false;
   1024             needSep = true;
   1025             for (int i=mOrderedBroadcasts.size()-1; i>=0; i--) {
   1026                 BroadcastRecord br = mOrderedBroadcasts.get(i);
   1027                 if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) {
   1028                     continue;
   1029                 }
   1030                 if (!printed) {
   1031                     if (needSep) {
   1032                         pw.println();
   1033                     }
   1034                     needSep = true;
   1035                     printed = true;
   1036                     pw.println("  Active ordered broadcasts [" + mQueueName + "]:");
   1037                 }
   1038                 pw.println("  Active Ordered Broadcast " + mQueueName + " #" + i + ":");
   1039                 mOrderedBroadcasts.get(i).dump(pw, "    ");
   1040             }
   1041             if (dumpPackage == null || (mPendingBroadcast != null
   1042                     && dumpPackage.equals(mPendingBroadcast.callerPackage))) {
   1043                 if (needSep) {
   1044                     pw.println();
   1045                 }
   1046                 pw.println("  Pending broadcast [" + mQueueName + "]:");
   1047                 if (mPendingBroadcast != null) {
   1048                     mPendingBroadcast.dump(pw, "    ");
   1049                 } else {
   1050                     pw.println("    (null)");
   1051                 }
   1052                 needSep = true;
   1053             }
   1054         }
   1055 
   1056         int i;
   1057         boolean printed = false;
   1058         for (i=0; i<MAX_BROADCAST_HISTORY; i++) {
   1059             BroadcastRecord r = mBroadcastHistory[i];
   1060             if (r == null) {
   1061                 break;
   1062             }
   1063             if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) {
   1064                 continue;
   1065             }
   1066             if (!printed) {
   1067                 if (needSep) {
   1068                     pw.println();
   1069                 }
   1070                 needSep = true;
   1071                 pw.println("  Historical broadcasts [" + mQueueName + "]:");
   1072                 printed = true;
   1073             }
   1074             if (dumpAll) {
   1075                 pw.print("  Historical Broadcast " + mQueueName + " #");
   1076                         pw.print(i); pw.println(":");
   1077                 r.dump(pw, "    ");
   1078             } else {
   1079                 pw.print("  #"); pw.print(i); pw.print(": "); pw.println(r);
   1080                 pw.print("    ");
   1081                 pw.println(r.intent.toShortString(false, true, true, false));
   1082                 if (r.targetComp != null && r.targetComp != r.intent.getComponent()) {
   1083                     pw.print("    targetComp: "); pw.println(r.targetComp.toShortString());
   1084                 }
   1085                 Bundle bundle = r.intent.getExtras();
   1086                 if (bundle != null) {
   1087                     pw.print("    extras: "); pw.println(bundle.toString());
   1088                 }
   1089             }
   1090         }
   1091 
   1092         if (dumpPackage == null) {
   1093             if (dumpAll) {
   1094                 i = 0;
   1095                 printed = false;
   1096             }
   1097             for (; i<MAX_BROADCAST_SUMMARY_HISTORY; i++) {
   1098                 Intent intent = mBroadcastSummaryHistory[i];
   1099                 if (intent == null) {
   1100                     break;
   1101                 }
   1102                 if (!printed) {
   1103                     if (needSep) {
   1104                         pw.println();
   1105                     }
   1106                     needSep = true;
   1107                     pw.println("  Historical broadcasts summary [" + mQueueName + "]:");
   1108                     printed = true;
   1109                 }
   1110                 if (!dumpAll && i >= 50) {
   1111                     pw.println("  ...");
   1112                     break;
   1113                 }
   1114                 pw.print("  #"); pw.print(i); pw.print(": ");
   1115                 pw.println(intent.toShortString(false, true, true, false));
   1116                 Bundle bundle = intent.getExtras();
   1117                 if (bundle != null) {
   1118                     pw.print("    extras: "); pw.println(bundle.toString());
   1119                 }
   1120             }
   1121         }
   1122 
   1123         return needSep;
   1124     }
   1125 }
   1126