Home | History | Annotate | Download | only in libcameraservice
      1 /*
      2  * Copyright (C) 2008 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 #define LOG_TAG "CameraService"
     18 #define ATRACE_TAG ATRACE_TAG_CAMERA
     19 //#define LOG_NDEBUG 0
     20 
     21 #include <algorithm>
     22 #include <climits>
     23 #include <stdio.h>
     24 #include <cstring>
     25 #include <ctime>
     26 #include <string>
     27 #include <sys/types.h>
     28 #include <inttypes.h>
     29 #include <pthread.h>
     30 
     31 #include <android/hardware/ICamera.h>
     32 #include <android/hardware/ICameraClient.h>
     33 
     34 #include <android-base/macros.h>
     35 #include <android-base/parseint.h>
     36 #include <binder/ActivityManager.h>
     37 #include <binder/AppOpsManager.h>
     38 #include <binder/IPCThreadState.h>
     39 #include <binder/IServiceManager.h>
     40 #include <binder/MemoryBase.h>
     41 #include <binder/MemoryHeapBase.h>
     42 #include <binder/PermissionController.h>
     43 #include <binder/ProcessInfoService.h>
     44 #include <binder/IResultReceiver.h>
     45 #include <cutils/atomic.h>
     46 #include <cutils/properties.h>
     47 #include <cutils/misc.h>
     48 #include <gui/Surface.h>
     49 #include <hardware/hardware.h>
     50 #include <memunreachable/memunreachable.h>
     51 #include <media/AudioSystem.h>
     52 #include <media/IMediaHTTPService.h>
     53 #include <media/mediaplayer.h>
     54 #include <mediautils/BatteryNotifier.h>
     55 #include <utils/Errors.h>
     56 #include <utils/Log.h>
     57 #include <utils/String16.h>
     58 #include <utils/SystemClock.h>
     59 #include <utils/Trace.h>
     60 #include <private/android_filesystem_config.h>
     61 #include <system/camera_vendor_tags.h>
     62 #include <system/camera_metadata.h>
     63 
     64 #include <system/camera.h>
     65 
     66 #include "CameraService.h"
     67 #include "api1/CameraClient.h"
     68 #include "api1/Camera2Client.h"
     69 #include "api2/CameraDeviceClient.h"
     70 #include "utils/CameraTraces.h"
     71 #include "utils/TagMonitor.h"
     72 
     73 namespace {
     74     const char* kPermissionServiceName = "permission";
     75 }; // namespace anonymous
     76 
     77 namespace android {
     78 
     79 using binder::Status;
     80 using hardware::ICamera;
     81 using hardware::ICameraClient;
     82 using hardware::ICameraServiceProxy;
     83 using hardware::ICameraServiceListener;
     84 using hardware::camera::common::V1_0::CameraDeviceStatus;
     85 using hardware::camera::common::V1_0::TorchModeStatus;
     86 
     87 // ----------------------------------------------------------------------------
     88 // Logging support -- this is for debugging only
     89 // Use "adb shell dumpsys media.camera -v 1" to change it.
     90 volatile int32_t gLogLevel = 0;
     91 
     92 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
     93 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
     94 
     95 static void setLogLevel(int level) {
     96     android_atomic_write(level, &gLogLevel);
     97 }
     98 
     99 // Convenience methods for constructing binder::Status objects for error returns
    100 
    101 #define STATUS_ERROR(errorCode, errorString) \
    102     binder::Status::fromServiceSpecificError(errorCode, \
    103             String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
    104 
    105 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
    106     binder::Status::fromServiceSpecificError(errorCode, \
    107             String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
    108                     __VA_ARGS__))
    109 
    110 // ----------------------------------------------------------------------------
    111 
    112 static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
    113 
    114 CameraService::CameraService() :
    115         mEventLog(DEFAULT_EVENT_LOG_LENGTH),
    116         mNumberOfCameras(0),
    117         mSoundRef(0), mInitialized(false) {
    118     ALOGI("CameraService started (pid=%d)", getpid());
    119     mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
    120 }
    121 
    122 void CameraService::onFirstRef()
    123 {
    124     ALOGI("CameraService process starting");
    125 
    126     BnCameraService::onFirstRef();
    127 
    128     // Update battery life tracking if service is restarting
    129     BatteryNotifier& notifier(BatteryNotifier::getInstance());
    130     notifier.noteResetCamera();
    131     notifier.noteResetFlashlight();
    132 
    133     status_t res = INVALID_OPERATION;
    134 
    135     res = enumerateProviders();
    136     if (res == OK) {
    137         mInitialized = true;
    138     }
    139 
    140     CameraService::pingCameraServiceProxy();
    141 
    142     mUidPolicy = new UidPolicy(this);
    143     mUidPolicy->registerSelf();
    144 }
    145 
    146 status_t CameraService::enumerateProviders() {
    147     status_t res;
    148 
    149     std::vector<std::string> deviceIds;
    150     {
    151         Mutex::Autolock l(mServiceLock);
    152 
    153         if (nullptr == mCameraProviderManager.get()) {
    154             mCameraProviderManager = new CameraProviderManager();
    155             res = mCameraProviderManager->initialize(this);
    156             if (res != OK) {
    157                 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
    158                         __FUNCTION__, strerror(-res), res);
    159                 return res;
    160             }
    161         }
    162 
    163 
    164         // Setup vendor tags before we call get_camera_info the first time
    165         // because HAL might need to setup static vendor keys in get_camera_info
    166         // TODO: maybe put this into CameraProviderManager::initialize()?
    167         mCameraProviderManager->setUpVendorTags();
    168 
    169         if (nullptr == mFlashlight.get()) {
    170             mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
    171         }
    172 
    173         res = mFlashlight->findFlashUnits();
    174         if (res != OK) {
    175             ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
    176         }
    177 
    178         deviceIds = mCameraProviderManager->getCameraDeviceIds();
    179     }
    180 
    181 
    182     for (auto& cameraId : deviceIds) {
    183         String8 id8 = String8(cameraId.c_str());
    184         onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
    185     }
    186 
    187     return OK;
    188 }
    189 
    190 sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
    191     sp<ICameraServiceProxy> proxyBinder = nullptr;
    192 #ifndef __BRILLO__
    193     sp<IServiceManager> sm = defaultServiceManager();
    194     // Use checkService because cameraserver normally starts before the
    195     // system server and the proxy service. So the long timeout that getService
    196     // has before giving up is inappropriate.
    197     sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
    198     if (binder != nullptr) {
    199         proxyBinder = interface_cast<ICameraServiceProxy>(binder);
    200     }
    201 #endif
    202     return proxyBinder;
    203 }
    204 
    205 void CameraService::pingCameraServiceProxy() {
    206     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
    207     if (proxyBinder == nullptr) return;
    208     proxyBinder->pingForUserUpdate();
    209 }
    210 
    211 CameraService::~CameraService() {
    212     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
    213     mUidPolicy->unregisterSelf();
    214 }
    215 
    216 void CameraService::onNewProviderRegistered() {
    217     enumerateProviders();
    218 }
    219 
    220 void CameraService::updateCameraNumAndIds() {
    221     Mutex::Autolock l(mServiceLock);
    222     mNumberOfCameras = mCameraProviderManager->getCameraCount();
    223     mNormalDeviceIds =
    224             mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
    225 }
    226 
    227 void CameraService::addStates(const String8 id) {
    228     std::string cameraId(id.c_str());
    229     hardware::camera::common::V1_0::CameraResourceCost cost;
    230     status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
    231     if (res != OK) {
    232         ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
    233         return;
    234     }
    235     std::set<String8> conflicting;
    236     for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
    237         conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
    238     }
    239 
    240     {
    241         Mutex::Autolock lock(mCameraStatesLock);
    242         mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
    243                                                                 conflicting));
    244     }
    245 
    246     if (mFlashlight->hasFlashUnit(id)) {
    247         Mutex::Autolock al(mTorchStatusMutex);
    248         mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
    249     }
    250 
    251     updateCameraNumAndIds();
    252     logDeviceAdded(id, "Device added");
    253 }
    254 
    255 void CameraService::removeStates(const String8 id) {
    256     updateCameraNumAndIds();
    257     if (mFlashlight->hasFlashUnit(id)) {
    258         Mutex::Autolock al(mTorchStatusMutex);
    259         mTorchStatusMap.removeItem(id);
    260     }
    261 
    262     {
    263         Mutex::Autolock lock(mCameraStatesLock);
    264         mCameraStates.erase(id);
    265     }
    266 }
    267 
    268 void CameraService::onDeviceStatusChanged(const String8& id,
    269         CameraDeviceStatus newHalStatus) {
    270     ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
    271             id.string(), newHalStatus);
    272 
    273     StatusInternal newStatus = mapToInternal(newHalStatus);
    274 
    275     std::shared_ptr<CameraState> state = getCameraState(id);
    276 
    277     if (state == nullptr) {
    278         if (newStatus == StatusInternal::PRESENT) {
    279             ALOGI("%s: Unknown camera ID %s, a new camera is added",
    280                     __FUNCTION__, id.string());
    281 
    282             // First add as absent to make sure clients are notified below
    283             addStates(id);
    284 
    285             updateStatus(newStatus, id);
    286         } else {
    287             ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
    288         }
    289         return;
    290     }
    291 
    292     StatusInternal oldStatus = state->getStatus();
    293 
    294     if (oldStatus == newStatus) {
    295         ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
    296         return;
    297     }
    298 
    299     if (newStatus == StatusInternal::NOT_PRESENT) {
    300         logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
    301                 newStatus));
    302 
    303         // Set the device status to NOT_PRESENT, clients will no longer be able to connect
    304         // to this device until the status changes
    305         updateStatus(StatusInternal::NOT_PRESENT, id);
    306 
    307         sp<BasicClient> clientToDisconnect;
    308         {
    309             // Don't do this in updateStatus to avoid deadlock over mServiceLock
    310             Mutex::Autolock lock(mServiceLock);
    311 
    312             // Remove cached shim parameters
    313             state->setShimParams(CameraParameters());
    314 
    315             // Remove the client from the list of active clients, if there is one
    316             clientToDisconnect = removeClientLocked(id);
    317         }
    318 
    319         // Disconnect client
    320         if (clientToDisconnect.get() != nullptr) {
    321             ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
    322                     __FUNCTION__, id.string());
    323             // Notify the client of disconnection
    324             clientToDisconnect->notifyError(
    325                     hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
    326                     CaptureResultExtras{});
    327             // Ensure not in binder RPC so client disconnect PID checks work correctly
    328             LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
    329                     "onDeviceStatusChanged must be called from the camera service process!");
    330             clientToDisconnect->disconnect();
    331         }
    332 
    333         removeStates(id);
    334     } else {
    335         if (oldStatus == StatusInternal::NOT_PRESENT) {
    336             logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
    337                     newStatus));
    338         }
    339         updateStatus(newStatus, id);
    340     }
    341 
    342 }
    343 
    344 void CameraService::onTorchStatusChanged(const String8& cameraId,
    345         TorchModeStatus newStatus) {
    346     Mutex::Autolock al(mTorchStatusMutex);
    347     onTorchStatusChangedLocked(cameraId, newStatus);
    348 }
    349 
    350 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
    351         TorchModeStatus newStatus) {
    352     ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
    353             __FUNCTION__, cameraId.string(), newStatus);
    354 
    355     TorchModeStatus status;
    356     status_t res = getTorchStatusLocked(cameraId, &status);
    357     if (res) {
    358         ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
    359                 __FUNCTION__, cameraId.string(), strerror(-res), res);
    360         return;
    361     }
    362     if (status == newStatus) {
    363         return;
    364     }
    365 
    366     res = setTorchStatusLocked(cameraId, newStatus);
    367     if (res) {
    368         ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
    369                 (uint32_t)newStatus, strerror(-res), res);
    370         return;
    371     }
    372 
    373     {
    374         // Update battery life logging for flashlight
    375         Mutex::Autolock al(mTorchUidMapMutex);
    376         auto iter = mTorchUidMap.find(cameraId);
    377         if (iter != mTorchUidMap.end()) {
    378             int oldUid = iter->second.second;
    379             int newUid = iter->second.first;
    380             BatteryNotifier& notifier(BatteryNotifier::getInstance());
    381             if (oldUid != newUid) {
    382                 // If the UID has changed, log the status and update current UID in mTorchUidMap
    383                 if (status == TorchModeStatus::AVAILABLE_ON) {
    384                     notifier.noteFlashlightOff(cameraId, oldUid);
    385                 }
    386                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
    387                     notifier.noteFlashlightOn(cameraId, newUid);
    388                 }
    389                 iter->second.second = newUid;
    390             } else {
    391                 // If the UID has not changed, log the status
    392                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
    393                     notifier.noteFlashlightOn(cameraId, oldUid);
    394                 } else {
    395                     notifier.noteFlashlightOff(cameraId, oldUid);
    396                 }
    397             }
    398         }
    399     }
    400 
    401     {
    402         Mutex::Autolock lock(mStatusListenerLock);
    403         for (auto& i : mListenerList) {
    404             i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId});
    405         }
    406     }
    407 }
    408 
    409 Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
    410     ATRACE_CALL();
    411     Mutex::Autolock l(mServiceLock);
    412     switch (type) {
    413         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
    414             *numCameras = static_cast<int>(mNormalDeviceIds.size());
    415             break;
    416         case CAMERA_TYPE_ALL:
    417             *numCameras = mNumberOfCameras;
    418             break;
    419         default:
    420             ALOGW("%s: Unknown camera type %d",
    421                     __FUNCTION__, type);
    422             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
    423                     "Unknown camera type %d", type);
    424     }
    425     return Status::ok();
    426 }
    427 
    428 Status CameraService::getCameraInfo(int cameraId,
    429         CameraInfo* cameraInfo) {
    430     ATRACE_CALL();
    431     Mutex::Autolock l(mServiceLock);
    432 
    433     if (!mInitialized) {
    434         return STATUS_ERROR(ERROR_DISCONNECTED,
    435                 "Camera subsystem is not available");
    436     }
    437 
    438     if (cameraId < 0 || cameraId >= mNumberOfCameras) {
    439         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
    440                 "CameraId is not valid");
    441     }
    442 
    443     Status ret = Status::ok();
    444     status_t err = mCameraProviderManager->getCameraInfo(
    445             cameraIdIntToStrLocked(cameraId), cameraInfo);
    446     if (err != OK) {
    447         ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
    448                 "Error retrieving camera info from device %d: %s (%d)", cameraId,
    449                 strerror(-err), err);
    450     }
    451 
    452     return ret;
    453 }
    454 
    455 std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
    456     if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(mNormalDeviceIds.size())) {
    457         ALOGE("%s: input id %d invalid: valid range  (0, %zu)",
    458                 __FUNCTION__, cameraIdInt, mNormalDeviceIds.size());
    459         return std::string{};
    460     }
    461 
    462     return mNormalDeviceIds[cameraIdInt];
    463 }
    464 
    465 String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
    466     Mutex::Autolock lock(mServiceLock);
    467     return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
    468 }
    469 
    470 Status CameraService::getCameraCharacteristics(const String16& cameraId,
    471         CameraMetadata* cameraInfo) {
    472     ATRACE_CALL();
    473     if (!cameraInfo) {
    474         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
    475         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
    476     }
    477 
    478     if (!mInitialized) {
    479         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
    480         return STATUS_ERROR(ERROR_DISCONNECTED,
    481                 "Camera subsystem is not available");;
    482     }
    483 
    484     Status ret{};
    485 
    486     status_t res = mCameraProviderManager->getCameraCharacteristics(
    487             String8(cameraId).string(), cameraInfo);
    488     if (res != OK) {
    489         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
    490                 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
    491                 strerror(-res), res);
    492     }
    493 
    494     return ret;
    495 }
    496 
    497 int CameraService::getCallingPid() {
    498     return IPCThreadState::self()->getCallingPid();
    499 }
    500 
    501 int CameraService::getCallingUid() {
    502     return IPCThreadState::self()->getCallingUid();
    503 }
    504 
    505 String8 CameraService::getFormattedCurrentTime() {
    506     time_t now = time(nullptr);
    507     char formattedTime[64];
    508     strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
    509     return String8(formattedTime);
    510 }
    511 
    512 Status CameraService::getCameraVendorTagDescriptor(
    513         /*out*/
    514         hardware::camera2::params::VendorTagDescriptor* desc) {
    515     ATRACE_CALL();
    516     if (!mInitialized) {
    517         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
    518         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
    519     }
    520     sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
    521     if (globalDescriptor != nullptr) {
    522         *desc = *(globalDescriptor.get());
    523     }
    524     return Status::ok();
    525 }
    526 
    527 Status CameraService::getCameraVendorTagCache(
    528         /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
    529     ATRACE_CALL();
    530     if (!mInitialized) {
    531         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
    532         return STATUS_ERROR(ERROR_DISCONNECTED,
    533                 "Camera subsystem not available");
    534     }
    535     sp<VendorTagDescriptorCache> globalCache =
    536             VendorTagDescriptorCache::getGlobalVendorTagCache();
    537     if (globalCache != nullptr) {
    538         *cache = *(globalCache.get());
    539     }
    540     return Status::ok();
    541 }
    542 
    543 int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
    544     ATRACE_CALL();
    545 
    546     int deviceVersion = 0;
    547 
    548     status_t res;
    549     hardware::hidl_version maxVersion{0,0};
    550     res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
    551             &maxVersion);
    552     if (res != OK) return -1;
    553     deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
    554 
    555     hardware::CameraInfo info;
    556     if (facing) {
    557         res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
    558         if (res != OK) return -1;
    559         *facing = info.facing;
    560     }
    561 
    562     return deviceVersion;
    563 }
    564 
    565 Status CameraService::filterGetInfoErrorCode(status_t err) {
    566     switch(err) {
    567         case NO_ERROR:
    568             return Status::ok();
    569         case BAD_VALUE:
    570             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
    571                     "CameraId is not valid for HAL module");
    572         case NO_INIT:
    573             return STATUS_ERROR(ERROR_DISCONNECTED,
    574                     "Camera device not available");
    575         default:
    576             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
    577                     "Camera HAL encountered error %d: %s",
    578                     err, strerror(-err));
    579     }
    580 }
    581 
    582 Status CameraService::makeClient(const sp<CameraService>& cameraService,
    583         const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
    584         int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
    585         bool legacyMode, int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
    586         /*out*/sp<BasicClient>* client) {
    587 
    588     if (halVersion < 0 || halVersion == deviceVersion) {
    589         // Default path: HAL version is unspecified by caller, create CameraClient
    590         // based on device version reported by the HAL.
    591         switch(deviceVersion) {
    592           case CAMERA_DEVICE_API_VERSION_1_0:
    593             if (effectiveApiLevel == API_1) {  // Camera1 API route
    594                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
    595                 *client = new CameraClient(cameraService, tmp, packageName,
    596                         api1CameraId, facing, clientPid, clientUid,
    597                         getpid(), legacyMode);
    598             } else { // Camera2 API route
    599                 ALOGW("Camera using old HAL version: %d", deviceVersion);
    600                 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
    601                         "Camera device \"%s\" HAL version %d does not support camera2 API",
    602                         cameraId.string(), deviceVersion);
    603             }
    604             break;
    605           case CAMERA_DEVICE_API_VERSION_3_0:
    606           case CAMERA_DEVICE_API_VERSION_3_1:
    607           case CAMERA_DEVICE_API_VERSION_3_2:
    608           case CAMERA_DEVICE_API_VERSION_3_3:
    609           case CAMERA_DEVICE_API_VERSION_3_4:
    610             if (effectiveApiLevel == API_1) { // Camera1 API route
    611                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
    612                 *client = new Camera2Client(cameraService, tmp, packageName,
    613                         cameraId, api1CameraId,
    614                         facing, clientPid, clientUid,
    615                         servicePid, legacyMode);
    616             } else { // Camera2 API route
    617                 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
    618                         static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
    619                 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
    620                         facing, clientPid, clientUid, servicePid);
    621             }
    622             break;
    623           default:
    624             // Should not be reachable
    625             ALOGE("Unknown camera device HAL version: %d", deviceVersion);
    626             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
    627                     "Camera device \"%s\" has unknown HAL version %d",
    628                     cameraId.string(), deviceVersion);
    629         }
    630     } else {
    631         // A particular HAL version is requested by caller. Create CameraClient
    632         // based on the requested HAL version.
    633         if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
    634             halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
    635             // Only support higher HAL version device opened as HAL1.0 device.
    636             sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
    637             *client = new CameraClient(cameraService, tmp, packageName,
    638                     api1CameraId, facing, clientPid, clientUid,
    639                     servicePid, legacyMode);
    640         } else {
    641             // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
    642             ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
    643                     " opened as HAL %x device", halVersion, deviceVersion,
    644                     CAMERA_DEVICE_API_VERSION_1_0);
    645             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
    646                     "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
    647                     cameraId.string(), deviceVersion, halVersion);
    648         }
    649     }
    650     return Status::ok();
    651 }
    652 
    653 String8 CameraService::toString(std::set<userid_t> intSet) {
    654     String8 s("");
    655     bool first = true;
    656     for (userid_t i : intSet) {
    657         if (first) {
    658             s.appendFormat("%d", i);
    659             first = false;
    660         } else {
    661             s.appendFormat(", %d", i);
    662         }
    663     }
    664     return s;
    665 }
    666 
    667 int32_t CameraService::mapToInterface(TorchModeStatus status) {
    668     int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
    669     switch (status) {
    670         case TorchModeStatus::NOT_AVAILABLE:
    671             serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
    672             break;
    673         case TorchModeStatus::AVAILABLE_OFF:
    674             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
    675             break;
    676         case TorchModeStatus::AVAILABLE_ON:
    677             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
    678             break;
    679         default:
    680             ALOGW("Unknown new flash status: %d", status);
    681     }
    682     return serviceStatus;
    683 }
    684 
    685 CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
    686     StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
    687     switch (status) {
    688         case CameraDeviceStatus::NOT_PRESENT:
    689             serviceStatus = StatusInternal::NOT_PRESENT;
    690             break;
    691         case CameraDeviceStatus::PRESENT:
    692             serviceStatus = StatusInternal::PRESENT;
    693             break;
    694         case CameraDeviceStatus::ENUMERATING:
    695             serviceStatus = StatusInternal::ENUMERATING;
    696             break;
    697         default:
    698             ALOGW("Unknown new HAL device status: %d", status);
    699     }
    700     return serviceStatus;
    701 }
    702 
    703 int32_t CameraService::mapToInterface(StatusInternal status) {
    704     int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
    705     switch (status) {
    706         case StatusInternal::NOT_PRESENT:
    707             serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
    708             break;
    709         case StatusInternal::PRESENT:
    710             serviceStatus = ICameraServiceListener::STATUS_PRESENT;
    711             break;
    712         case StatusInternal::ENUMERATING:
    713             serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
    714             break;
    715         case StatusInternal::NOT_AVAILABLE:
    716             serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
    717             break;
    718         case StatusInternal::UNKNOWN:
    719             serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
    720             break;
    721         default:
    722             ALOGW("Unknown new internal device status: %d", status);
    723     }
    724     return serviceStatus;
    725 }
    726 
    727 Status CameraService::initializeShimMetadata(int cameraId) {
    728     int uid = getCallingUid();
    729 
    730     String16 internalPackageName("cameraserver");
    731     String8 id = String8::format("%d", cameraId);
    732     Status ret = Status::ok();
    733     sp<Client> tmp = nullptr;
    734     if (!(ret = connectHelper<ICameraClient,Client>(
    735             sp<ICameraClient>{nullptr}, id, cameraId,
    736             static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
    737             internalPackageName, uid, USE_CALLING_PID,
    738             API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true,
    739             /*out*/ tmp)
    740             ).isOk()) {
    741         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
    742     }
    743     return ret;
    744 }
    745 
    746 Status CameraService::getLegacyParametersLazy(int cameraId,
    747         /*out*/
    748         CameraParameters* parameters) {
    749 
    750     ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
    751 
    752     Status ret = Status::ok();
    753 
    754     if (parameters == NULL) {
    755         ALOGE("%s: parameters must not be null", __FUNCTION__);
    756         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
    757     }
    758 
    759     String8 id = String8::format("%d", cameraId);
    760 
    761     // Check if we already have parameters
    762     {
    763         // Scope for service lock
    764         Mutex::Autolock lock(mServiceLock);
    765         auto cameraState = getCameraState(id);
    766         if (cameraState == nullptr) {
    767             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
    768             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
    769                     "Invalid camera ID: %s", id.string());
    770         }
    771         CameraParameters p = cameraState->getShimParams();
    772         if (!p.isEmpty()) {
    773             *parameters = p;
    774             return ret;
    775         }
    776     }
    777 
    778     int64_t token = IPCThreadState::self()->clearCallingIdentity();
    779     ret = initializeShimMetadata(cameraId);
    780     IPCThreadState::self()->restoreCallingIdentity(token);
    781     if (!ret.isOk()) {
    782         // Error already logged by callee
    783         return ret;
    784     }
    785 
    786     // Check for parameters again
    787     {
    788         // Scope for service lock
    789         Mutex::Autolock lock(mServiceLock);
    790         auto cameraState = getCameraState(id);
    791         if (cameraState == nullptr) {
    792             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
    793             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
    794                     "Invalid camera ID: %s", id.string());
    795         }
    796         CameraParameters p = cameraState->getShimParams();
    797         if (!p.isEmpty()) {
    798             *parameters = p;
    799             return ret;
    800         }
    801     }
    802 
    803     ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
    804             __FUNCTION__);
    805     return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
    806 }
    807 
    808 // Can camera service trust the caller based on the calling UID?
    809 static bool isTrustedCallingUid(uid_t uid) {
    810     switch (uid) {
    811         case AID_MEDIA:        // mediaserver
    812         case AID_CAMERASERVER: // cameraserver
    813         case AID_RADIO:        // telephony
    814             return true;
    815         default:
    816             return false;
    817     }
    818 }
    819 
    820 Status CameraService::validateConnectLocked(const String8& cameraId,
    821         const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
    822         /*out*/int& originalClientPid) const {
    823 
    824 #ifdef __BRILLO__
    825     UNUSED(clientName8);
    826     UNUSED(clientUid);
    827     UNUSED(clientPid);
    828     UNUSED(originalClientPid);
    829 #else
    830     Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
    831             originalClientPid);
    832     if (!allowed.isOk()) {
    833         return allowed;
    834     }
    835 #endif  // __BRILLO__
    836 
    837     int callingPid = getCallingPid();
    838 
    839     if (!mInitialized) {
    840         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
    841                 callingPid);
    842         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
    843                 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
    844     }
    845 
    846     if (getCameraState(cameraId) == nullptr) {
    847         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
    848                 cameraId.string());
    849         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
    850                 "No camera device with ID \"%s\" available", cameraId.string());
    851     }
    852 
    853     status_t err = checkIfDeviceIsUsable(cameraId);
    854     if (err != NO_ERROR) {
    855         switch(err) {
    856             case -ENODEV:
    857             case -EBUSY:
    858                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
    859                         "No camera device with ID \"%s\" currently available", cameraId.string());
    860             default:
    861                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
    862                         "Unknown error connecting to ID \"%s\"", cameraId.string());
    863         }
    864     }
    865     return Status::ok();
    866 }
    867 
    868 Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
    869         const String8& clientName8, int& clientUid, int& clientPid,
    870         /*out*/int& originalClientPid) const {
    871     int callingPid = getCallingPid();
    872     int callingUid = getCallingUid();
    873 
    874     // Check if we can trust clientUid
    875     if (clientUid == USE_CALLING_UID) {
    876         clientUid = callingUid;
    877     } else if (!isTrustedCallingUid(callingUid)) {
    878         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
    879                 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
    880         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
    881                 "Untrusted caller (calling PID %d, UID %d) trying to "
    882                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
    883                 callingPid, callingUid, cameraId.string(),
    884                 clientName8.string(), clientUid, clientPid);
    885     }
    886 
    887     // Check if we can trust clientPid
    888     if (clientPid == USE_CALLING_PID) {
    889         clientPid = callingPid;
    890     } else if (!isTrustedCallingUid(callingUid)) {
    891         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
    892                 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
    893         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
    894                 "Untrusted caller (calling PID %d, UID %d) trying to "
    895                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
    896                 callingPid, callingUid, cameraId.string(),
    897                 clientName8.string(), clientUid, clientPid);
    898     }
    899 
    900     // If it's not calling from cameraserver, check the permission.
    901     if (callingPid != getpid() &&
    902             !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
    903         ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
    904         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
    905                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
    906                 clientName8.string(), clientUid, clientPid, cameraId.string());
    907     }
    908 
    909     // Make sure the UID is in an active state to use the camera
    910     if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
    911         ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
    912             clientPid, clientUid);
    913         return STATUS_ERROR_FMT(ERROR_DISABLED,
    914                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background",
    915                 clientName8.string(), clientUid, clientPid, cameraId.string());
    916     }
    917 
    918     // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
    919     // connected to camera service directly.
    920     originalClientPid = clientPid;
    921     clientPid = callingPid;
    922 
    923     userid_t clientUserId = multiuser_get_user_id(clientUid);
    924 
    925     // Only allow clients who are being used by the current foreground device user, unless calling
    926     // from our own process.
    927     if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
    928         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
    929                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
    930                 toString(mAllowedUsers).string());
    931         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
    932                 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
    933                 clientUserId, cameraId.string());
    934     }
    935 
    936     return Status::ok();
    937 }
    938 
    939 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
    940     auto cameraState = getCameraState(cameraId);
    941     int callingPid = getCallingPid();
    942     if (cameraState == nullptr) {
    943         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
    944                 cameraId.string());
    945         return -ENODEV;
    946     }
    947 
    948     StatusInternal currentStatus = cameraState->getStatus();
    949     if (currentStatus == StatusInternal::NOT_PRESENT) {
    950         ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
    951                 callingPid, cameraId.string());
    952         return -ENODEV;
    953     } else if (currentStatus == StatusInternal::ENUMERATING) {
    954         ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
    955                 callingPid, cameraId.string());
    956         return -EBUSY;
    957     }
    958 
    959     return NO_ERROR;
    960 }
    961 
    962 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
    963         const CameraService::DescriptorPtr& desc) {
    964 
    965     // Make a descriptor for the incoming client
    966     auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
    967     auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
    968 
    969     logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
    970             String8(client->getPackageName()));
    971 
    972     if (evicted.size() > 0) {
    973         // This should never happen - clients should already have been removed in disconnect
    974         for (auto& i : evicted) {
    975             ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
    976                     __FUNCTION__, i->getKey().string());
    977         }
    978 
    979         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
    980                 __FUNCTION__);
    981     }
    982 
    983     // And register a death notification for the client callback. Do
    984     // this last to avoid Binder policy where a nested Binder
    985     // transaction might be pre-empted to service the client death
    986     // notification if the client process dies before linkToDeath is
    987     // invoked.
    988     sp<IBinder> remoteCallback = client->getRemote();
    989     if (remoteCallback != nullptr) {
    990         remoteCallback->linkToDeath(this);
    991     }
    992 }
    993 
    994 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
    995         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
    996         /*out*/
    997         sp<BasicClient>* client,
    998         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
    999     ATRACE_CALL();
   1000     status_t ret = NO_ERROR;
   1001     std::vector<DescriptorPtr> evictedClients;
   1002     DescriptorPtr clientDescriptor;
   1003     {
   1004         if (effectiveApiLevel == API_1) {
   1005             // If we are using API1, any existing client for this camera ID with the same remote
   1006             // should be returned rather than evicted to allow MediaRecorder to work properly.
   1007 
   1008             auto current = mActiveClientManager.get(cameraId);
   1009             if (current != nullptr) {
   1010                 auto clientSp = current->getValue();
   1011                 if (clientSp.get() != nullptr) { // should never be needed
   1012                     if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
   1013                         ALOGW("CameraService connect called from same client, but with a different"
   1014                                 " API level, evicting prior client...");
   1015                     } else if (clientSp->getRemote() == remoteCallback) {
   1016                         ALOGI("CameraService::connect X (PID %d) (second call from same"
   1017                                 " app binder, returning the same client)", clientPid);
   1018                         *client = clientSp;
   1019                         return NO_ERROR;
   1020                     }
   1021                 }
   1022             }
   1023         }
   1024 
   1025         // Get current active client PIDs
   1026         std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
   1027         ownerPids.push_back(clientPid);
   1028 
   1029         std::vector<int> priorityScores(ownerPids.size());
   1030         std::vector<int> states(ownerPids.size());
   1031 
   1032         // Get priority scores of all active PIDs
   1033         status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
   1034                 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
   1035                 /*out*/&priorityScores[0]);
   1036         if (err != OK) {
   1037             ALOGE("%s: Priority score query failed: %d",
   1038                   __FUNCTION__, err);
   1039             return err;
   1040         }
   1041 
   1042         // Update all active clients' priorities
   1043         std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
   1044         for (size_t i = 0; i < ownerPids.size() - 1; i++) {
   1045             pidToPriorityMap.emplace(ownerPids[i],
   1046                     resource_policy::ClientPriority(priorityScores[i], states[i]));
   1047         }
   1048         mActiveClientManager.updatePriorities(pidToPriorityMap);
   1049 
   1050         // Get state for the given cameraId
   1051         auto state = getCameraState(cameraId);
   1052         if (state == nullptr) {
   1053             ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
   1054                 clientPid, cameraId.string());
   1055             // Should never get here because validateConnectLocked should have errored out
   1056             return BAD_VALUE;
   1057         }
   1058 
   1059         // Make descriptor for incoming client
   1060         clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
   1061                 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
   1062                 state->getConflicting(),
   1063                 priorityScores[priorityScores.size() - 1],
   1064                 clientPid,
   1065                 states[states.size() - 1]);
   1066 
   1067         // Find clients that would be evicted
   1068         auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
   1069 
   1070         // If the incoming client was 'evicted,' higher priority clients have the camera in the
   1071         // background, so we cannot do evictions
   1072         if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
   1073             ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
   1074                     " priority).", clientPid);
   1075 
   1076             sp<BasicClient> clientSp = clientDescriptor->getValue();
   1077             String8 curTime = getFormattedCurrentTime();
   1078             auto incompatibleClients =
   1079                     mActiveClientManager.getIncompatibleClients(clientDescriptor);
   1080 
   1081             String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
   1082                     "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
   1083                     cameraId.string(), packageName.string(), clientPid,
   1084                     priorityScores[priorityScores.size() - 1],
   1085                     states[states.size() - 1]);
   1086 
   1087             for (auto& i : incompatibleClients) {
   1088                 msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
   1089                         "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
   1090                         i->getKey().string(),
   1091                         String8{i->getValue()->getPackageName()}.string(),
   1092                         i->getOwnerId(), i->getPriority().getScore(),
   1093                         i->getPriority().getState());
   1094                 ALOGE("   Conflicts with: Device %s, client package %s (PID %"
   1095                         PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
   1096                         String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
   1097                         i->getPriority().getScore(), i->getPriority().getState());
   1098             }
   1099 
   1100             // Log the client's attempt
   1101             Mutex::Autolock l(mLogLock);
   1102             mEventLog.add(msg);
   1103 
   1104             return -EBUSY;
   1105         }
   1106 
   1107         for (auto& i : evicted) {
   1108             sp<BasicClient> clientSp = i->getValue();
   1109             if (clientSp.get() == nullptr) {
   1110                 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
   1111 
   1112                 // TODO: Remove this
   1113                 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
   1114                         __FUNCTION__);
   1115                 mActiveClientManager.remove(i);
   1116                 continue;
   1117             }
   1118 
   1119             ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
   1120                     i->getKey().string());
   1121             evictedClients.push_back(i);
   1122 
   1123             // Log the clients evicted
   1124             logEvent(String8::format("EVICT device %s client held by package %s (PID"
   1125                     " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
   1126                     " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
   1127                     i->getKey().string(), String8{clientSp->getPackageName()}.string(),
   1128                     i->getOwnerId(), i->getPriority().getScore(),
   1129                     i->getPriority().getState(), cameraId.string(),
   1130                     packageName.string(), clientPid,
   1131                     priorityScores[priorityScores.size() - 1],
   1132                     states[states.size() - 1]));
   1133 
   1134             // Notify the client of disconnection
   1135             clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
   1136                     CaptureResultExtras());
   1137         }
   1138     }
   1139 
   1140     // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
   1141     // other clients from connecting in mServiceLockWrapper if held
   1142     mServiceLock.unlock();
   1143 
   1144     // Clear caller identity temporarily so client disconnect PID checks work correctly
   1145     int64_t token = IPCThreadState::self()->clearCallingIdentity();
   1146 
   1147     // Destroy evicted clients
   1148     for (auto& i : evictedClients) {
   1149         // Disconnect is blocking, and should only have returned when HAL has cleaned up
   1150         i->getValue()->disconnect(); // Clients will remove themselves from the active client list
   1151     }
   1152 
   1153     IPCThreadState::self()->restoreCallingIdentity(token);
   1154 
   1155     for (const auto& i : evictedClients) {
   1156         ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
   1157                 __FUNCTION__, i->getKey().string(), i->getOwnerId());
   1158         ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
   1159         if (ret == TIMED_OUT) {
   1160             ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
   1161                     "current clients:\n%s", __FUNCTION__, i->getKey().string(),
   1162                     mActiveClientManager.toString().string());
   1163             return -EBUSY;
   1164         }
   1165         if (ret != NO_ERROR) {
   1166             ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
   1167                     "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
   1168                     ret, mActiveClientManager.toString().string());
   1169             return ret;
   1170         }
   1171     }
   1172 
   1173     evictedClients.clear();
   1174 
   1175     // Once clients have been disconnected, relock
   1176     mServiceLock.lock();
   1177 
   1178     // Check again if the device was unplugged or something while we weren't holding mServiceLock
   1179     if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
   1180         return ret;
   1181     }
   1182 
   1183     *partial = clientDescriptor;
   1184     return NO_ERROR;
   1185 }
   1186 
   1187 Status CameraService::connect(
   1188         const sp<ICameraClient>& cameraClient,
   1189         int api1CameraId,
   1190         const String16& clientPackageName,
   1191         int clientUid,
   1192         int clientPid,
   1193         /*out*/
   1194         sp<ICamera>* device) {
   1195 
   1196     ATRACE_CALL();
   1197     Status ret = Status::ok();
   1198 
   1199     String8 id = cameraIdIntToStr(api1CameraId);
   1200     sp<Client> client = nullptr;
   1201     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
   1202             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
   1203             /*legacyMode*/ false, /*shimUpdateOnly*/ false,
   1204             /*out*/client);
   1205 
   1206     if(!ret.isOk()) {
   1207         logRejected(id, getCallingPid(), String8(clientPackageName),
   1208                 ret.toString8());
   1209         return ret;
   1210     }
   1211 
   1212     *device = client;
   1213     return ret;
   1214 }
   1215 
   1216 Status CameraService::connectLegacy(
   1217         const sp<ICameraClient>& cameraClient,
   1218         int api1CameraId, int halVersion,
   1219         const String16& clientPackageName,
   1220         int clientUid,
   1221         /*out*/
   1222         sp<ICamera>* device) {
   1223 
   1224     ATRACE_CALL();
   1225     String8 id = cameraIdIntToStr(api1CameraId);
   1226 
   1227     Status ret = Status::ok();
   1228     sp<Client> client = nullptr;
   1229     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
   1230             clientPackageName, clientUid, USE_CALLING_PID, API_1,
   1231             /*legacyMode*/ true, /*shimUpdateOnly*/ false,
   1232             /*out*/client);
   1233 
   1234     if(!ret.isOk()) {
   1235         logRejected(id, getCallingPid(), String8(clientPackageName),
   1236                 ret.toString8());
   1237         return ret;
   1238     }
   1239 
   1240     *device = client;
   1241     return ret;
   1242 }
   1243 
   1244 Status CameraService::connectDevice(
   1245         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
   1246         const String16& cameraId,
   1247         const String16& clientPackageName,
   1248         int clientUid,
   1249         /*out*/
   1250         sp<hardware::camera2::ICameraDeviceUser>* device) {
   1251 
   1252     ATRACE_CALL();
   1253     Status ret = Status::ok();
   1254     String8 id = String8(cameraId);
   1255     sp<CameraDeviceClient> client = nullptr;
   1256     ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
   1257             /*api1CameraId*/-1,
   1258             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName,
   1259             clientUid, USE_CALLING_PID, API_2,
   1260             /*legacyMode*/ false, /*shimUpdateOnly*/ false,
   1261             /*out*/client);
   1262 
   1263     if(!ret.isOk()) {
   1264         logRejected(id, getCallingPid(), String8(clientPackageName),
   1265                 ret.toString8());
   1266         return ret;
   1267     }
   1268 
   1269     *device = client;
   1270     return ret;
   1271 }
   1272 
   1273 template<class CALLBACK, class CLIENT>
   1274 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
   1275         int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
   1276         int clientPid, apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
   1277         /*out*/sp<CLIENT>& device) {
   1278     binder::Status ret = binder::Status::ok();
   1279 
   1280     String8 clientName8(clientPackageName);
   1281 
   1282     int originalClientPid = 0;
   1283 
   1284     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
   1285             "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
   1286             (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
   1287             static_cast<int>(effectiveApiLevel));
   1288 
   1289     sp<CLIENT> client = nullptr;
   1290     {
   1291         // Acquire mServiceLock and prevent other clients from connecting
   1292         std::unique_ptr<AutoConditionLock> lock =
   1293                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
   1294 
   1295         if (lock == nullptr) {
   1296             ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
   1297                     , clientPid);
   1298             return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
   1299                     "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
   1300                     cameraId.string(), clientName8.string(), clientPid);
   1301         }
   1302 
   1303         // Enforce client permissions and do basic sanity checks
   1304         if(!(ret = validateConnectLocked(cameraId, clientName8,
   1305                 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
   1306             return ret;
   1307         }
   1308 
   1309         // Check the shim parameters after acquiring lock, if they have already been updated and
   1310         // we were doing a shim update, return immediately
   1311         if (shimUpdateOnly) {
   1312             auto cameraState = getCameraState(cameraId);
   1313             if (cameraState != nullptr) {
   1314                 if (!cameraState->getShimParams().isEmpty()) return ret;
   1315             }
   1316         }
   1317 
   1318         status_t err;
   1319 
   1320         sp<BasicClient> clientTmp = nullptr;
   1321         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
   1322         if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
   1323                 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
   1324                 /*out*/&partial)) != NO_ERROR) {
   1325             switch (err) {
   1326                 case -ENODEV:
   1327                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
   1328                             "No camera device with ID \"%s\" currently available",
   1329                             cameraId.string());
   1330                 case -EBUSY:
   1331                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
   1332                             "Higher-priority client using camera, ID \"%s\" currently unavailable",
   1333                             cameraId.string());
   1334                 default:
   1335                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
   1336                             "Unexpected error %s (%d) opening camera \"%s\"",
   1337                             strerror(-err), err, cameraId.string());
   1338             }
   1339         }
   1340 
   1341         if (clientTmp.get() != nullptr) {
   1342             // Handle special case for API1 MediaRecorder where the existing client is returned
   1343             device = static_cast<CLIENT*>(clientTmp.get());
   1344             return ret;
   1345         }
   1346 
   1347         // give flashlight a chance to close devices if necessary.
   1348         mFlashlight->prepareDeviceOpen(cameraId);
   1349 
   1350         int facing = -1;
   1351         int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
   1352         if (facing == -1) {
   1353             ALOGE("%s: Unable to get camera device \"%s\"  facing", __FUNCTION__, cameraId.string());
   1354             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
   1355                     "Unable to get camera device \"%s\" facing", cameraId.string());
   1356         }
   1357 
   1358         sp<BasicClient> tmp = nullptr;
   1359         if(!(ret = makeClient(this, cameraCb, clientPackageName,
   1360                 cameraId, api1CameraId, facing,
   1361                 clientPid, clientUid, getpid(), legacyMode,
   1362                 halVersion, deviceVersion, effectiveApiLevel,
   1363                 /*out*/&tmp)).isOk()) {
   1364             return ret;
   1365         }
   1366         client = static_cast<CLIENT*>(tmp.get());
   1367 
   1368         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
   1369                 __FUNCTION__);
   1370 
   1371         err = client->initialize(mCameraProviderManager, mMonitorTags);
   1372         if (err != OK) {
   1373             ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
   1374             // Errors could be from the HAL module open call or from AppOpsManager
   1375             switch(err) {
   1376                 case BAD_VALUE:
   1377                     return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
   1378                             "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
   1379                 case -EBUSY:
   1380                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
   1381                             "Camera \"%s\" is already open", cameraId.string());
   1382                 case -EUSERS:
   1383                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
   1384                             "Too many cameras already open, cannot open camera \"%s\"",
   1385                             cameraId.string());
   1386                 case PERMISSION_DENIED:
   1387                     return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
   1388                             "No permission to open camera \"%s\"", cameraId.string());
   1389                 case -EACCES:
   1390                     return STATUS_ERROR_FMT(ERROR_DISABLED,
   1391                             "Camera \"%s\" disabled by policy", cameraId.string());
   1392                 case -ENODEV:
   1393                 default:
   1394                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
   1395                             "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
   1396                             strerror(-err), err);
   1397             }
   1398         }
   1399 
   1400         // Update shim paremeters for legacy clients
   1401         if (effectiveApiLevel == API_1) {
   1402             // Assume we have always received a Client subclass for API1
   1403             sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
   1404             String8 rawParams = shimClient->getParameters();
   1405             CameraParameters params(rawParams);
   1406 
   1407             auto cameraState = getCameraState(cameraId);
   1408             if (cameraState != nullptr) {
   1409                 cameraState->setShimParams(params);
   1410             } else {
   1411                 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
   1412                         __FUNCTION__, cameraId.string());
   1413             }
   1414         }
   1415 
   1416         if (shimUpdateOnly) {
   1417             // If only updating legacy shim parameters, immediately disconnect client
   1418             mServiceLock.unlock();
   1419             client->disconnect();
   1420             mServiceLock.lock();
   1421         } else {
   1422             // Otherwise, add client to active clients list
   1423             finishConnectLocked(client, partial);
   1424         }
   1425     } // lock is destroyed, allow further connect calls
   1426 
   1427     // Important: release the mutex here so the client can call back into the service from its
   1428     // destructor (can be at the end of the call)
   1429     device = client;
   1430     return ret;
   1431 }
   1432 
   1433 Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
   1434         const sp<IBinder>& clientBinder) {
   1435     Mutex::Autolock lock(mServiceLock);
   1436 
   1437     ATRACE_CALL();
   1438     if (enabled && clientBinder == nullptr) {
   1439         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
   1440         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
   1441                 "Torch client Binder is null");
   1442     }
   1443 
   1444     String8 id = String8(cameraId.string());
   1445     int uid = getCallingUid();
   1446 
   1447     // verify id is valid.
   1448     auto state = getCameraState(id);
   1449     if (state == nullptr) {
   1450         ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
   1451         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
   1452                 "Camera ID \"%s\" is a not valid camera ID", id.string());
   1453     }
   1454 
   1455     StatusInternal cameraStatus = state->getStatus();
   1456     if (cameraStatus != StatusInternal::PRESENT &&
   1457             cameraStatus != StatusInternal::NOT_AVAILABLE) {
   1458         ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
   1459         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
   1460                 "Camera ID \"%s\" is a not valid camera ID", id.string());
   1461     }
   1462 
   1463     {
   1464         Mutex::Autolock al(mTorchStatusMutex);
   1465         TorchModeStatus status;
   1466         status_t err = getTorchStatusLocked(id, &status);
   1467         if (err != OK) {
   1468             if (err == NAME_NOT_FOUND) {
   1469                 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
   1470                         "Camera \"%s\" does not have a flash unit", id.string());
   1471             }
   1472             ALOGE("%s: getting current torch status failed for camera %s",
   1473                     __FUNCTION__, id.string());
   1474             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
   1475                     "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
   1476                     strerror(-err), err);
   1477         }
   1478 
   1479         if (status == TorchModeStatus::NOT_AVAILABLE) {
   1480             if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
   1481                 ALOGE("%s: torch mode of camera %s is not available because "
   1482                         "camera is in use", __FUNCTION__, id.string());
   1483                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
   1484                         "Torch for camera \"%s\" is not available due to an existing camera user",
   1485                         id.string());
   1486             } else {
   1487                 ALOGE("%s: torch mode of camera %s is not available due to "
   1488                         "insufficient resources", __FUNCTION__, id.string());
   1489                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
   1490                         "Torch for camera \"%s\" is not available due to insufficient resources",
   1491                         id.string());
   1492             }
   1493         }
   1494     }
   1495 
   1496     {
   1497         // Update UID map - this is used in the torch status changed callbacks, so must be done
   1498         // before setTorchMode
   1499         Mutex::Autolock al(mTorchUidMapMutex);
   1500         if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
   1501             mTorchUidMap[id].first = uid;
   1502             mTorchUidMap[id].second = uid;
   1503         } else {
   1504             // Set the pending UID
   1505             mTorchUidMap[id].first = uid;
   1506         }
   1507     }
   1508 
   1509     status_t err = mFlashlight->setTorchMode(id, enabled);
   1510 
   1511     if (err != OK) {
   1512         int32_t errorCode;
   1513         String8 msg;
   1514         switch (err) {
   1515             case -ENOSYS:
   1516                 msg = String8::format("Camera \"%s\" has no flashlight",
   1517                     id.string());
   1518                 errorCode = ERROR_ILLEGAL_ARGUMENT;
   1519                 break;
   1520             default:
   1521                 msg = String8::format(
   1522                     "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
   1523                     id.string(), enabled, strerror(-err), err);
   1524                 errorCode = ERROR_INVALID_OPERATION;
   1525         }
   1526         ALOGE("%s: %s", __FUNCTION__, msg.string());
   1527         return STATUS_ERROR(errorCode, msg.string());
   1528     }
   1529 
   1530     {
   1531         // update the link to client's death
   1532         Mutex::Autolock al(mTorchClientMapMutex);
   1533         ssize_t index = mTorchClientMap.indexOfKey(id);
   1534         if (enabled) {
   1535             if (index == NAME_NOT_FOUND) {
   1536                 mTorchClientMap.add(id, clientBinder);
   1537             } else {
   1538                 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
   1539                 mTorchClientMap.replaceValueAt(index, clientBinder);
   1540             }
   1541             clientBinder->linkToDeath(this);
   1542         } else if (index != NAME_NOT_FOUND) {
   1543             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
   1544         }
   1545     }
   1546 
   1547     return Status::ok();
   1548 }
   1549 
   1550 Status CameraService::notifySystemEvent(int32_t eventId,
   1551         const std::vector<int32_t>& args) {
   1552     ATRACE_CALL();
   1553 
   1554     switch(eventId) {
   1555         case ICameraService::EVENT_USER_SWITCHED: {
   1556             // Try to register for UID policy updates, in case we're recovering
   1557             // from a system server crash
   1558             mUidPolicy->registerSelf();
   1559             doUserSwitch(/*newUserIds*/ args);
   1560             break;
   1561         }
   1562         case ICameraService::EVENT_NONE:
   1563         default: {
   1564             ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
   1565                     eventId);
   1566             break;
   1567         }
   1568     }
   1569     return Status::ok();
   1570 }
   1571 
   1572 Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
   1573         /*out*/
   1574         std::vector<hardware::CameraStatus> *cameraStatuses) {
   1575     ATRACE_CALL();
   1576 
   1577     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
   1578 
   1579     if (listener == nullptr) {
   1580         ALOGE("%s: Listener must not be null", __FUNCTION__);
   1581         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
   1582     }
   1583 
   1584     Mutex::Autolock lock(mServiceLock);
   1585 
   1586     {
   1587         Mutex::Autolock lock(mStatusListenerLock);
   1588         for (auto& it : mListenerList) {
   1589             if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
   1590                 ALOGW("%s: Tried to add listener %p which was already subscribed",
   1591                       __FUNCTION__, listener.get());
   1592                 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
   1593             }
   1594         }
   1595 
   1596         mListenerList.push_back(listener);
   1597     }
   1598 
   1599     /* Collect current devices and status */
   1600     {
   1601         Mutex::Autolock lock(mCameraStatesLock);
   1602         for (auto& i : mCameraStates) {
   1603             cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
   1604         }
   1605     }
   1606 
   1607     /*
   1608      * Immediately signal current torch status to this listener only
   1609      * This may be a subset of all the devices, so don't include it in the response directly
   1610      */
   1611     {
   1612         Mutex::Autolock al(mTorchStatusMutex);
   1613         for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
   1614             String16 id = String16(mTorchStatusMap.keyAt(i).string());
   1615             listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
   1616         }
   1617     }
   1618 
   1619     return Status::ok();
   1620 }
   1621 
   1622 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
   1623     ATRACE_CALL();
   1624 
   1625     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
   1626 
   1627     if (listener == 0) {
   1628         ALOGE("%s: Listener must not be null", __FUNCTION__);
   1629         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
   1630     }
   1631 
   1632     Mutex::Autolock lock(mServiceLock);
   1633 
   1634     {
   1635         Mutex::Autolock lock(mStatusListenerLock);
   1636         for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
   1637             if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
   1638                 mListenerList.erase(it);
   1639                 return Status::ok();
   1640             }
   1641         }
   1642     }
   1643 
   1644     ALOGW("%s: Tried to remove a listener %p which was not subscribed",
   1645           __FUNCTION__, listener.get());
   1646 
   1647     return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
   1648 }
   1649 
   1650 Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
   1651 
   1652     ATRACE_CALL();
   1653     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
   1654 
   1655     if (parameters == NULL) {
   1656         ALOGE("%s: parameters must not be null", __FUNCTION__);
   1657         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
   1658     }
   1659 
   1660     Status ret = Status::ok();
   1661 
   1662     CameraParameters shimParams;
   1663     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
   1664         // Error logged by caller
   1665         return ret;
   1666     }
   1667 
   1668     String8 shimParamsString8 = shimParams.flatten();
   1669     String16 shimParamsString16 = String16(shimParamsString8);
   1670 
   1671     *parameters = shimParamsString16;
   1672 
   1673     return ret;
   1674 }
   1675 
   1676 Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
   1677         /*out*/ bool *isSupported) {
   1678     ATRACE_CALL();
   1679 
   1680     const String8 id = String8(cameraId);
   1681 
   1682     ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
   1683 
   1684     switch (apiVersion) {
   1685         case API_VERSION_1:
   1686         case API_VERSION_2:
   1687             break;
   1688         default:
   1689             String8 msg = String8::format("Unknown API version %d", apiVersion);
   1690             ALOGE("%s: %s", __FUNCTION__, msg.string());
   1691             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
   1692     }
   1693 
   1694     int deviceVersion = getDeviceVersion(id);
   1695     switch(deviceVersion) {
   1696         case CAMERA_DEVICE_API_VERSION_1_0:
   1697         case CAMERA_DEVICE_API_VERSION_3_0:
   1698         case CAMERA_DEVICE_API_VERSION_3_1:
   1699             if (apiVersion == API_VERSION_2) {
   1700                 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
   1701                         __FUNCTION__, id.string(), deviceVersion);
   1702                 *isSupported = false;
   1703             } else { // if (apiVersion == API_VERSION_1) {
   1704                 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
   1705                         __FUNCTION__, id.string());
   1706                 *isSupported = true;
   1707             }
   1708             break;
   1709         case CAMERA_DEVICE_API_VERSION_3_2:
   1710         case CAMERA_DEVICE_API_VERSION_3_3:
   1711         case CAMERA_DEVICE_API_VERSION_3_4:
   1712             ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
   1713                     __FUNCTION__, id.string());
   1714             *isSupported = true;
   1715             break;
   1716         case -1: {
   1717             String8 msg = String8::format("Unknown camera ID %s", id.string());
   1718             ALOGE("%s: %s", __FUNCTION__, msg.string());
   1719             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
   1720         }
   1721         default: {
   1722             String8 msg = String8::format("Unknown device version %x for device %s",
   1723                     deviceVersion, id.string());
   1724             ALOGE("%s: %s", __FUNCTION__, msg.string());
   1725             return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
   1726         }
   1727     }
   1728 
   1729     return Status::ok();
   1730 }
   1731 
   1732 void CameraService::removeByClient(const BasicClient* client) {
   1733     Mutex::Autolock lock(mServiceLock);
   1734     for (auto& i : mActiveClientManager.getAll()) {
   1735         auto clientSp = i->getValue();
   1736         if (clientSp.get() == client) {
   1737             mActiveClientManager.remove(i);
   1738         }
   1739     }
   1740 }
   1741 
   1742 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
   1743     bool ret = false;
   1744     {
   1745         // Acquire mServiceLock and prevent other clients from connecting
   1746         std::unique_ptr<AutoConditionLock> lock =
   1747                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
   1748 
   1749 
   1750         std::vector<sp<BasicClient>> evicted;
   1751         for (auto& i : mActiveClientManager.getAll()) {
   1752             auto clientSp = i->getValue();
   1753             if (clientSp.get() == nullptr) {
   1754                 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
   1755                 mActiveClientManager.remove(i);
   1756                 continue;
   1757             }
   1758             if (remote == clientSp->getRemote()) {
   1759                 mActiveClientManager.remove(i);
   1760                 evicted.push_back(clientSp);
   1761 
   1762                 // Notify the client of disconnection
   1763                 clientSp->notifyError(
   1764                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
   1765                         CaptureResultExtras());
   1766             }
   1767         }
   1768 
   1769         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
   1770         // other clients from connecting in mServiceLockWrapper if held
   1771         mServiceLock.unlock();
   1772 
   1773         // Do not clear caller identity, remote caller should be client proccess
   1774 
   1775         for (auto& i : evicted) {
   1776             if (i.get() != nullptr) {
   1777                 i->disconnect();
   1778                 ret = true;
   1779             }
   1780         }
   1781 
   1782         // Reacquire mServiceLock
   1783         mServiceLock.lock();
   1784 
   1785     } // lock is destroyed, allow further connect calls
   1786 
   1787     return ret;
   1788 }
   1789 
   1790 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
   1791         const String8& cameraId) const {
   1792     std::shared_ptr<CameraState> state;
   1793     {
   1794         Mutex::Autolock lock(mCameraStatesLock);
   1795         auto iter = mCameraStates.find(cameraId);
   1796         if (iter != mCameraStates.end()) {
   1797             state = iter->second;
   1798         }
   1799     }
   1800     return state;
   1801 }
   1802 
   1803 sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
   1804     // Remove from active clients list
   1805     auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
   1806     if (clientDescriptorPtr == nullptr) {
   1807         ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
   1808                 cameraId.string());
   1809         return sp<BasicClient>{nullptr};
   1810     }
   1811 
   1812     return clientDescriptorPtr->getValue();
   1813 }
   1814 
   1815 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
   1816     // Acquire mServiceLock and prevent other clients from connecting
   1817     std::unique_ptr<AutoConditionLock> lock =
   1818             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
   1819 
   1820     std::set<userid_t> newAllowedUsers;
   1821     for (size_t i = 0; i < newUserIds.size(); i++) {
   1822         if (newUserIds[i] < 0) {
   1823             ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
   1824                     __FUNCTION__, newUserIds[i]);
   1825             return;
   1826         }
   1827         newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
   1828     }
   1829 
   1830 
   1831     if (newAllowedUsers == mAllowedUsers) {
   1832         ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
   1833         return;
   1834     }
   1835 
   1836     logUserSwitch(mAllowedUsers, newAllowedUsers);
   1837 
   1838     mAllowedUsers = std::move(newAllowedUsers);
   1839 
   1840     // Current user has switched, evict all current clients.
   1841     std::vector<sp<BasicClient>> evicted;
   1842     for (auto& i : mActiveClientManager.getAll()) {
   1843         auto clientSp = i->getValue();
   1844 
   1845         if (clientSp.get() == nullptr) {
   1846             ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
   1847             continue;
   1848         }
   1849 
   1850         // Don't evict clients that are still allowed.
   1851         uid_t clientUid = clientSp->getClientUid();
   1852         userid_t clientUserId = multiuser_get_user_id(clientUid);
   1853         if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
   1854             continue;
   1855         }
   1856 
   1857         evicted.push_back(clientSp);
   1858 
   1859         String8 curTime = getFormattedCurrentTime();
   1860 
   1861         ALOGE("Evicting conflicting client for camera ID %s due to user change",
   1862                 i->getKey().string());
   1863 
   1864         // Log the clients evicted
   1865         logEvent(String8::format("EVICT device %s client held by package %s (PID %"
   1866                 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n   - Evicted due"
   1867                 " to user switch.", i->getKey().string(),
   1868                 String8{clientSp->getPackageName()}.string(),
   1869                 i->getOwnerId(), i->getPriority().getScore(),
   1870                 i->getPriority().getState()));
   1871 
   1872     }
   1873 
   1874     // Do not hold mServiceLock while disconnecting clients, but retain the condition
   1875     // blocking other clients from connecting in mServiceLockWrapper if held.
   1876     mServiceLock.unlock();
   1877 
   1878     // Clear caller identity temporarily so client disconnect PID checks work correctly
   1879     int64_t token = IPCThreadState::self()->clearCallingIdentity();
   1880 
   1881     for (auto& i : evicted) {
   1882         i->disconnect();
   1883     }
   1884 
   1885     IPCThreadState::self()->restoreCallingIdentity(token);
   1886 
   1887     // Reacquire mServiceLock
   1888     mServiceLock.lock();
   1889 }
   1890 
   1891 void CameraService::logEvent(const char* event) {
   1892     String8 curTime = getFormattedCurrentTime();
   1893     Mutex::Autolock l(mLogLock);
   1894     mEventLog.add(String8::format("%s : %s", curTime.string(), event));
   1895 }
   1896 
   1897 void CameraService::logDisconnected(const char* cameraId, int clientPid,
   1898         const char* clientPackage) {
   1899     // Log the clients evicted
   1900     logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
   1901             clientPackage, clientPid));
   1902 }
   1903 
   1904 void CameraService::logConnected(const char* cameraId, int clientPid,
   1905         const char* clientPackage) {
   1906     // Log the clients evicted
   1907     logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
   1908             clientPackage, clientPid));
   1909 }
   1910 
   1911 void CameraService::logRejected(const char* cameraId, int clientPid,
   1912         const char* clientPackage, const char* reason) {
   1913     // Log the client rejected
   1914     logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
   1915             cameraId, clientPackage, clientPid, reason));
   1916 }
   1917 
   1918 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
   1919         const std::set<userid_t>& newUserIds) {
   1920     String8 newUsers = toString(newUserIds);
   1921     String8 oldUsers = toString(oldUserIds);
   1922     if (oldUsers.size() == 0) {
   1923         oldUsers = "<None>";
   1924     }
   1925     // Log the new and old users
   1926     logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
   1927             oldUsers.string(), newUsers.string()));
   1928 }
   1929 
   1930 void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
   1931     // Log the device removal
   1932     logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
   1933 }
   1934 
   1935 void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
   1936     // Log the device removal
   1937     logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
   1938 }
   1939 
   1940 void CameraService::logClientDied(int clientPid, const char* reason) {
   1941     // Log the device removal
   1942     logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
   1943 }
   1944 
   1945 void CameraService::logServiceError(const char* msg, int errorCode) {
   1946     String8 curTime = getFormattedCurrentTime();
   1947     logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
   1948 }
   1949 
   1950 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
   1951         uint32_t flags) {
   1952 
   1953     const int pid = getCallingPid();
   1954     const int selfPid = getpid();
   1955 
   1956     // Permission checks
   1957     switch (code) {
   1958         case SHELL_COMMAND_TRANSACTION: {
   1959             int in = data.readFileDescriptor();
   1960             int out = data.readFileDescriptor();
   1961             int err = data.readFileDescriptor();
   1962             int argc = data.readInt32();
   1963             Vector<String16> args;
   1964             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
   1965                args.add(data.readString16());
   1966             }
   1967             sp<IBinder> unusedCallback;
   1968             sp<IResultReceiver> resultReceiver;
   1969             status_t status;
   1970             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
   1971                 return status;
   1972             }
   1973             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
   1974                 return status;
   1975             }
   1976             status = shellCommand(in, out, err, args);
   1977             if (resultReceiver != nullptr) {
   1978                 resultReceiver->send(status);
   1979             }
   1980             return NO_ERROR;
   1981         }
   1982         case BnCameraService::NOTIFYSYSTEMEVENT: {
   1983             if (pid != selfPid) {
   1984                 // Ensure we're being called by system_server, or similar process with
   1985                 // permissions to notify the camera service about system events
   1986                 if (!checkCallingPermission(
   1987                         String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
   1988                     const int uid = getCallingUid();
   1989                     ALOGE("Permission Denial: cannot send updates to camera service about system"
   1990                             " events from pid=%d, uid=%d", pid, uid);
   1991                     return PERMISSION_DENIED;
   1992                 }
   1993             }
   1994             break;
   1995         }
   1996     }
   1997 
   1998     return BnCameraService::onTransact(code, data, reply, flags);
   1999 }
   2000 
   2001 // We share the media players for shutter and recording sound for all clients.
   2002 // A reference count is kept to determine when we will actually release the
   2003 // media players.
   2004 
   2005 sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
   2006     sp<MediaPlayer> mp = new MediaPlayer();
   2007     status_t error;
   2008     if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
   2009         mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
   2010         error = mp->prepare();
   2011     }
   2012     if (error != NO_ERROR) {
   2013         ALOGE("Failed to load CameraService sounds: %s", file);
   2014         mp->disconnect();
   2015         mp.clear();
   2016         return nullptr;
   2017     }
   2018     return mp;
   2019 }
   2020 
   2021 void CameraService::loadSound() {
   2022     ATRACE_CALL();
   2023 
   2024     Mutex::Autolock lock(mSoundLock);
   2025     LOG1("CameraService::loadSound ref=%d", mSoundRef);
   2026     if (mSoundRef++) return;
   2027 
   2028     mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
   2029     if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
   2030         mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
   2031     }
   2032     mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
   2033     if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
   2034         mSoundPlayer[SOUND_RECORDING_START] =
   2035                 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
   2036     }
   2037     mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
   2038     if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
   2039         mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
   2040     }
   2041 }
   2042 
   2043 void CameraService::releaseSound() {
   2044     Mutex::Autolock lock(mSoundLock);
   2045     LOG1("CameraService::releaseSound ref=%d", mSoundRef);
   2046     if (--mSoundRef) return;
   2047 
   2048     for (int i = 0; i < NUM_SOUNDS; i++) {
   2049         if (mSoundPlayer[i] != 0) {
   2050             mSoundPlayer[i]->disconnect();
   2051             mSoundPlayer[i].clear();
   2052         }
   2053     }
   2054 }
   2055 
   2056 void CameraService::playSound(sound_kind kind) {
   2057     ATRACE_CALL();
   2058 
   2059     LOG1("playSound(%d)", kind);
   2060     Mutex::Autolock lock(mSoundLock);
   2061     sp<MediaPlayer> player = mSoundPlayer[kind];
   2062     if (player != 0) {
   2063         player->seekTo(0);
   2064         player->start();
   2065     }
   2066 }
   2067 
   2068 // ----------------------------------------------------------------------------
   2069 
   2070 CameraService::Client::Client(const sp<CameraService>& cameraService,
   2071         const sp<ICameraClient>& cameraClient,
   2072         const String16& clientPackageName,
   2073         const String8& cameraIdStr,
   2074         int api1CameraId, int cameraFacing,
   2075         int clientPid, uid_t clientUid,
   2076         int servicePid) :
   2077         CameraService::BasicClient(cameraService,
   2078                 IInterface::asBinder(cameraClient),
   2079                 clientPackageName,
   2080                 cameraIdStr, cameraFacing,
   2081                 clientPid, clientUid,
   2082                 servicePid),
   2083         mCameraId(api1CameraId)
   2084 {
   2085     int callingPid = getCallingPid();
   2086     LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
   2087 
   2088     mRemoteCallback = cameraClient;
   2089 
   2090     cameraService->loadSound();
   2091 
   2092     LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
   2093 }
   2094 
   2095 // tear down the client
   2096 CameraService::Client::~Client() {
   2097     ALOGV("~Client");
   2098     mDestructionStarted = true;
   2099 
   2100     sCameraService->releaseSound();
   2101     // unconditionally disconnect. function is idempotent
   2102     Client::disconnect();
   2103 }
   2104 
   2105 sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
   2106 
   2107 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
   2108         const sp<IBinder>& remoteCallback,
   2109         const String16& clientPackageName,
   2110         const String8& cameraIdStr, int cameraFacing,
   2111         int clientPid, uid_t clientUid,
   2112         int servicePid):
   2113         mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
   2114         mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
   2115         mServicePid(servicePid),
   2116         mDisconnected(false),
   2117         mRemoteBinder(remoteCallback)
   2118 {
   2119     if (sCameraService == nullptr) {
   2120         sCameraService = cameraService;
   2121     }
   2122     mOpsActive = false;
   2123     mDestructionStarted = false;
   2124 
   2125     // In some cases the calling code has no access to the package it runs under.
   2126     // For example, NDK camera API.
   2127     // In this case we will get the packages for the calling UID and pick the first one
   2128     // for attributing the app op. This will work correctly for runtime permissions
   2129     // as for legacy apps we will toggle the app op for all packages in the UID.
   2130     // The caveat is that the operation may be attributed to the wrong package and
   2131     // stats based on app ops may be slightly off.
   2132     if (mClientPackageName.size() <= 0) {
   2133         sp<IServiceManager> sm = defaultServiceManager();
   2134         sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
   2135         if (binder == 0) {
   2136             ALOGE("Cannot get permission service");
   2137             // Leave mClientPackageName unchanged (empty) and the further interaction
   2138             // with camera will fail in BasicClient::startCameraOps
   2139             return;
   2140         }
   2141 
   2142         sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
   2143         Vector<String16> packages;
   2144 
   2145         permCtrl->getPackagesForUid(mClientUid, packages);
   2146 
   2147         if (packages.isEmpty()) {
   2148             ALOGE("No packages for calling UID");
   2149             // Leave mClientPackageName unchanged (empty) and the further interaction
   2150             // with camera will fail in BasicClient::startCameraOps
   2151             return;
   2152         }
   2153         mClientPackageName = packages[0];
   2154     }
   2155 }
   2156 
   2157 CameraService::BasicClient::~BasicClient() {
   2158     ALOGV("~BasicClient");
   2159     mDestructionStarted = true;
   2160 }
   2161 
   2162 binder::Status CameraService::BasicClient::disconnect() {
   2163     binder::Status res = Status::ok();
   2164     if (mDisconnected) {
   2165         return res;
   2166     }
   2167     mDisconnected = true;
   2168 
   2169     sCameraService->removeByClient(this);
   2170     sCameraService->logDisconnected(mCameraIdStr, mClientPid,
   2171             String8(mClientPackageName));
   2172 
   2173     sp<IBinder> remote = getRemote();
   2174     if (remote != nullptr) {
   2175         remote->unlinkToDeath(sCameraService);
   2176     }
   2177 
   2178     finishCameraOps();
   2179     // Notify flashlight that a camera device is closed.
   2180     sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
   2181     ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
   2182             mClientPid);
   2183 
   2184     // client shouldn't be able to call into us anymore
   2185     mClientPid = 0;
   2186 
   2187     return res;
   2188 }
   2189 
   2190 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
   2191     // No dumping of clients directly over Binder,
   2192     // must go through CameraService::dump
   2193     android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
   2194             IPCThreadState::self()->getCallingUid(), NULL, 0);
   2195     return OK;
   2196 }
   2197 
   2198 String16 CameraService::BasicClient::getPackageName() const {
   2199     return mClientPackageName;
   2200 }
   2201 
   2202 
   2203 int CameraService::BasicClient::getClientPid() const {
   2204     return mClientPid;
   2205 }
   2206 
   2207 uid_t CameraService::BasicClient::getClientUid() const {
   2208     return mClientUid;
   2209 }
   2210 
   2211 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
   2212     // Defaults to API2.
   2213     return level == API_2;
   2214 }
   2215 
   2216 status_t CameraService::BasicClient::startCameraOps() {
   2217     ATRACE_CALL();
   2218 
   2219     int32_t res;
   2220     // Notify app ops that the camera is not available
   2221     mOpsCallback = new OpsCallback(this);
   2222 
   2223     {
   2224         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
   2225               __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
   2226     }
   2227 
   2228     mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
   2229             mClientPackageName, mOpsCallback);
   2230     res = mAppOpsManager.startOpNoThrow(AppOpsManager::OP_CAMERA,
   2231             mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
   2232 
   2233     if (res == AppOpsManager::MODE_ERRORED) {
   2234         ALOGI("Camera %s: Access for \"%s\" has been revoked",
   2235                 mCameraIdStr.string(), String8(mClientPackageName).string());
   2236         return PERMISSION_DENIED;
   2237     }
   2238 
   2239     if (res == AppOpsManager::MODE_IGNORED) {
   2240         ALOGI("Camera %s: Access for \"%s\" has been restricted",
   2241                 mCameraIdStr.string(), String8(mClientPackageName).string());
   2242         // Return the same error as for device policy manager rejection
   2243         return -EACCES;
   2244     }
   2245 
   2246     mOpsActive = true;
   2247 
   2248     // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
   2249     sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
   2250 
   2251     int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
   2252     if (canCastToApiClient(API_2)) {
   2253         apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
   2254     }
   2255     // Transition device state to OPEN
   2256     sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
   2257             mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
   2258 
   2259     return OK;
   2260 }
   2261 
   2262 status_t CameraService::BasicClient::finishCameraOps() {
   2263     ATRACE_CALL();
   2264 
   2265     // Check if startCameraOps succeeded, and if so, finish the camera op
   2266     if (mOpsActive) {
   2267         // Notify app ops that the camera is available again
   2268         mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
   2269                 mClientPackageName);
   2270         mOpsActive = false;
   2271 
   2272         // This function is called when a client disconnects. This should
   2273         // release the camera, but actually only if it was in a proper
   2274         // functional state, i.e. with status NOT_AVAILABLE
   2275         std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
   2276                 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
   2277 
   2278         // Transition to PRESENT if the camera is not in either of the rejected states
   2279         sCameraService->updateStatus(StatusInternal::PRESENT,
   2280                 mCameraIdStr, rejected);
   2281 
   2282         int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
   2283         if (canCastToApiClient(API_2)) {
   2284             apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
   2285         }
   2286         // Transition device state to CLOSED
   2287         sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
   2288                 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
   2289     }
   2290     // Always stop watching, even if no camera op is active
   2291     if (mOpsCallback != NULL) {
   2292         mAppOpsManager.stopWatchingMode(mOpsCallback);
   2293     }
   2294     mOpsCallback.clear();
   2295 
   2296     return OK;
   2297 }
   2298 
   2299 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
   2300     ATRACE_CALL();
   2301 
   2302     String8 name(packageName);
   2303     String8 myName(mClientPackageName);
   2304 
   2305     if (op != AppOpsManager::OP_CAMERA) {
   2306         ALOGW("Unexpected app ops notification received: %d", op);
   2307         return;
   2308     }
   2309 
   2310     int32_t res;
   2311     res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
   2312             mClientUid, mClientPackageName);
   2313     ALOGV("checkOp returns: %d, %s ", res,
   2314             res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
   2315             res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
   2316             res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
   2317             "UNKNOWN");
   2318 
   2319     if (res != AppOpsManager::MODE_ALLOWED) {
   2320         ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
   2321                 myName.string());
   2322         block();
   2323     }
   2324 }
   2325 
   2326 void CameraService::BasicClient::block() {
   2327     ATRACE_CALL();
   2328 
   2329     // Reset the client PID to allow server-initiated disconnect,
   2330     // and to prevent further calls by client.
   2331     mClientPid = getCallingPid();
   2332     CaptureResultExtras resultExtras; // a dummy result (invalid)
   2333     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
   2334     disconnect();
   2335 }
   2336 
   2337 // ----------------------------------------------------------------------------
   2338 
   2339 void CameraService::Client::notifyError(int32_t errorCode,
   2340         const CaptureResultExtras& resultExtras) {
   2341     (void) resultExtras;
   2342     if (mRemoteCallback != NULL) {
   2343         int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
   2344         if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
   2345             api1ErrorCode = CAMERA_ERROR_DISABLED;
   2346         }
   2347         mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
   2348     } else {
   2349         ALOGE("mRemoteCallback is NULL!!");
   2350     }
   2351 }
   2352 
   2353 // NOTE: function is idempotent
   2354 binder::Status CameraService::Client::disconnect() {
   2355     ALOGV("Client::disconnect");
   2356     return BasicClient::disconnect();
   2357 }
   2358 
   2359 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
   2360     return level == API_1;
   2361 }
   2362 
   2363 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
   2364         mClient(client) {
   2365 }
   2366 
   2367 void CameraService::Client::OpsCallback::opChanged(int32_t op,
   2368         const String16& packageName) {
   2369     sp<BasicClient> client = mClient.promote();
   2370     if (client != NULL) {
   2371         client->opChanged(op, packageName);
   2372     }
   2373 }
   2374 
   2375 // ----------------------------------------------------------------------------
   2376 //                  UidPolicy
   2377 // ----------------------------------------------------------------------------
   2378 
   2379 void CameraService::UidPolicy::registerSelf() {
   2380     Mutex::Autolock _l(mUidLock);
   2381 
   2382     ActivityManager am;
   2383     if (mRegistered) return;
   2384     am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
   2385             | ActivityManager::UID_OBSERVER_IDLE
   2386             | ActivityManager::UID_OBSERVER_ACTIVE,
   2387             ActivityManager::PROCESS_STATE_UNKNOWN,
   2388             String16("cameraserver"));
   2389     status_t res = am.linkToDeath(this);
   2390     if (res == OK) {
   2391         mRegistered = true;
   2392         ALOGV("UidPolicy: Registered with ActivityManager");
   2393     }
   2394 }
   2395 
   2396 void CameraService::UidPolicy::unregisterSelf() {
   2397     Mutex::Autolock _l(mUidLock);
   2398 
   2399     ActivityManager am;
   2400     am.unregisterUidObserver(this);
   2401     am.unlinkToDeath(this);
   2402     mRegistered = false;
   2403     mActiveUids.clear();
   2404     ALOGV("UidPolicy: Unregistered with ActivityManager");
   2405 }
   2406 
   2407 void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
   2408     onUidIdle(uid, disabled);
   2409 }
   2410 
   2411 void CameraService::UidPolicy::onUidActive(uid_t uid) {
   2412     Mutex::Autolock _l(mUidLock);
   2413     mActiveUids.insert(uid);
   2414 }
   2415 
   2416 void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
   2417     bool deleted = false;
   2418     {
   2419         Mutex::Autolock _l(mUidLock);
   2420         if (mActiveUids.erase(uid) > 0) {
   2421             deleted = true;
   2422         }
   2423     }
   2424     if (deleted) {
   2425         sp<CameraService> service = mService.promote();
   2426         if (service != nullptr) {
   2427             service->blockClientsForUid(uid);
   2428         }
   2429     }
   2430 }
   2431 
   2432 bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
   2433     Mutex::Autolock _l(mUidLock);
   2434     return isUidActiveLocked(uid, callingPackage);
   2435 }
   2436 
   2437 static const int kPollUidActiveTimeoutMillis = 50;
   2438 
   2439 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
   2440     // Non-app UIDs are considered always active
   2441     // If activity manager is unreachable, assume everything is active
   2442     if (uid < FIRST_APPLICATION_UID || !mRegistered) {
   2443         return true;
   2444     }
   2445     auto it = mOverrideUids.find(uid);
   2446     if (it != mOverrideUids.end()) {
   2447         return it->second;
   2448     }
   2449     bool active = mActiveUids.find(uid) != mActiveUids.end();
   2450     if (!active) {
   2451         // We want active UIDs to always access camera with their first attempt since
   2452         // there is no guarantee the app is robustly written and would retry getting
   2453         // the camera on failure. The inverse case is not a problem as we would take
   2454         // camera away soon once we get the callback that the uid is no longer active.
   2455         ActivityManager am;
   2456         // Okay to access with a lock held as UID changes are dispatched without
   2457         // a lock and we are a higher level component.
   2458         int64_t startTimeMillis = 0;
   2459         do {
   2460             // TODO: Fix this b/109950150!
   2461             // Okay this is a hack. There is a race between the UID turning active and
   2462             // activity being resumed. The proper fix is very risky, so we temporary add
   2463             // some polling which should happen pretty rarely anyway as the race is hard
   2464             // to hit.
   2465             active = am.isUidActive(uid, callingPackage);
   2466             if (active) {
   2467                 break;
   2468             }
   2469             if (startTimeMillis <= 0) {
   2470                 startTimeMillis = uptimeMillis();
   2471             }
   2472             int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
   2473             int64_t remainingTimeMillis = kPollUidActiveTimeoutMillis - ellapsedTimeMillis;
   2474             if (remainingTimeMillis <= 0) {
   2475                 break;
   2476             }
   2477             usleep(remainingTimeMillis * 1000);
   2478         } while (true);
   2479 
   2480         if (active) {
   2481             // Now that we found out the UID is actually active, cache that
   2482             mActiveUids.insert(uid);
   2483         }
   2484     }
   2485     return active;
   2486 }
   2487 
   2488 void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
   2489         String16 callingPackage, bool active) {
   2490     updateOverrideUid(uid, callingPackage, active, true);
   2491 }
   2492 
   2493 void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
   2494     updateOverrideUid(uid, callingPackage, false, false);
   2495 }
   2496 
   2497 void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
   2498     Mutex::Autolock _l(mUidLock);
   2499     ALOGV("UidPolicy: ActivityManager has died");
   2500     mRegistered = false;
   2501     mActiveUids.clear();
   2502 }
   2503 
   2504 void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
   2505         bool active, bool insert) {
   2506     bool wasActive = false;
   2507     bool isActive = false;
   2508     {
   2509         Mutex::Autolock _l(mUidLock);
   2510         wasActive = isUidActiveLocked(uid, callingPackage);
   2511         mOverrideUids.erase(uid);
   2512         if (insert) {
   2513             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
   2514         }
   2515         isActive = isUidActiveLocked(uid, callingPackage);
   2516     }
   2517     if (wasActive != isActive && !isActive) {
   2518         sp<CameraService> service = mService.promote();
   2519         if (service != nullptr) {
   2520             service->blockClientsForUid(uid);
   2521         }
   2522     }
   2523 }
   2524 
   2525 // ----------------------------------------------------------------------------
   2526 //                  CameraState
   2527 // ----------------------------------------------------------------------------
   2528 
   2529 CameraService::CameraState::CameraState(const String8& id, int cost,
   2530         const std::set<String8>& conflicting) : mId(id),
   2531         mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting) {}
   2532 
   2533 CameraService::CameraState::~CameraState() {}
   2534 
   2535 CameraService::StatusInternal CameraService::CameraState::getStatus() const {
   2536     Mutex::Autolock lock(mStatusLock);
   2537     return mStatus;
   2538 }
   2539 
   2540 CameraParameters CameraService::CameraState::getShimParams() const {
   2541     return mShimParams;
   2542 }
   2543 
   2544 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
   2545     mShimParams = params;
   2546 }
   2547 
   2548 int CameraService::CameraState::getCost() const {
   2549     return mCost;
   2550 }
   2551 
   2552 std::set<String8> CameraService::CameraState::getConflicting() const {
   2553     return mConflicting;
   2554 }
   2555 
   2556 String8 CameraService::CameraState::getId() const {
   2557     return mId;
   2558 }
   2559 
   2560 // ----------------------------------------------------------------------------
   2561 //                  ClientEventListener
   2562 // ----------------------------------------------------------------------------
   2563 
   2564 void CameraService::ClientEventListener::onClientAdded(
   2565         const resource_policy::ClientDescriptor<String8,
   2566         sp<CameraService::BasicClient>>& descriptor) {
   2567     const auto& basicClient = descriptor.getValue();
   2568     if (basicClient.get() != nullptr) {
   2569         BatteryNotifier& notifier(BatteryNotifier::getInstance());
   2570         notifier.noteStartCamera(descriptor.getKey(),
   2571                 static_cast<int>(basicClient->getClientUid()));
   2572     }
   2573 }
   2574 
   2575 void CameraService::ClientEventListener::onClientRemoved(
   2576         const resource_policy::ClientDescriptor<String8,
   2577         sp<CameraService::BasicClient>>& descriptor) {
   2578     const auto& basicClient = descriptor.getValue();
   2579     if (basicClient.get() != nullptr) {
   2580         BatteryNotifier& notifier(BatteryNotifier::getInstance());
   2581         notifier.noteStopCamera(descriptor.getKey(),
   2582                 static_cast<int>(basicClient->getClientUid()));
   2583     }
   2584 }
   2585 
   2586 
   2587 // ----------------------------------------------------------------------------
   2588 //                  CameraClientManager
   2589 // ----------------------------------------------------------------------------
   2590 
   2591 CameraService::CameraClientManager::CameraClientManager() {
   2592     setListener(std::make_shared<ClientEventListener>());
   2593 }
   2594 
   2595 CameraService::CameraClientManager::~CameraClientManager() {}
   2596 
   2597 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
   2598         const String8& id) const {
   2599     auto descriptor = get(id);
   2600     if (descriptor == nullptr) {
   2601         return sp<BasicClient>{nullptr};
   2602     }
   2603     return descriptor->getValue();
   2604 }
   2605 
   2606 String8 CameraService::CameraClientManager::toString() const {
   2607     auto all = getAll();
   2608     String8 ret("[");
   2609     bool hasAny = false;
   2610     for (auto& i : all) {
   2611         hasAny = true;
   2612         String8 key = i->getKey();
   2613         int32_t cost = i->getCost();
   2614         int32_t pid = i->getOwnerId();
   2615         int32_t score = i->getPriority().getScore();
   2616         int32_t state = i->getPriority().getState();
   2617         auto conflicting = i->getConflicting();
   2618         auto clientSp = i->getValue();
   2619         String8 packageName;
   2620         userid_t clientUserId = 0;
   2621         if (clientSp.get() != nullptr) {
   2622             packageName = String8{clientSp->getPackageName()};
   2623             uid_t clientUid = clientSp->getClientUid();
   2624             clientUserId = multiuser_get_user_id(clientUid);
   2625         }
   2626         ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
   2627                 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
   2628 
   2629         if (clientSp.get() != nullptr) {
   2630             ret.appendFormat("User Id: %d, ", clientUserId);
   2631         }
   2632         if (packageName.size() != 0) {
   2633             ret.appendFormat("Client Package Name: %s", packageName.string());
   2634         }
   2635 
   2636         ret.append(", Conflicting Client Devices: {");
   2637         for (auto& j : conflicting) {
   2638             ret.appendFormat("%s, ", j.string());
   2639         }
   2640         ret.append("})");
   2641     }
   2642     if (hasAny) ret.append("\n");
   2643     ret.append("]\n");
   2644     return ret;
   2645 }
   2646 
   2647 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
   2648         const String8& key, const sp<BasicClient>& value, int32_t cost,
   2649         const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
   2650         int32_t state) {
   2651 
   2652     return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
   2653             key, value, cost, conflictingKeys, score, ownerId, state);
   2654 }
   2655 
   2656 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
   2657         const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
   2658     return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
   2659             partial->getConflicting(), partial->getPriority().getScore(),
   2660             partial->getOwnerId(), partial->getPriority().getState());
   2661 }
   2662 
   2663 // ----------------------------------------------------------------------------
   2664 
   2665 static const int kDumpLockRetries = 50;
   2666 static const int kDumpLockSleep = 60000;
   2667 
   2668 static bool tryLock(Mutex& mutex)
   2669 {
   2670     bool locked = false;
   2671     for (int i = 0; i < kDumpLockRetries; ++i) {
   2672         if (mutex.tryLock() == NO_ERROR) {
   2673             locked = true;
   2674             break;
   2675         }
   2676         usleep(kDumpLockSleep);
   2677     }
   2678     return locked;
   2679 }
   2680 
   2681 status_t CameraService::dump(int fd, const Vector<String16>& args) {
   2682     ATRACE_CALL();
   2683 
   2684     if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
   2685         dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
   2686                 getCallingPid(),
   2687                 getCallingUid());
   2688         return NO_ERROR;
   2689     }
   2690     bool locked = tryLock(mServiceLock);
   2691     // failed to lock - CameraService is probably deadlocked
   2692     if (!locked) {
   2693         dprintf(fd, "!! CameraService may be deadlocked !!\n");
   2694     }
   2695 
   2696     if (!mInitialized) {
   2697         dprintf(fd, "!! No camera HAL available !!\n");
   2698 
   2699         // Dump event log for error information
   2700         dumpEventLog(fd);
   2701 
   2702         if (locked) mServiceLock.unlock();
   2703         return NO_ERROR;
   2704     }
   2705     dprintf(fd, "\n== Service global info: ==\n\n");
   2706     dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
   2707     dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
   2708     for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
   2709         dprintf(fd, "    Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
   2710     }
   2711     String8 activeClientString = mActiveClientManager.toString();
   2712     dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
   2713     dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
   2714 
   2715     dumpEventLog(fd);
   2716 
   2717     bool stateLocked = tryLock(mCameraStatesLock);
   2718     if (!stateLocked) {
   2719         dprintf(fd, "CameraStates in use, may be deadlocked\n");
   2720     }
   2721 
   2722     int argSize = args.size();
   2723     for (int i = 0; i < argSize; i++) {
   2724         if (args[i] == TagMonitor::kMonitorOption) {
   2725             if (i + 1 < argSize) {
   2726                 mMonitorTags = String8(args[i + 1]);
   2727             }
   2728             break;
   2729         }
   2730     }
   2731 
   2732     for (auto& state : mCameraStates) {
   2733         String8 cameraId = state.first;
   2734 
   2735         dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
   2736 
   2737         CameraParameters p = state.second->getShimParams();
   2738         if (!p.isEmpty()) {
   2739             dprintf(fd, "  Camera1 API shim is using parameters:\n        ");
   2740             p.dump(fd, args);
   2741         }
   2742 
   2743         auto clientDescriptor = mActiveClientManager.get(cameraId);
   2744         if (clientDescriptor != nullptr) {
   2745             dprintf(fd, "  Device %s is open. Client instance dump:\n",
   2746                     cameraId.string());
   2747             dprintf(fd, "    Client priority score: %d state: %d\n",
   2748                     clientDescriptor->getPriority().getScore(),
   2749                     clientDescriptor->getPriority().getState());
   2750             dprintf(fd, "    Client PID: %d\n", clientDescriptor->getOwnerId());
   2751 
   2752             auto client = clientDescriptor->getValue();
   2753             dprintf(fd, "    Client package: %s\n",
   2754                     String8(client->getPackageName()).string());
   2755 
   2756             client->dumpClient(fd, args);
   2757         } else {
   2758             dprintf(fd, "  Device %s is closed, no client instance\n",
   2759                     cameraId.string());
   2760         }
   2761 
   2762     }
   2763 
   2764     if (stateLocked) mCameraStatesLock.unlock();
   2765 
   2766     if (locked) mServiceLock.unlock();
   2767 
   2768     mCameraProviderManager->dump(fd, args);
   2769 
   2770     dprintf(fd, "\n== Vendor tags: ==\n\n");
   2771 
   2772     sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
   2773     if (desc == NULL) {
   2774         sp<VendorTagDescriptorCache> cache =
   2775                 VendorTagDescriptorCache::getGlobalVendorTagCache();
   2776         if (cache == NULL) {
   2777             dprintf(fd, "No vendor tags.\n");
   2778         } else {
   2779             cache->dump(fd, /*verbosity*/2, /*indentation*/2);
   2780         }
   2781     } else {
   2782         desc->dump(fd, /*verbosity*/2, /*indentation*/2);
   2783     }
   2784 
   2785     // Dump camera traces if there were any
   2786     dprintf(fd, "\n");
   2787     camera3::CameraTraces::dump(fd, args);
   2788 
   2789     // Process dump arguments, if any
   2790     int n = args.size();
   2791     String16 verboseOption("-v");
   2792     String16 unreachableOption("--unreachable");
   2793     for (int i = 0; i < n; i++) {
   2794         if (args[i] == verboseOption) {
   2795             // change logging level
   2796             if (i + 1 >= n) continue;
   2797             String8 levelStr(args[i+1]);
   2798             int level = atoi(levelStr.string());
   2799             dprintf(fd, "\nSetting log level to %d.\n", level);
   2800             setLogLevel(level);
   2801         } else if (args[i] == unreachableOption) {
   2802             // Dump memory analysis
   2803             // TODO - should limit be an argument parameter?
   2804             UnreachableMemoryInfo info;
   2805             bool success = GetUnreachableMemory(info, /*limit*/ 10000);
   2806             if (!success) {
   2807                 dprintf(fd, "\n== Unable to dump unreachable memory. "
   2808                         "Try disabling SELinux enforcement. ==\n");
   2809             } else {
   2810                 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
   2811                 std::string s = info.ToString(/*log_contents*/ true);
   2812                 write(fd, s.c_str(), s.size());
   2813             }
   2814         }
   2815     }
   2816     return NO_ERROR;
   2817 }
   2818 
   2819 void CameraService::dumpEventLog(int fd) {
   2820     dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
   2821 
   2822     Mutex::Autolock l(mLogLock);
   2823     for (const auto& msg : mEventLog) {
   2824         dprintf(fd, "  %s\n", msg.string());
   2825     }
   2826 
   2827     if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
   2828         dprintf(fd, "  ...\n");
   2829     } else if (mEventLog.size() == 0) {
   2830         dprintf(fd, "  [no events yet]\n");
   2831     }
   2832     dprintf(fd, "\n");
   2833 }
   2834 
   2835 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
   2836     Mutex::Autolock al(mTorchClientMapMutex);
   2837     for (size_t i = 0; i < mTorchClientMap.size(); i++) {
   2838         if (mTorchClientMap[i] == who) {
   2839             // turn off the torch mode that was turned on by dead client
   2840             String8 cameraId = mTorchClientMap.keyAt(i);
   2841             status_t res = mFlashlight->setTorchMode(cameraId, false);
   2842             if (res) {
   2843                 ALOGE("%s: torch client died but couldn't turn off torch: "
   2844                     "%s (%d)", __FUNCTION__, strerror(-res), res);
   2845                 return;
   2846             }
   2847             mTorchClientMap.removeItemsAt(i);
   2848             break;
   2849         }
   2850     }
   2851 }
   2852 
   2853 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
   2854 
   2855     /**
   2856       * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
   2857       * binder driver
   2858       */
   2859     // PID here is approximate and can be wrong.
   2860     logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
   2861 
   2862     // check torch client
   2863     handleTorchClientBinderDied(who);
   2864 
   2865     // check camera device client
   2866     if(!evictClientIdByRemote(who)) {
   2867         ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
   2868         return;
   2869     }
   2870 
   2871     ALOGE("%s: Java client's binder died, removing it from the list of active clients",
   2872             __FUNCTION__);
   2873 }
   2874 
   2875 void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
   2876     updateStatus(status, cameraId, {});
   2877 }
   2878 
   2879 void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
   2880         std::initializer_list<StatusInternal> rejectSourceStates) {
   2881     // Do not lock mServiceLock here or can get into a deadlock from
   2882     // connect() -> disconnect -> updateStatus
   2883 
   2884     auto state = getCameraState(cameraId);
   2885 
   2886     if (state == nullptr) {
   2887         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
   2888                 cameraId.string());
   2889         return;
   2890     }
   2891 
   2892     // Update the status for this camera state, then send the onStatusChangedCallbacks to each
   2893     // of the listeners with both the mStatusStatus and mStatusListenerLock held
   2894     state->updateStatus(status, cameraId, rejectSourceStates, [this]
   2895             (const String8& cameraId, StatusInternal status) {
   2896 
   2897             if (status != StatusInternal::ENUMERATING) {
   2898                 // Update torch status if it has a flash unit.
   2899                 Mutex::Autolock al(mTorchStatusMutex);
   2900                 TorchModeStatus torchStatus;
   2901                 if (getTorchStatusLocked(cameraId, &torchStatus) !=
   2902                         NAME_NOT_FOUND) {
   2903                     TorchModeStatus newTorchStatus =
   2904                             status == StatusInternal::PRESENT ?
   2905                             TorchModeStatus::AVAILABLE_OFF :
   2906                             TorchModeStatus::NOT_AVAILABLE;
   2907                     if (torchStatus != newTorchStatus) {
   2908                         onTorchStatusChangedLocked(cameraId, newTorchStatus);
   2909                     }
   2910                 }
   2911             }
   2912 
   2913             Mutex::Autolock lock(mStatusListenerLock);
   2914 
   2915             for (auto& listener : mListenerList) {
   2916                 listener->onStatusChanged(mapToInterface(status), String16(cameraId));
   2917             }
   2918         });
   2919 }
   2920 
   2921 template<class Func>
   2922 void CameraService::CameraState::updateStatus(StatusInternal status,
   2923         const String8& cameraId,
   2924         std::initializer_list<StatusInternal> rejectSourceStates,
   2925         Func onStatusUpdatedLocked) {
   2926     Mutex::Autolock lock(mStatusLock);
   2927     StatusInternal oldStatus = mStatus;
   2928     mStatus = status;
   2929 
   2930     if (oldStatus == status) {
   2931         return;
   2932     }
   2933 
   2934     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
   2935             cameraId.string(), oldStatus, status);
   2936 
   2937     if (oldStatus == StatusInternal::NOT_PRESENT &&
   2938             (status != StatusInternal::PRESENT &&
   2939              status != StatusInternal::ENUMERATING)) {
   2940 
   2941         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
   2942                 __FUNCTION__);
   2943         mStatus = oldStatus;
   2944         return;
   2945     }
   2946 
   2947     /**
   2948      * Sometimes we want to conditionally do a transition.
   2949      * For example if a client disconnects, we want to go to PRESENT
   2950      * only if we weren't already in NOT_PRESENT or ENUMERATING.
   2951      */
   2952     for (auto& rejectStatus : rejectSourceStates) {
   2953         if (oldStatus == rejectStatus) {
   2954             ALOGV("%s: Rejecting status transition for Camera ID %s,  since the source "
   2955                     "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
   2956             mStatus = oldStatus;
   2957             return;
   2958         }
   2959     }
   2960 
   2961     onStatusUpdatedLocked(cameraId, status);
   2962 }
   2963 
   2964 void CameraService::updateProxyDeviceState(int newState,
   2965         const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
   2966     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
   2967     if (proxyBinder == nullptr) return;
   2968     String16 id(cameraId);
   2969     proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
   2970 }
   2971 
   2972 status_t CameraService::getTorchStatusLocked(
   2973         const String8& cameraId,
   2974         TorchModeStatus *status) const {
   2975     if (!status) {
   2976         return BAD_VALUE;
   2977     }
   2978     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
   2979     if (index == NAME_NOT_FOUND) {
   2980         // invalid camera ID or the camera doesn't have a flash unit
   2981         return NAME_NOT_FOUND;
   2982     }
   2983 
   2984     *status = mTorchStatusMap.valueAt(index);
   2985     return OK;
   2986 }
   2987 
   2988 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
   2989         TorchModeStatus status) {
   2990     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
   2991     if (index == NAME_NOT_FOUND) {
   2992         return BAD_VALUE;
   2993     }
   2994     mTorchStatusMap.editValueAt(index) = status;
   2995 
   2996     return OK;
   2997 }
   2998 
   2999 void CameraService::blockClientsForUid(uid_t uid) {
   3000     const auto clients = mActiveClientManager.getAll();
   3001     for (auto& current : clients) {
   3002         if (current != nullptr) {
   3003             const auto basicClient = current->getValue();
   3004             if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
   3005                 basicClient->block();
   3006             }
   3007         }
   3008     }
   3009 }
   3010 
   3011 // NOTE: This is a remote API - make sure all args are validated
   3012 status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
   3013     if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
   3014         return PERMISSION_DENIED;
   3015     }
   3016     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
   3017         return BAD_VALUE;
   3018     }
   3019     if (args.size() == 3 && args[0] == String16("set-uid-state")) {
   3020         return handleSetUidState(args, err);
   3021     } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
   3022         return handleResetUidState(args, err);
   3023     } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
   3024         return handleGetUidState(args, out, err);
   3025     } else if (args.size() == 1 && args[0] == String16("help")) {
   3026         printHelp(out);
   3027         return NO_ERROR;
   3028     }
   3029     printHelp(err);
   3030     return BAD_VALUE;
   3031 }
   3032 
   3033 status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
   3034     PermissionController pc;
   3035     int uid = pc.getPackageUid(args[1], 0);
   3036     if (uid <= 0) {
   3037         ALOGE("Unknown package: '%s'", String8(args[1]).string());
   3038         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
   3039         return BAD_VALUE;
   3040     }
   3041     bool active = false;
   3042     if (args[2] == String16("active")) {
   3043         active = true;
   3044     } else if ((args[2] != String16("idle"))) {
   3045         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
   3046         return BAD_VALUE;
   3047     }
   3048     mUidPolicy->addOverrideUid(uid, args[1], active);
   3049     return NO_ERROR;
   3050 }
   3051 
   3052 status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
   3053     PermissionController pc;
   3054     int uid = pc.getPackageUid(args[1], 0);
   3055     if (uid < 0) {
   3056         ALOGE("Unknown package: '%s'", String8(args[1]).string());
   3057         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
   3058         return BAD_VALUE;
   3059     }
   3060     mUidPolicy->removeOverrideUid(uid, args[1]);
   3061     return NO_ERROR;
   3062 }
   3063 
   3064 status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
   3065     PermissionController pc;
   3066     int uid = pc.getPackageUid(args[1], 0);
   3067     if (uid <= 0) {
   3068         ALOGE("Unknown package: '%s'", String8(args[1]).string());
   3069         dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
   3070         return BAD_VALUE;
   3071     }
   3072     if (mUidPolicy->isUidActive(uid, args[1])) {
   3073         return dprintf(out, "active\n");
   3074     } else {
   3075         return dprintf(out, "idle\n");
   3076     }
   3077 }
   3078 
   3079 status_t CameraService::printHelp(int out) {
   3080     return dprintf(out, "Camera service commands:\n"
   3081         "  get-uid-state <PACKAGE> gets the uid state\n"
   3082         "  set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
   3083         "  reset-uid-state <PACKAGE> clears the uid state override\n"
   3084         "  help print this message\n");
   3085 }
   3086 
   3087 }; // namespace android
   3088