xref: /freebsd/contrib/mandoc/mandoc_aux.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /* $Id: mandoc_aux.c,v 1.12 2022/04/14 16:43:44 schwarze Exp $ */
2 /*
3  * Copyright (c) 2014, 2015, 2017, 2018 Ingo Schwarze <schwarze@openbsd.org>
4  * Copyright (c) 2009, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include "config.h"
19 
20 #include <sys/types.h>
21 
22 #if HAVE_ERR
23 #include <err.h>
24 #endif
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 
30 #define DEBUG_NODEF 1
31 #include "mandoc.h"
32 #include "mandoc_aux.h"
33 
34 
35 int
36 mandoc_asprintf(char **dest, const char *fmt, ...)
37 {
38 	va_list	 ap;
39 	int	 ret;
40 
41 	va_start(ap, fmt);
42 	ret = vasprintf(dest, fmt, ap);
43 	va_end(ap);
44 
45 	if (ret == -1)
46 		err((int)MANDOCLEVEL_SYSERR, NULL);
47 	return ret;
48 }
49 
50 void *
51 mandoc_calloc(size_t num, size_t size)
52 {
53 	void	*ptr;
54 
55 	ptr = calloc(num, size);
56 	if (ptr == NULL)
57 		err((int)MANDOCLEVEL_SYSERR, NULL);
58 	return ptr;
59 }
60 
61 void *
62 mandoc_malloc(size_t size)
63 {
64 	void	*ptr;
65 
66 	ptr = malloc(size);
67 	if (ptr == NULL)
68 		err((int)MANDOCLEVEL_SYSERR, NULL);
69 	return ptr;
70 }
71 
72 void *
73 mandoc_realloc(void *ptr, size_t size)
74 {
75 	ptr = realloc(ptr, size);
76 	if (ptr == NULL)
77 		err((int)MANDOCLEVEL_SYSERR, NULL);
78 	return ptr;
79 }
80 
81 void *
82 mandoc_reallocarray(void *ptr, size_t num, size_t size)
83 {
84 	ptr = reallocarray(ptr, num, size);
85 	if (ptr == NULL)
86 		err((int)MANDOCLEVEL_SYSERR, NULL);
87 	return ptr;
88 }
89 
90 void *
91 mandoc_recallocarray(void *ptr, size_t oldnum, size_t num, size_t size)
92 {
93 	ptr = recallocarray(ptr, oldnum, num, size);
94 	if (ptr == NULL)
95 		err((int)MANDOCLEVEL_SYSERR, NULL);
96 	return ptr;
97 }
98 
99 char *
100 mandoc_strdup(const char *ptr)
101 {
102 	char	*p;
103 
104 	p = strdup(ptr);
105 	if (p == NULL)
106 		err((int)MANDOCLEVEL_SYSERR, NULL);
107 	return p;
108 }
109 
110 char *
111 mandoc_strndup(const char *ptr, size_t sz)
112 {
113 	char	*p;
114 
115 	p = strndup(ptr, sz);
116 	if (p == NULL)
117 		err((int)MANDOCLEVEL_SYSERR, NULL);
118 	return p;
119 }
120