1 /* vim: set expandtab ts=4 sw=4: */
2 /*
3  * You may redistribute this program and/or modify it under the terms of
4  * the GNU General Public License as published by the Free Software Foundation,
5  * either version 3 of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
14  */
15 #define _POSIX_C_SOURCE 200112L
16 
17 #include "exception/Er.h"
18 #include "util/CString.h"
19 
20 #include <stdarg.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 
24 Gcc_USE_RET
Er__raise(char * file,int line,struct Allocator * alloc,char * format,...)25 struct Er_Ret* Er__raise(char* file, int line, struct Allocator* alloc, char* format, ...)
26 {
27     va_list args;
28     va_start(args, format);
29 
30     if (alloc) {
31         int written = snprintf(NULL, 0, "%s:%d ", file, line);
32         Assert_true(written >= 0);
33 
34         va_list argsCopy;
35         va_copy(argsCopy, args);
36         int written2 = vsnprintf(NULL, 0, format, argsCopy);
37         Assert_true(written2 >= 0);
38         va_end(argsCopy);
39 
40         int len = written + written2 + 1;
41 
42         char* buf = Allocator_calloc(alloc, len, 1);
43 
44         snprintf(buf, len, "%s:%d ", file, line);
45         vsnprintf(&buf[written], len - written, format, args);
46         struct Er_Ret* res = Allocator_calloc(alloc, sizeof(struct Er_Ret), 1);
47         res->message = buf;
48         va_end(args);
49         return res;
50     } else {
51         fprintf(stderr, "%s:%d ", file, line);
52         vfprintf(stderr, format, args);
53         fprintf(stderr, "\n");
54     }
55     abort();
56     exit(100);
57 }
58 
Er__assertFail(struct Er_Ret * er)59 void Er__assertFail(struct Er_Ret* er)
60 {
61     if (!er) { return; }
62     fprintf(stderr, "%s\n", er->message);
63     abort();
64     exit(100);
65 }