Replace MinGW with Windows to avoid ambiguities
[tinc] / src / xalloc.h
1 #ifndef TINC_XALLOC_H
2 #define TINC_XALLOC_H
3
4 /*
5    xalloc.h -- malloc and related functions with out of memory checking
6    Copyright (C) 1990, 91, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.
7    Copyright (C) 2011-2013 Guus Sliepen <guus@tinc-vpn.org>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2, or (at your option)
12    any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License along
20    with this program; if not, write to the Free Software Foundation, Inc., Foundation,
21    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 #include "system.h"
25
26 static inline void *xmalloc(size_t n) __attribute__((__malloc__));
27 static inline void *xmalloc(size_t n) {
28         void *p = malloc(n);
29
30         if(!p) {
31                 abort();
32         }
33
34         return p;
35 }
36
37 static inline void *xzalloc(size_t n) __attribute__((__malloc__));
38 static inline void *xzalloc(size_t n) {
39         void *p = calloc(1, n);
40
41         if(!p) {
42                 abort();
43         }
44
45         return p;
46 }
47
48 static inline void *xrealloc(void *p, size_t n) {
49         p = realloc(p, n);
50
51         if(!p) {
52                 abort();
53         }
54
55         return p;
56 }
57
58 static inline char *xstrdup(const char *s) __attribute__((__malloc__)) __attribute((__nonnull__));
59 static inline char *xstrdup(const char *s) {
60         char *p = strdup(s);
61
62         if(!p) {
63                 abort();
64         }
65
66         return p;
67 }
68
69 static inline int xvasprintf(char **strp, const char *fmt, va_list ap) {
70 #ifdef HAVE_WINDOWS
71         char buf[1024];
72         int result = vsnprintf(buf, sizeof(buf), fmt, ap);
73
74         if(result < 0) {
75                 abort();
76         }
77
78         *strp = xstrdup(buf);
79 #else
80         int result = vasprintf(strp, fmt, ap);
81
82         if(result < 0) {
83                 abort();
84         }
85
86 #endif
87         return result;
88 }
89
90 static inline int xasprintf(char **strp, const char *fmt, ...) __attribute__((__format__(printf, 2, 3)));
91 static inline int xasprintf(char **strp, const char *fmt, ...) {
92         va_list ap;
93         va_start(ap, fmt);
94         int result = xvasprintf(strp, fmt, ap);
95         va_end(ap);
96         return result;
97 }
98
99 #endif