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