void BpBinder::sendObituary()
{
    ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n",
        this, mHandle, mObitsSent ? "true" : "false");

    mAlive = 0;
    if (mObitsSent) return;

    mLock.lock();
    Vector<Obituary>* obits = mObituaries;
    if(obits != NULL) {
        ALOGV("Clearing sent death notification: %p handle %d\n", this, mHandle);
        IPCThreadState* self = IPCThreadState::self();
        self->clearDeathNotification(mHandle, this);
        self->flushCommands();
        mObituaries = NULL;
    }
    mObitsSent = 1;
    mLock.unlock();

    ALOGV("Reporting death of proxy %p for %d recipients\n",
        this, obits ? obits->size() : 0);

    if (obits != NULL) {
        const size_t N = obits->size();
        for (size_t i=0; i<N; i++) {
            reportOneDeath(obits->itemAt(i));
        }

        delete obits;
    }
}
static void android_os_Parcel_enforceInterface(JNIEnv* env, jclass clazz, jlong nativePtr, jstring name)
{
    Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
    if (parcel != NULL) {
        const jchar* str = env->GetStringCritical(name, 0);
        if (str) {
            IPCThreadState* threadState = IPCThreadState::self();
            const int32_t oldPolicy = threadState->getStrictModePolicy();
            const bool isValid = parcel->enforceInterface(
                String16(reinterpret_cast<const char16_t*>(str),
                         env->GetStringLength(name)),
                threadState);
            env->ReleaseStringCritical(name, str);
            if (isValid) {
                const int32_t newPolicy = threadState->getStrictModePolicy();
                if (oldPolicy != newPolicy) {
                    // Need to keep the Java-level thread-local strict
                    // mode policy in sync for the libcore
                    // enforcements, which involves an upcall back
                    // into Java.  (We can't modify the
                    // Parcel.enforceInterface signature, as it's
                    // pseudo-public, and used via AIDL
                    // auto-generation...)
                    set_dalvik_blockguard_policy(env, newPolicy);
                }
                return;     // everything was correct -> return silently
            }
        }
    }

    // all error conditions wind up here
    jniThrowException(env, "java/lang/SecurityException",
            "Binder invocation to an incorrect interface");
}
Exemplo n.º 3
0
status_t FakeSurfaceComposer::onTransact(uint32_t code, const Parcel& data,
                                         Parcel* reply, uint32_t flags)
{
    switch (code) {
        case CREATE_CONNECTION:
        case CREATE_DISPLAY:
        case SET_TRANSACTION_STATE:
        case CAPTURE_SCREEN:
        {
            // codes that require permission check
            IPCThreadState* ipc = IPCThreadState::self();
            const int pid = ipc->getCallingPid();
            const int uid = ipc->getCallingUid();
            // Accept request only when uid is root.
            if (uid != AID_ROOT) {
                ALOGE("Permission Denial: "
                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
                return PERMISSION_DENIED;
            }
            break;
        }
    }

    return BnSurfaceComposer::onTransact(code, data, reply, flags);
}
BpBinder::~BpBinder()
{
    ALOGV("Destroying BpBinder %p handle %d\n", this, mHandle);

    IPCThreadState* ipc = IPCThreadState::self();

    mLock.lock();
    Vector<Obituary>* obits = mObituaries;
    if(obits != NULL) {
        if (ipc) ipc->clearDeathNotification(mHandle, this);
        mObituaries = NULL;
    }
    mLock.unlock();

    if (obits != NULL) {
        // XXX Should we tell any remaining DeathRecipient
        // objects that the last strong ref has gone away, so they
        // are no longer linked?
        delete obits;
    }

    if (ipc) {
        ipc->expungeHandle(mHandle, this);
        ipc->decWeakHandle(mHandle);
    }
}
Exemplo n.º 5
0
bool Permission::checkCalling() const
{
    IPCThreadState* ipcState = IPCThreadState::self();
    pid_t pid = ipcState->getCallingPid();
    uid_t uid = ipcState->getCallingUid();
    return doCheckPermission(pid, uid);
}
Exemplo n.º 6
0
static bool isProtectedCallAllowed() {
    // M: migration these from ICS
    // TODO
    // Following implementation is just for reference.
    // Each OEM manufacturer should implement/replace with their own solutions.
    bool result = false;

    IPCThreadState* ipcState = IPCThreadState::self();
    uid_t uid = ipcState->getCallingUid();

    for (unsigned int i = 0; i < trustedUids.size(); ++i) {
        if (trustedUids[i] == uid) {
            result = true;
            break;
        }
    }

    // M:
    // for OMA DRM v1 implementation
    // if can't authorize the process by UID, then check the process name.
    if (!result) {
        pid_t pid = ipcState->getCallingPid();
        result = DrmTrustedClient::IsDrmTrustedClient(DrmMtkUtil::getProcessName(pid));
    }

    return result;
}
status_t BpBinder::linkToDeath(
    const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
{
    Obituary ob;
    ob.recipient = recipient;
    ob.cookie = cookie;
    ob.flags = flags;

    LOG_ALWAYS_FATAL_IF(recipient == NULL,
                        "linkToDeath(): recipient must be non-NULL");

    {
        AutoMutex _l(mLock);

        if (!mObitsSent) {
            if (!mObituaries) {
                mObituaries = new Vector<Obituary>;
                if (!mObituaries) {
                    return NO_MEMORY;
                }
                ALOGV("Requesting death notification: %p handle %d\n", this, mHandle);
                getWeakRefs()->incWeak(this);
                IPCThreadState* self = IPCThreadState::self();
                self->requestDeathNotification(mHandle, this);
                self->flushCommands();
            }
            ssize_t res = mObituaries->add(ob);
            return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
        }
    }

    return DEAD_OBJECT;
}
status_t BpBinder::unlinkToDeath(
    const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
    wp<DeathRecipient>* outRecipient)
{
    AutoMutex _l(mLock);

    if (mObitsSent) {
        return DEAD_OBJECT;
    }

    const size_t N = mObituaries ? mObituaries->size() : 0;
    for (size_t i=0; i<N; i++) {
        const Obituary& obit = mObituaries->itemAt(i);
        if ((obit.recipient == recipient
                    || (recipient == NULL && obit.cookie == cookie))
                && obit.flags == flags) {
            const uint32_t allFlags = obit.flags|flags;
            if (outRecipient != NULL) {
                *outRecipient = mObituaries->itemAt(i).recipient;
            }
            mObituaries->removeAt(i);
            if (mObituaries->size() == 0) {
                ALOGV("Clearing death notification: %p handle %d\n", this, mHandle);
                IPCThreadState* self = IPCThreadState::self();
                self->clearDeathNotification(mHandle, this);
                self->flushCommands();
                delete mObituaries;
                mObituaries = NULL;
            }
            return NO_ERROR;
        }
    }

    return NAME_NOT_FOUND;
}
sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
{
    mLock.lock();
    sp<IBinder> object(
        mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : NULL);
    mLock.unlock();
    
    //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
    
    if (object != NULL) return object;

    // Don't attempt to retrieve contexts if we manage them
    if (mManagesContexts) {
        ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
            String8(name).string());
        return NULL;
    }
    
    IPCThreadState* ipc = IPCThreadState::self();
    {
        Parcel data, reply;
        // no interface token on this magic transaction
        data.writeString16(name);
        data.writeStrongBinder(caller);
        status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
        if (result == NO_ERROR) {
            object = reply.readStrongBinder();
        }
    }
    
    ipc->flushCommands();
    
    if (object != NULL) setContextObject(object, name);
    return object;
}
Exemplo n.º 10
0
status_t BnQService::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    // IPC should be from mediaserver only
    IPCThreadState* ipc = IPCThreadState::self();
    const int callerPid = ipc->getCallingPid();
    const int callerUid = ipc->getCallingUid();

    const bool permission = (callerUid == AID_MEDIA);

    switch(code) {
        case CONNECT: {
            CHECK_INTERFACE(IQService, data, reply);

            sp<IQClient> client =
                interface_cast<IQClient>(data.readStrongBinder());
            connect(client);
            return NO_ERROR;
        } break;
		case SETMEM: {
            CHECK_INTERFACE(IQService, data, reply);

            sp<IMemory> sharedBuffer =
                interface_cast<IMemory>(data.readStrongBinder());
            setMemory(sharedBuffer);
            return NO_ERROR;
        } break;
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
}
Exemplo n.º 11
0
void BpBinder::onLastStrongRef(const void* id)
{
    ALOGV("onLastStrongRef BpBinder %p handle %d\n", this, mHandle);
    IF_ALOGV() {
        printRefs();
    }
    IPCThreadState* ipc = IPCThreadState::self();
    if (ipc) ipc->decStrongHandle(mHandle);
}
bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid)
{
    IPCThreadState* ipcState = IPCThreadState::self();
    pid_t pid = ipcState->getCallingPid();
    uid_t uid = ipcState->getCallingUid();
    if (outPid) *outPid = pid;
    if (outUid) *outUid = uid;
    return checkPermission(permission, pid, uid);
}
    virtual int enroll(uint32_t uid,
            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
            const uint8_t *current_password, uint32_t current_password_length,
            const uint8_t *desired_password, uint32_t desired_password_length,
            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
        IPCThreadState* ipc = IPCThreadState::self();
        const int calling_pid = ipc->getCallingPid();
        const int calling_uid = ipc->getCallingUid();
        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
            return PERMISSION_DENIED;
        }

        // need a desired password to enroll
        if (desired_password_length == 0) return -EINVAL;

        int ret;
        if (device) {
            const gatekeeper::password_handle_t *handle =
                    reinterpret_cast<const gatekeeper::password_handle_t *>(current_password_handle);

            if (handle != NULL && handle->version != 0 && !handle->hardware_backed) {
                // handle is being re-enrolled from a software version. HAL probably won't accept
                // the handle as valid, so we nullify it and enroll from scratch
                current_password_handle = NULL;
                current_password_handle_length = 0;
                current_password = NULL;
                current_password_length = 0;
            }

            ret = device->enroll(device, uid, current_password_handle, current_password_handle_length,
                    current_password, current_password_length,
                    desired_password, desired_password_length,
                    enrolled_password_handle, enrolled_password_handle_length);
        } else {
            ret = soft_device->enroll(uid,
                    current_password_handle, current_password_handle_length,
                    current_password, current_password_length,
                    desired_password, desired_password_length,
                    enrolled_password_handle, enrolled_password_handle_length);
        }

        if (ret == 0) {
            gatekeeper::password_handle_t *handle =
                    reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
            store_sid(uid, handle->user_id);
            bool rr;

            // immediately verify this password so we don't ask the user to enter it again
            // if they just created it.
            verify(uid, *enrolled_password_handle, sizeof(password_handle_t), desired_password,
                    desired_password_length, &rr);
        }

        return ret;
    }
