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