convert malloc use under libc-internal locks to use internal allocator
[musl] / src / ldso / dlerror.c
1 #include <dlfcn.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include "pthread_impl.h"
5 #include "dynlink.h"
6 #include "lock.h"
7
8 #define malloc __libc_malloc
9 #define calloc __libc_calloc
10 #define realloc __libc_realloc
11 #define free __libc_free
12
13 char *dlerror()
14 {
15         pthread_t self = __pthread_self();
16         if (!self->dlerror_flag) return 0;
17         self->dlerror_flag = 0;
18         char *s = self->dlerror_buf;
19         if (s == (void *)-1)
20                 return "Dynamic linker failed to allocate memory for error message";
21         else
22                 return s;
23 }
24
25 static volatile int freebuf_queue_lock[1];
26 static void **freebuf_queue;
27
28 void __dl_thread_cleanup(void)
29 {
30         pthread_t self = __pthread_self();
31         if (self->dlerror_buf && self->dlerror_buf != (void *)-1) {
32                 LOCK(freebuf_queue_lock);
33                 void **p = (void **)self->dlerror_buf;
34                 *p = freebuf_queue;
35                 freebuf_queue = p;
36                 UNLOCK(freebuf_queue_lock);
37         }
38 }
39
40 hidden void __dl_vseterr(const char *fmt, va_list ap)
41 {
42         LOCK(freebuf_queue_lock);
43         void **q = freebuf_queue;
44         freebuf_queue = 0;
45         UNLOCK(freebuf_queue_lock);
46
47         while (q) {
48                 void **p = *q;
49                 free(q);
50                 q = p;
51         }
52
53         va_list ap2;
54         va_copy(ap2, ap);
55         pthread_t self = __pthread_self();
56         if (self->dlerror_buf != (void *)-1)
57                 free(self->dlerror_buf);
58         size_t len = vsnprintf(0, 0, fmt, ap2);
59         if (len < sizeof(void *)) len = sizeof(void *);
60         va_end(ap2);
61         char *buf = malloc(len+1);
62         if (buf) {
63                 vsnprintf(buf, len+1, fmt, ap);
64         } else {
65                 buf = (void *)-1;       
66         }
67         self->dlerror_buf = buf;
68         self->dlerror_flag = 1;
69 }
70
71 hidden void __dl_seterr(const char *fmt, ...)
72 {
73         va_list ap;
74         va_start(ap, fmt);
75         __dl_vseterr(fmt, ap);
76         va_end(ap);
77 }
78
79 static int stub_invalid_handle(void *h)
80 {
81         __dl_seterr("Invalid library handle %p", (void *)h);
82         return 1;
83 }
84
85 weak_alias(stub_invalid_handle, __dl_invalid_handle);