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