summaryrefslogtreecommitdiff
path: root/components/libc/posix/libdl/dlopen.c
blob: baaf1667132f3da42f4dac5689730af7a832ace5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Copyright (c) 2006-2024 RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author        Notes
 * 2010-11-17      yi.qiu   first version
 */

#include <rtthread.h>
#include <rtm.h>
#include <string.h>

#include "dlmodule.h"

#define MODULE_ROOT_DIR     "/modules"

/**
 * @brief  dynamically load a shared library at runtime.
 *
 * @param  filename the path to the shared library to load, which shouldn't be set to NULL.
 * @param  flags options for loading the shared library.
 * @return void* on success, it returns a handle (a pointer) to the opened shared library, otherwise it returns NULL.
 *
 * @note   This function is an API of POSIX standard, which is used for dynamically loading shared libraries at runtime.
 *         the function first tries to check if the module is already loaded, by finding module in module list.
 *         If module is found in memory (RT_NULL check fails), the reference count (nref) is incremented.
 *         Otherwise,  dlmodule_load() will be called to load the module into memory.
 *         A handle (a pointer to the module) is returned at last, which can be used with other functions like dlsym().
 */
void* dlopen(const char *filename, int flags)
{
    struct rt_dlmodule *module;
    char *fullpath;
    const char *def_path = MODULE_ROOT_DIR;
    char module_name[RT_NAME_MAX];

    /* check parameters */
    RT_ASSERT(filename != RT_NULL);

    if (filename[0] != '/') /* it's a relative path, prefix with MODULE_ROOT_DIR */
    {
        fullpath = rt_malloc(strlen(def_path) + strlen(filename) + 2);

        /* join path and file name */
        rt_snprintf(fullpath, strlen(def_path) + strlen(filename) + 2,
            "%s/%s", def_path, filename);
    }
    else
    {
        fullpath = (char *)filename; /* absolute path, use it directly */
    }

    /* Extract module name from path (strip directory and extension)
     * This matches the logic in _dlmodule_set_name() so that dlmodule_find()
     * can properly locate already-loaded modules by their stored name.
     */
    dlmodule_extract_name(fullpath, module_name, RT_NAME_MAX);

    rt_enter_critical();

    /* find in module list using the stripped module name */
    module = dlmodule_find(module_name);

    if (module != RT_NULL)
    {
        rt_exit_critical();
        module->nref++;
    }
    else
    {
        rt_exit_critical();
        module = dlmodule_load(fullpath);
    }

    if (fullpath != filename)
    {
        rt_free(fullpath);
    }

    return (void *)module;
}
RTM_EXPORT(dlopen);