status_t BatteryPropertiesRegistrar::dump(int fd, const Vector<String16>& /*args*/) {
    IPCThreadState* self = IPCThreadState::self();
    const int pid = self->getCallingPid();
    const int uid = self->getCallingUid();
    if ((uid != AID_SHELL) &&
        !PermissionCache::checkPermission(
                String16("android.permission.DUMP"), pid, uid))
        return PERMISSION_DENIED;

    healthd_dump_battery_state(fd);
    return OK;
}
    virtual void clearSecureUserId(uint32_t uid) {
        IPCThreadState* ipc = IPCThreadState::self();
        const int calling_pid = ipc->getCallingPid();
        const int calling_uid = ipc->getCallingUid();
        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
            ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
            return;
        }
        clear_sid(uid);

        if (device != NULL && device->delete_user != NULL) {
            device->delete_user(device, uid);
        }
    }
Exemplo n.º 16
0
status_t BnMediaAnalyticsService::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{


    // get calling pid/tid
    IPCThreadState *ipc = IPCThreadState::self();
    int clientPid = ipc->getCallingPid();
    // permission checking

    if(DEBUGGING_FLOW) {
        ALOGD("running in service, code %d, pid %d; called from pid %d",
            code, getpid(), clientPid);
    }

    switch (code) {

        case GENERATE_UNIQUE_SESSIONID: {
            CHECK_INTERFACE(IMediaAnalyticsService, data, reply);

            MediaAnalyticsItem::SessionID_t sessionid = generateUniqueSessionID();
            reply->writeInt64(sessionid);

            return NO_ERROR;
        } break;

        case SUBMIT_ITEM: {
            CHECK_INTERFACE(IMediaAnalyticsService, data, reply);

            bool forcenew;
            MediaAnalyticsItem *item = new MediaAnalyticsItem;

            data.readBool(&forcenew);
            item->readFromParcel(data);

            item->setPid(clientPid);

            // submit() takes over ownership of 'item'
            MediaAnalyticsItem::SessionID_t sessionid = submit(item, forcenew);
            reply->writeInt64(sessionid);

            return NO_ERROR;
        } break;

        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
}
Exemplo n.º 17
0
BpBinder::~BpBinder()
{
    ALOGV("Destroying BpBinder %p handle %d\n", this, mHandle);

    IPCThreadState* ipc = IPCThreadState::self();

    if (mTrackedUid >= 0) {
        AutoMutex _l(sTrackingLock);
        uint32_t trackedValue = sTrackingMap[mTrackedUid];
        if (CC_UNLIKELY((trackedValue & COUNTING_VALUE_MASK) == 0)) {
            ALOGE("Unexpected Binder Proxy tracking decrement in %p handle %d\n", this, mHandle);
        } else {
            if (CC_UNLIKELY(
                (trackedValue & LIMIT_REACHED_MASK) &&
                ((trackedValue & COUNTING_VALUE_MASK) <= sBinderProxyCountLowWatermark)
                )) {
                ALOGI("Limit reached bit reset for uid %d (fewer than %d proxies from uid %d held)",
                                   getuid(), mTrackedUid, sBinderProxyCountLowWatermark);
                sTrackingMap[mTrackedUid] &= ~LIMIT_REACHED_MASK;
            }
            if (--sTrackingMap[mTrackedUid] == 0) {
                sTrackingMap.erase(mTrackedUid);
            }
        }
    }

    mLock.lock();
    Vector<Obituary>* obits = mObituaries;
    if(obits != NULL) {
        if (ipc) ipc->clearDeathNotification(mHandle, this);
        mObituaries = NULL;
    }
    mLock.unlock();

    if (obits != NULL) {
        // XXX Should we tell any remaining DeathRecipient
        // objects that the last strong ref has gone away, so they
        // are no longer linked?
        delete obits;
    }

    if (ipc) {
        ipc->expungeHandle(mHandle, this);
        ipc->decWeakHandle(mHandle);
    }
}
    virtual status_t dump(int fd, const Vector<String16> &) {
        IPCThreadState* ipc = IPCThreadState::self();
        const int pid = ipc->getCallingPid();
        const int uid = ipc->getCallingUid();
        if (!PermissionCache::checkPermission(DUMP_PERMISSION, pid, uid)) {
            return PERMISSION_DENIED;
        }

        if (device == NULL) {
            const char *result = "Device not available";
            write(fd, result, strlen(result) + 1);
        } else {
            const char *result = "OK";
            write(fd, result, strlen(result) + 1);
        }

        return NO_ERROR;
    }
Exemplo n.º 19
0
status_t Client::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    // these must be checked
     IPCThreadState* ipc = IPCThreadState::self();
     const int pid = ipc->getCallingPid();
     const int uid = ipc->getCallingUid();
     const int self_pid = getpid();
     if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) {
         // we're called from a different process, do the real check
         if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
         {
             ALOGE("Permission Denial: "
                     "can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
             return PERMISSION_DENIED;
         }
     }
     return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
}
status_t LayerBaseClient::Surface::onTransact(
        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    switch (code) {
        case REGISTER_BUFFERS:
        case UNREGISTER_BUFFERS:
        case CREATE_OVERLAY:
        {
            if (!mFlinger->mAccessSurfaceFlinger.checkCalling()) {
                IPCThreadState* ipc = IPCThreadState::self();
                const int pid = ipc->getCallingPid();
                const int uid = ipc->getCallingUid();
                LOGE("Permission Denial: "
                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
                return PERMISSION_DENIED;
            }
        }
    }
    return BnSurface::onTransact(code, data, reply, flags);
}
Exemplo n.º 21
0
int
GonkSchedulePolicyService::requestPriority(int32_t pid, int32_t tid, int32_t prio)
{
    // See SchedulingPolicyService.java
#define PRIORITY_MIN 1
#define PRIORITY_MAX 3

    IPCThreadState* ipcState = IPCThreadState::self();
    if (ipcState->getCallingUid() != AID_MEDIA ||
        prio < PRIORITY_MIN || prio > PRIORITY_MAX ||
        !tidBelongsToPid(tid, pid))
        return -1; /* PackageManager.PERMISSION_DENIED */

    set_sched_policy(tid, ipcState->getCallingPid() == pid ?
                          SP_AUDIO_SYS : SP_AUDIO_APP);
    struct sched_param param;
    param.sched_priority = prio;
    int rc = sched_setscheduler(tid, SCHED_FIFO, &param);
    if (rc)
        return -1;

    return 0; /* PackageManger.PERMISSION_GRANTED */
}
Exemplo n.º 22
0
status_t Client::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    // these must be checked
     IPCThreadState* ipc = IPCThreadState::self();
     const int pid = ipc->getCallingPid();
     const int uid = ipc->getCallingUid();
     const int self_pid = getpid();
     // If we are called from another non root process without the GRAPHICS, SYSTEM, or ROOT
     // uid we require the sAccessSurfaceFlinger permission.
     // We grant an exception in the case that the Client has a "parent layer", as its
     // effects will be scoped to that layer.
     if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != 0)
             && (getParentLayer() == nullptr)) {
         // we're called from a different process, do the real check
         if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
         {
             ALOGE("Permission Denial: "
                     "can't openGlobalTransaction pid=%d, uid<=%d", pid, uid);
             return PERMISSION_DENIED;
         }
     }
     return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
}
Exemplo n.º 23
0
status_t BnMonzax::onTransact(
        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{

    status_t status = BBinder::onTransact(code, data, reply, flags);
    if (status != UNKNOWN_TRANSACTION) {
        return status;
    }
    if (! reply) {
        ALOGE("Monzax::onTransact(): null reply parcel received.");
        return BAD_VALUE;
    }

    IPCThreadState *ipc = IPCThreadState::self();
    const int pid = ipc->getCallingPid();
    const int uid = ipc->getCallingUid();

    // dispatch to the appropriate method based on the transaction code.
    switch(code){
        case FILE_OPEN:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                ALOGI("BnMonzax: onTransact: FILE_OPEN"
                    "client to access MonzaxService from uid=%d pid=%d code: %d",
                    uid, pid, code);
                char *pName = (char *) data.readCString();
                int ret = file_open(pName);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_CLOSE:
            {
                ALOGI("BnMonzax: onTransact: FILE_CLOSE"
                    "client to access MonzaxService from uid=%d pid=%d code: %d",
                    uid, pid, code);
                CHECK_INTERFACE(IMonzax, data, reply);
                int fd = data.readInt32();
                int ret = file_close(fd);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_SEEK:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                int ret;

                int fd = data.readInt32();
                int offset = data.readInt32();
                int whence = data.readInt32();
                ret = file_seek(fd, offset, whence);
                reply->writeInt32(ret);
                return NO_ERROR;
            }
            break;
        case FILE_READ:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                char *pReadBuf;
                int ret;

                int fd = data.readInt32();
                int length = data.readInt32();
                pReadBuf = (char*) malloc(sizeof(char) * length);
                if (pReadBuf == NULL) {
                    ret = -1;
                    reply->writeInt32(ret);
                    ALOGE("onTransact File_Read malloc result failed.\n");
                    goto err_read;
                }
                ret = file_read(fd, pReadBuf, length);
                reply->writeInt32(ret);
                if(ret >0){
                    reply->write((char *) pReadBuf, ret);
                }
                free(pReadBuf);
                pReadBuf = NULL;
                return NO_ERROR;
err_read:
                ALOGE("onTransact File_Read ,ret =%d out\n",  (int)ret);
                return ret;
            }
            break;
        case FILE_WRITE:
            {
                CHECK_INTERFACE(IMonzax, data, reply);
                int ret;
                int fd = data.readInt32();
                int length = data.readInt32();
                char *pWriteBuf = (char*) malloc(sizeof(char) * length);
                if (pWriteBuf == NULL) {
                    ret = -1;
                    reply->writeInt32(ret);
                    ALOGE("onTransact File_Write malloc result failed.\n");
                    goto err_write;
                }
                if(length > 0){
                    const char *input = (const char *) data.readInplace(length);
                    if (input)
                        memcpy(pWriteBuf, input, length);
                    else {
                        ALOGE("onTransact File_Write length is 0, failed.\n");
                        memset(pWriteBuf, 0, length);
                        length = 0;
                    }
                } else
                    memset(pWriteBuf, 0, length);

                ret = file_write(fd, (char *)pWriteBuf, length);
                reply->writeInt32(ret);
                free(pWriteBuf);
                pWriteBuf = NULL;
                return NO_ERROR;
err_write:
                ALOGE("onTransact File_Write ,ret =%d out\n",  (int)ret);
                return ret;
            }
            break;
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }
}
/**
 * The VM calls this when mutex contention debugging is enabled to
 * determine whether or not the blocked thread was a "sensitive thread"
 * for user responsiveness/smoothess.
 *
 * Our policy for this is whether or not we're tracing any StrictMode
 * events on this thread (which we might've inherited via Binder calls
 * into us)
 */
