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