


#define OPENSSL_SUPPRESS_DEPRECATED

#include "internal/e_os.h"
#include "eng_local.h"


int engine_unlocked_init(ENGINE *e)
{
    int to_return = 1;

    if ((e->funct_ref == 0) && e->init)
        
        to_return = e->init(e);
    if (to_return) {
        int ref;

        
        if (!CRYPTO_UP_REF(&e->struct_ref, &ref)) {
            e->finish(e);
            return 0;
        }
        e->funct_ref++;
        ENGINE_REF_PRINT(e, 0, 1);
        ENGINE_REF_PRINT(e, 1, 1);
    }
    return to_return;
}


int engine_unlocked_finish(ENGINE *e, int unlock_for_handlers)
{
    int to_return = 1;

    
    e->funct_ref--;
    ENGINE_REF_PRINT(e, 1, -1);
    if ((e->funct_ref == 0) && e->finish) {
        if (unlock_for_handlers)
            CRYPTO_THREAD_unlock(global_engine_lock);
        to_return = e->finish(e);
        if (unlock_for_handlers)
            if (!CRYPTO_THREAD_write_lock(global_engine_lock))
                return 0;
        if (!to_return)
            return 0;
    }
    REF_ASSERT_ISNT(e->funct_ref < 0);
    
    if (!engine_free_util(e, 0)) {
        ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FINISH_FAILED);
        return 0;
    }
    return to_return;
}


int ENGINE_init(ENGINE *e)
{
    int ret;
    if (e == NULL) {
        ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER);
        return 0;
    }
    if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) {
        
        ERR_raise(ERR_LIB_ENGINE, ERR_R_CRYPTO_LIB);
        return 0;
    }
    if (!CRYPTO_THREAD_write_lock(global_engine_lock))
        return 0;
    ret = engine_unlocked_init(e);
    CRYPTO_THREAD_unlock(global_engine_lock);
    return ret;
}


int ENGINE_finish(ENGINE *e)
{
    int to_return = 1;

    if (e == NULL)
        return 1;
    if (!CRYPTO_THREAD_write_lock(global_engine_lock))
        return 0;
    to_return = engine_unlocked_finish(e, 1);
    CRYPTO_THREAD_unlock(global_engine_lock);
    if (!to_return) {
        ERR_raise(ERR_LIB_ENGINE, ENGINE_R_FINISH_FAILED);
        return 0;
    }
    return to_return;
}
