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