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