


#ifndef _GNU_SOURCE
# define _GNU_SOURCE            
#endif

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

#ifdef DSO_DLFCN

# ifdef HAVE_DLFCN_H
#  ifdef __osf__
#   define __EXTENSIONS__
#  endif
#  include <dlfcn.h>
#  define HAVE_DLINFO 1
#  if defined(__SCO_VERSION__) || defined(_SCO_ELF) || \
     (defined(__osf__) && !defined(RTLD_NEXT))     || \
     (defined(__OpenBSD__) && !defined(RTLD_SELF)) || \
     defined(__ANDROID__) || defined(__TANDEM)
#   undef HAVE_DLINFO
#  endif
# endif


# define DSO_MAX_TRANSLATED_SIZE 256

static int dlfcn_load(DSO *dso);
static int dlfcn_unload(DSO *dso);
static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname);
static char *dlfcn_name_converter(DSO *dso, const char *filename);
static char *dlfcn_merger(DSO *dso, const char *filespec1,
                          const char *filespec2);
static int dlfcn_pathbyaddr(void *addr, char *path, int sz);
static void *dlfcn_globallookup(const char *name);

static DSO_METHOD dso_meth_dlfcn = {
    "OpenSSL 'dlfcn' shared library method",
    dlfcn_load,
    dlfcn_unload,
    dlfcn_bind_func,
    NULL,                       
    dlfcn_name_converter,
    dlfcn_merger,
    NULL,                       
    NULL,                       
    dlfcn_pathbyaddr,
    dlfcn_globallookup
};

DSO_METHOD *DSO_METHOD_openssl(void)
{
    return &dso_meth_dlfcn;
}


# if defined(__OpenBSD__) || defined(__NetBSD__)
#  ifdef DL_LAZY
#   define DLOPEN_FLAG DL_LAZY
#  else
#   ifdef RTLD_NOW
#    define DLOPEN_FLAG RTLD_NOW
#   else
#    define DLOPEN_FLAG 0
#   endif
#  endif
# else
#  define DLOPEN_FLAG RTLD_NOW  
# endif



static int dlfcn_load(DSO *dso)
{
    void *ptr = NULL;
    
    char *filename = DSO_convert_filename(dso, NULL);
    int flags = DLOPEN_FLAG;
    int saveerrno = get_last_sys_error();

    if (filename == NULL) {
        ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME);
        goto err;
    }
# ifdef RTLD_GLOBAL
    if (dso->flags & DSO_FLAG_GLOBAL_SYMBOLS)
        flags |= RTLD_GLOBAL;
# endif
# ifdef _AIX
    if (filename[strlen(filename) - 1] == ')')
        flags |= RTLD_MEMBER;
# endif
    ptr = dlopen(filename, flags);
    if (ptr == NULL) {
        ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED,
                       "filename(%s): %s", filename, dlerror());
        goto err;
    }
    
    set_sys_error(saveerrno);
    if (!sk_void_push(dso->meth_data, (char *)ptr)) {
        ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR);
        goto err;
    }
    
    dso->loaded_filename = filename;
    return 1;
 err:
    
    OPENSSL_free(filename);
    if (ptr != NULL)
        dlclose(ptr);
    return 0;
}

static int dlfcn_unload(DSO *dso)
{
    void *ptr;
    if (dso == NULL) {
        ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
        return 0;
    }
    if (sk_void_num(dso->meth_data) < 1)
        return 1;
    ptr = sk_void_pop(dso->meth_data);
    if (ptr == NULL) {
        ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE);
        
        sk_void_push(dso->meth_data, ptr);
        return 0;
    }
    
    dlclose(ptr);
    return 1;
}

static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname)
{
    void *ptr;
    union {
        DSO_FUNC_TYPE sym;
        void *dlret;
    } u;

    if ((dso == NULL) || (symname == NULL)) {
        ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
        return NULL;
    }
    if (sk_void_num(dso->meth_data) < 1) {
        ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR);
        return NULL;
    }
    ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1);
    if (ptr == NULL) {
        ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE);
        return NULL;
    }
    u.dlret = dlsym(ptr, symname);
    if (u.dlret == NULL) {
        ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE,
                       "symname(%s): %s", symname, dlerror());
        return NULL;
    }
    return u.sym;
}

static char *dlfcn_merger(DSO *dso, const char *filespec1,
                          const char *filespec2)
{
    char *merged;

    if (!filespec1 && !filespec2) {
        ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
        return NULL;
    }
    
    if (!filespec2 || (filespec1 != NULL && filespec1[0] == '/')) {
        merged = OPENSSL_strdup(filespec1);
        if (merged == NULL)
            return NULL;
    }
    
    else if (!filespec1) {
        merged = OPENSSL_strdup(filespec2);
        if (merged == NULL)
            return NULL;
    } else {
        
        int spec2len, len;

        spec2len = strlen(filespec2);
        len = spec2len + strlen(filespec1);

        if (spec2len && filespec2[spec2len - 1] == '/') {
            spec2len--;
            len--;
        }
        merged = OPENSSL_malloc(len + 2);
        if (merged == NULL)
            return NULL;
        strcpy(merged, filespec2);
        merged[spec2len] = '/';
        strcpy(&merged[spec2len + 1], filespec1);
    }
    return merged;
}