static bool runtime_isSensitiveThread() {
    IPCThreadState* state = IPCThreadState::selfOrNull();
    return state && state->getStrictModePolicy() != 0;
}
Exemplo n.º 25
0
/*******************************************************************************
**
**  gc_gralloc_alloc_buffer
**
**  Allocate android native buffer.
**  Will allocate surface types as follows,
**
**  +------------------------------------------------------------------------+
**  | To Allocate Surface(s)        | Linear(surface) | Tile(resolveSurface) |
**  |------------------------------------------------------------------------|
**  |Enable              |  CPU app |      yes        |                      |
**  |LINEAR OUTPUT       |  3D app  |      yes        |                      |
**  |------------------------------------------------------------------------|
**  |Diable              |  CPU app |      yes        |                      |
**  |LINEAR OUTPUT       |  3D app  |                 |         yes          |
**  +------------------------------------------------------------------------+
**
**
**  INPUT:
**
**      alloc_device_t * Dev
**          alloc device handle.
**
**      int Width
**          Specified target buffer width.
**
**      int Hieght
**          Specified target buffer height.
**
**      int Format
**          Specified target buffer format.
**
**      int Usage
**          Specified target buffer usage.
**
**  OUTPUT:
**
**      buffer_handle_t * Handle
**          Pointer to hold the allocated buffer handle.
**
**      int * Stride
**          Pointer to hold buffer stride.
*/
static int
gc_gralloc_alloc_buffer(
    alloc_device_t * Dev,
    int Width,
    int Height,
    int Format,
    int Usage,
    buffer_handle_t * Handle,
    int * Stride
    )
{
    int err = 0;
    int fd = open("/dev/null",O_RDONLY,0);

    gceSTATUS status = gcvSTATUS_OK;
    gctUINT stride   = 0;

    gceSURF_FORMAT format             = gcvSURF_UNKNOWN;
    gceSURF_FORMAT resolveFormat      = gcvSURF_UNKNOWN;
    (void) resolveFormat;

    /* Linear stuff. */
    gcoSURF surface                   = gcvNULL;
    gcuVIDMEM_NODE_PTR vidNode        = gcvNULL;
    gcePOOL pool                      = gcvPOOL_UNKNOWN;
    gctUINT adjustedSize              = 0U;

    /* Tile stuff. */
    gcoSURF resolveSurface            = gcvNULL;
    gcuVIDMEM_NODE_PTR resolveVidNode = gcvNULL;
    gcePOOL resolvePool               = gcvPOOL_UNKNOWN;
    gctUINT resolveAdjustedSize       = 0U;

    gctSIGNAL signal                  = gcvNULL;
    gctINT clientPID                  = 0;

    gctBOOL forSelf                   = gcvTRUE;

    /* Binder info. */
    IPCThreadState* ipc               = IPCThreadState::self();

    /* Buffer handle. */
    gc_private_handle_t * handle      = NULL;

    /* Cast module. */
    gralloc_module_t * module =
        reinterpret_cast<gralloc_module_t *>(Dev->common.module);

    /* Convert to hal pixel format. */
    gcmONERROR(
       _ConvertAndroid2HALFormat(Format,
                                 &format));

    clientPID = ipc->getCallingPid();

    forSelf = (clientPID == getpid());

    if (forSelf)
    {
        LOGI("Self allocation");
    }

    /* Allocate tiled surface if needed. */
#if !gcdGPU_LINEAR_BUFFER_ENABLED
    if (Usage & GRALLOC_USAGE_HW_RENDER)
    {
        /* Get the resolve format. */
        gcmONERROR(
            gcoTEXTURE_GetClosestFormat(gcvNULL,
                                        format,
                                        &resolveFormat));

        /* Construct the tile surface. */
        gcmONERROR(
            gcoSURF_Construct(gcvNULL,
                              Width,
                              Height,
                              1,
                              gcvSURF_TEXTURE,
                              resolveFormat,
                              gcvPOOL_DEFAULT,
                              &resolveSurface));

        /* 3D surfaces are bottom-top. */
        gcmONERROR(
            gcoSURF_SetOrientation(resolveSurface,
                                   gcvORIENTATION_BOTTOM_TOP));

        /*
        gcmONERROR(gcoSURF_SetUsage(resolveSurface, (Usage & GRALLOC_USAGE_SW_WRITE_MASK) ?
                                                    gcvSURF_USAGE_RESOLVE_AFTER_CPU : gcvSURF_USAGE_RESOLVE_AFTER_3D));
         */

        /* Now retrieve and store vid mem node attributes. */
        gcmONERROR(
           gcoSURF_QueryVidMemNode(resolveSurface,
                                   &resolveVidNode,
                                   &resolvePool,
                                   &resolveAdjustedSize));

        /* Android expects stride in pixels which is returned as alignedWidth. */
        gcmONERROR(
            gcoSURF_GetAlignedSize(resolveSurface,
                                   &stride,
                                   gcvNULL,
                                   gcvNULL));

        LOGV("resolve buffer resolveSurface=%p, "
             "resolveNode=%p, "
             "resolvevidnode=%p, "
             "resolveBytes=%d, "
             "resolvePool=%d, "
             "resolveFormat=%d",
             (void *) resolveSurface,
             (void *) &resolveSurface->info.node,
             (void *) resolveVidNode,
             resolveAdjustedSize,
             resolvePool,
             resolveFormat);
    }
#endif

#if !gcdGPU_LINEAR_BUFFER_ENABLED
    /* Allocate linear surface if needed. */
    if (Usage & GRALLOC_USAGE_SW_WRITE_MASK)
#endif
    {
        /* For CPU apps, if allocating for self (i.e. for server a.k.a. SF),
         * then we must request a cacheable allocation so when it gets mapped,
         * it'll be cacheable. Otherwise, the surface will be mapped uncached
         * in the server, but cached in the client. */
        gceSURF_TYPE type = (forSelf && (Usage & GRALLOC_USAGE_SW_WRITE_MASK))
                          ? gcvSURF_CACHEABLE_BITMAP : gcvSURF_BITMAP;

#if gcdANDROID_UNALIGNED_LINEAR_COMPOSITION_ADJUST
        if (Usage & GRALLOC_USAGE_HW_RENDER)
        {
            type = gcvSURF_FLIP_BITMAP;
        }
#endif

        /* Allocate from contiguous pool for CPU apps while from default pool
         * for GPU apps. */
        pool = (Usage & GRALLOC_USAGE_SW_WRITE_MASK) ? gcvPOOL_CONTIGUOUS
             : gcvPOOL_DEFAULT;

        /* Allocate the linear surface. */
        gcmONERROR(
            gcoSURF_Construct(gcvNULL,
                              Width,
                              Height,
                              1,
                              type,
                              format,
                              pool,
                              &surface));

        /* Now retrieve and store vid mem node attributes. */
        gcmONERROR(
           gcoSURF_QueryVidMemNode(surface,
                                   &vidNode,
                                   &pool,
                                   &adjustedSize));

        /* Get stride. */
        gcmONERROR(
            gcoSURF_GetAlignedSize(surface,
                                   &stride,
                                   gcvNULL,
                                   gcvNULL));

        LOGV("allocated buffer surface=%p, "
             "node=%p, "
             "vidNode=%p, "
             "pool=%d, "
             "bytes=%d, "
             "width=%d, height=%d, "
             "formatRequested=%d, "
             "usage=0x%08X",
             (void *) surface,
             (void *) &surface->info.node,
             (void *) vidNode,
             pool,
             adjustedSize,
             Width, Height,
             format,
             Usage);
    }

    if (!(Usage & GRALLOC_USAGE_HW_RENDER))
    {
        /* For CPU apps, we must synchronize lock requests from CPU with the composition.
         * Composition could happen in the following ways. i)2D, ii)3D, iii)CE, iv)copybit 2D.
         * (Note that, we are not considering copybit composition of 3D apps, which also uses
         * linear surfaces. Can be added later if needed.)

         * In all cases, the following mechanism must be used for proper synchronization
         * between CPU and GPU :

         * - App on gralloc::lock
         *      wait_signal(hwDoneSignal);

         * - Compositor on composition
         *      set_unsignalled(hwDoneSignal);
         *      issue composition;
         *      schedule_event(hwDoneSignal, clientPID);

         *  This is a manually reset signal, which is unsignalled by the compositor when
         *  buffer is in use, prohibiting app from obtaining write lock.
         */
        /* Manually reset signal, for CPU/GPU sync. */
        gcmONERROR(gcoOS_CreateSignal(gcvNULL,
                                      gcvTRUE,
                                      &signal));

        /* Initially signalled. */
        gcmONERROR(gcoOS_Signal(gcvNULL,
                                signal,
                                gcvTRUE));

        LOGV("Created signal=%p for hnd=%p", signal, handle);
    }

    /* Allocate buffer handle. */
    handle = new gc_private_handle_t(fd, stride * Height, 0);

    handle->width               = (int) Width;
    handle->height              = (int) Height;
    handle->format              = (int) format;
    handle->size                = ((surface == gcvNULL) ? 0 : (int) surface->info.node.size);

    /* Save linear surface to buffer handle. */
    handle->surface             = (int) surface;
    handle->vidNode             = (int) vidNode;
    handle->pool                = (int) pool;
    handle->adjustedSize        = (int) adjustedSize;

    /* Save tile resolveSurface to buffer handle. */
    handle->resolveSurface      = (int) resolveSurface;
    handle->resolveVidNode      = (int) resolveVidNode;
    handle->resolvePool         = (int) resolvePool;
    handle->resolveAdjustedSize = (int) resolveAdjustedSize;

    handle->hwDoneSignal        = (int) signal;

    /* Record usage to recall later in hwc. */
    handle->lockUsage           = 0;
    handle->allocUsage          = Usage;
    handle->clientPID           = clientPID;

    LOGV("allocated buffer handle=%p, "
         "width=%d, height=%d, "
         "formatRequested=%d, "
         "usage=0x%08X, "
         "stride=%d pixels",
         (void *) handle,
         Width,
         Height,
         format,
         Usage,
         stride);

    /* Map video memory to userspace. */
    err = _MapBuffer(module, handle);

    if (err == 0)
    {
        *Handle = handle;
        *Stride = stride;
    }
    else
    {
        gcmONERROR(gcvSTATUS_NOT_SUPPORTED);
    }

    return err;

OnError:
    /* Destroy linear surface. */
    if (surface != gcvNULL)
    {
        gcoSURF_Destroy(surface);
    }

    /* Destroy tile resolveSurface. */
    if (resolveSurface != gcvNULL)
    {
        gcoSURF_Destroy(resolveSurface);
    }

    /* Destroy signal. */
    if (signal)
    {
        gcoOS_DestroySignal(gcvNULL, signal);
    }

    /* Error roll back. */
    if (handle != NULL)
    {
        delete handle;
    }

    LOGE("failed to allocate, status=%d", status);

    return -EINVAL;
}
Exemplo n.º 26
0
bool BpBinder::onIncStrongAttempted(uint32_t flags, const void* id)
{
    ALOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, mHandle);
    IPCThreadState* ipc = IPCThreadState::self();
    return ipc ? ipc->attemptIncStrongHandle(mHandle) == NO_ERROR : false;
}
    virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
            const uint8_t *provided_password, uint32_t provided_password_length,
            uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
        IPCThreadState* ipc = IPCThreadState::self();
        const int calling_pid = ipc->getCallingPid();
        const int calling_uid = ipc->getCallingUid();
        if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
            return PERMISSION_DENIED;
        }

        // can't verify if we're missing either param
        if ((enrolled_password_handle_length | provided_password_length) == 0)
            return -EINVAL;

        int ret;
        if (device) {
            const gatekeeper::password_handle_t *handle =
                    reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
            // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
            // a HAL if there was none before
            if (handle->version == 0 || handle->hardware_backed) {
                ret = device->verify(device, uid, challenge,
                    enrolled_password_handle, enrolled_password_handle_length,
                    provided_password, provided_password_length, auth_token, auth_token_length,
                    request_reenroll);
            } else {
                // upgrade scenario, a HAL has been added to this device where there was none before
                SoftGateKeeperDevice soft_dev;
                ret = soft_dev.verify(uid, challenge,
                    enrolled_password_handle, enrolled_password_handle_length,
                    provided_password, provided_password_length, auth_token, auth_token_length,
                    request_reenroll);

                if (ret == 0) {
                    // success! re-enroll with HAL
                    *request_reenroll = true;
                }
            }
        } else {
            ret = soft_device->verify(uid, challenge,
                enrolled_password_handle, enrolled_password_handle_length,
                provided_password, provided_password_length, auth_token, auth_token_length,
                request_reenroll);
        }

        if (ret == 0 && *auth_token != NULL && *auth_token_length > 0) {
            // TODO: cache service?
            sp<IServiceManager> sm = defaultServiceManager();
            sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
            sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
            if (service != NULL) {
                status_t ret = service->addAuthToken(*auth_token, *auth_token_length);
                if (ret != ResponseCode::NO_ERROR) {
                    ALOGE("Falure sending auth token to KeyStore: %d", ret);
                }
            } else {
                ALOGE("Unable to communicate with KeyStore");
            }
        }

        if (ret == 0) {
            maybe_store_sid(uid, reinterpret_cast<const gatekeeper::password_handle_t *>(
                        enrolled_password_handle)->user_id);
        }

        return ret;
    }
Exemplo n.º 28
0
void BpBinder::onFirstRef()
{
    ALOGV("onFirstRef BpBinder %p handle %d\n", this, mHandle);
    IPCThreadState* ipc = IPCThreadState::self();
    if (ipc) ipc->incStrongHandle(mHandle);
}