2 * Error handling for libcdecl.
3 * Copyright © 2011-2012, 2021 Nick Bowler
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "cdecl-internal.h"
29 #include <glthread/lock.h>
30 #include <glthread/tls.h>
32 gl_once_define(static, tls_initialized);
33 static gl_tls_key_t tls_key;
36 struct cdecl_error err;
38 char str[FLEXIBLE_ARRAY_MEMBER];
41 /* This error is reserved for extremely dire out-of-memory conditions. */
42 static struct err_state err_no_mem = {
49 static void free_err(void *err)
51 if (err == &err_no_mem)
57 static void initialize(void)
60 err_no_mem.err.str = _("failed to allocate memory");
62 gl_tls_key_init(tls_key, free_err);
66 * cdecl__err(CDECL_ENOMEM);
67 * cdecl__err(code, fmt, ...);
69 * Sets the library error to code, with a printf-style error string.
71 void cdecl__err(unsigned code, ...)
74 struct err_state *state;
78 gl_once(tls_initialized, initialize);
80 state = gl_tls_get(tls_key);
81 if (!state || state == &err_no_mem) {
82 void *tmp = malloc(sizeof *state + 100);
89 gl_tls_set(tls_key, (state = tmp));
93 if (code == CDECL_ENOMEM) {
94 if (state != &err_no_mem)
95 state->err = err_no_mem.err;
100 fmt = va_arg(ap, const char *);
101 rc = vsnprintf(state->str, state->nstr, fmt, ap);
104 if (rc > 0 && rc >= state->nstr) {
108 assert(try == 0 && rc < SIZE_MAX / 4);
110 n = ((size_t)rc + 1) * 2;
111 tmp = realloc(state, sizeof *state + n);
120 state->err = err_no_mem.err;
124 state->err.str = state->str;
125 state->err.code = code;
128 const struct cdecl_error *cdecl_get_error(void)
130 struct err_state *state;
132 gl_once(tls_initialized, initialize);
134 state = gl_tls_get(tls_key);
135 return state ? &state->err : NULL;