static char *dlfcn_name_converter(DSO *dso, const char *filename)
{
    char *translated;
    int len, rsize, transform;

    len = strlen(filename);
    rsize = len + 1;
    transform = (strchr(filename, '/') == NULL);
    if (transform) {
        
        rsize += strlen(DSO_EXTENSION);    
        if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0)
            rsize += 3;         
    }
    translated = OPENSSL_malloc(rsize);
    if (translated == NULL) {
        ERR_raise(ERR_LIB_DSO, DSO_R_NAME_TRANSLATION_FAILED);
        return NULL;
    }
    if (transform) {
        if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0)
            sprintf(translated, "lib%s" DSO_EXTENSION, filename);
        else
            sprintf(translated, "%s" DSO_EXTENSION, filename);
    } else
        sprintf(translated, "%s", filename);
    return translated;
}

# ifdef __sgi

#  include <rld_interface.h>
#  ifndef _RLD_INTERFACE_DLFCN_H_DLADDR
#   define _RLD_INTERFACE_DLFCN_H_DLADDR
typedef struct Dl_info {
    const char *dli_fname;
    void *dli_fbase;
    const char *dli_sname;
    void *dli_saddr;
    int dli_version;
    int dli_reserved1;
    long dli_reserved[4];
} Dl_info;
#  else
typedef struct Dl_info Dl_info;
#  endif
#  define _RLD_DLADDR             14

static int dladdr(void *address, Dl_info *dl)
{
    void *v;
    v = _rld_new_interface(_RLD_DLADDR, address, dl);
    return (int)v;
}
# endif                         

# ifdef _AIX

#  include <sys/ldr.h>
#  include <errno.h>

#  define DLFCN_LDINFO_SIZE 86976
typedef struct Dl_info {
    const char *dli_fname;
} Dl_info;

static int dladdr(void *ptr, Dl_info *dl)
{
    uintptr_t addr = (uintptr_t)ptr;
    unsigned int found = 0;
    struct ld_info *ldinfos, *next_ldi, *this_ldi;

    if ((ldinfos = OPENSSL_malloc(DLFCN_LDINFO_SIZE)) == NULL) {
        errno = ENOMEM;
        dl->dli_fname = NULL;
        return 0;
    }

    if ((loadquery(L_GETINFO, (void *)ldinfos, DLFCN_LDINFO_SIZE)) < 0) {
        
        OPENSSL_free((void *)ldinfos);
        dl->dli_fname = NULL;
        return 0;
    }
    next_ldi = ldinfos;

    do {
        this_ldi = next_ldi;
        if (((addr >= (uintptr_t)this_ldi->ldinfo_textorg)
             && (addr < ((uintptr_t)this_ldi->ldinfo_textorg +
                         this_ldi->ldinfo_textsize)))
            || ((addr >= (uintptr_t)this_ldi->ldinfo_dataorg)
                && (addr < ((uintptr_t)this_ldi->ldinfo_dataorg +
                            this_ldi->ldinfo_datasize)))) {
            char *buffer, *member;
            size_t buffer_sz, member_len;

            buffer_sz = strlen(this_ldi->ldinfo_filename) + 1;
            member = this_ldi->ldinfo_filename + buffer_sz;
            if ((member_len = strlen(member)) > 0)
                buffer_sz += 1 + member_len + 1;
            found = 1;
            if ((buffer = OPENSSL_malloc(buffer_sz)) != NULL) {
                OPENSSL_strlcpy(buffer, this_ldi->ldinfo_filename, buffer_sz);
                if (member_len > 0) {
                    
                    OPENSSL_strlcat(buffer, "(", buffer_sz);
                    OPENSSL_strlcat(buffer, member, buffer_sz);
                    OPENSSL_strlcat(buffer, ")", buffer_sz);
                }
                dl->dli_fname = buffer;
            } else {
                errno = ENOMEM;
            }
        } else {
            next_ldi = (struct ld_info *)((uintptr_t)this_ldi +
                                          this_ldi->ldinfo_next);
        }
    } while (this_ldi->ldinfo_next && !found);
    OPENSSL_free((void *)ldinfos);
    return (found && dl->dli_fname != NULL);
}
# endif                         

static int dlfcn_pathbyaddr(void *addr, char *path, int sz)
{
# ifdef HAVE_DLINFO
    Dl_info dli;
    int len;

    if (addr == NULL) {
        union {
            int (*f) (void *, char *, int);
            void *p;
        } t = {
            dlfcn_pathbyaddr
        };
        addr = t.p;
    }

    if (dladdr(addr, &dli)) {
        len = (int)strlen(dli.dli_fname);
        if (sz <= 0) {
#  ifdef _AIX
            OPENSSL_free((void *)dli.dli_fname);
#  endif
            return len + 1;
        }
        if (len >= sz)
            len = sz - 1;
        memcpy(path, dli.dli_fname, len);
        path[len++] = 0;
#  ifdef _AIX
        OPENSSL_free((void *)dli.dli_fname);
#  endif
        return len;
    }

    ERR_add_error_data(2, "dlfcn_pathbyaddr(): ", dlerror());
# endif
    return -1;
}

static void *dlfcn_globallookup(const char *name)
{
    void *ret = NULL, *handle = dlopen(NULL, RTLD_LAZY);

    if (handle) {
        ret = dlsym(handle, name);
        dlclose(handle);
    }

    return ret;
}
#endif                          
