xref: /libuv/src/unix/dl.c (revision 64742416)
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21 
22 #include "uv.h"
23 #include "internal.h"
24 
25 #include <dlfcn.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <locale.h>
29 
30 static int uv__dlerror(uv_lib_t* lib);
31 
32 
uv_dlopen(const char * filename,uv_lib_t * lib)33 int uv_dlopen(const char* filename, uv_lib_t* lib) {
34   dlerror(); /* Reset error status. */
35   lib->errmsg = NULL;
36   lib->handle = dlopen(filename, RTLD_LAZY);
37   return lib->handle ? 0 : uv__dlerror(lib);
38 }
39 
40 
uv_dlclose(uv_lib_t * lib)41 void uv_dlclose(uv_lib_t* lib) {
42   uv__free(lib->errmsg);
43   lib->errmsg = NULL;
44 
45   if (lib->handle) {
46     /* Ignore errors. No good way to signal them without leaking memory. */
47     dlclose(lib->handle);
48     lib->handle = NULL;
49   }
50 }
51 
52 
uv_dlsym(uv_lib_t * lib,const char * name,void ** ptr)53 int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr) {
54   dlerror(); /* Reset error status. */
55   *ptr = dlsym(lib->handle, name);
56   return *ptr ? 0 : uv__dlerror(lib);
57 }
58 
59 
uv_dlerror(const uv_lib_t * lib)60 const char* uv_dlerror(const uv_lib_t* lib) {
61   return lib->errmsg ? lib->errmsg : "no error";
62 }
63 
64 
uv__dlerror(uv_lib_t * lib)65 static int uv__dlerror(uv_lib_t* lib) {
66   const char* errmsg;
67 
68   uv__free(lib->errmsg);
69 
70   errmsg = dlerror();
71 
72   if (errmsg) {
73     lib->errmsg = uv__strdup(errmsg);
74     return -1;
75   }
76   else {
77     lib->errmsg = NULL;
78     return 0;
79   }
80 }
81