xref: /openbsd/usr.bin/cvs/xmalloc.c (revision 73471bf0)
1 /* $OpenBSD: xmalloc.c,v 1.14 2019/06/28 05:44:09 deraadt Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Versions of malloc and friends that check their results, and never return
7  * failure (they call fatal if they encounter an error).
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  */
15 
16 #include <errno.h>
17 #include <limits.h>
18 #include <stdint.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 
23 #include "log.h"
24 #include "xmalloc.h"
25 
26 void *
27 xmalloc(size_t size)
28 {
29 	void *ptr;
30 
31 	if (size == 0)
32 		fatal("xmalloc: zero size");
33 	ptr = malloc(size);
34 	if (ptr == NULL)
35 		fatal("xmalloc: allocating %zu bytes: %s",
36 		    size, strerror(errno));
37 	return ptr;
38 }
39 
40 void *
41 xcalloc(size_t nmemb, size_t size)
42 {
43 	void *ptr;
44 
45 	if (size == 0 || nmemb == 0)
46 		fatal("xcalloc: zero size");
47 	ptr = calloc(nmemb, size);
48 	if (ptr == NULL)
49 		fatal("xcalloc: allocating %zu * %zu bytes: %s",
50 		    nmemb, size, strerror(errno));
51 	return ptr;
52 }
53 
54 void *
55 xreallocarray(void *ptr, size_t nmemb, size_t size)
56 {
57 	void *new_ptr;
58 
59 	if (nmemb == 0 || size == 0)
60 		fatal("xreallocarray: zero size");
61 	new_ptr = reallocarray(ptr, nmemb, size);
62 	if (new_ptr == NULL)
63 		fatal("xreallocarray: allocating %zu * %zu bytes: %s",
64 		    nmemb, size, strerror(errno));
65 	return new_ptr;
66 }
67 
68 char *
69 xstrdup(const char *str)
70 {
71 	char *cp;
72 
73 	if ((cp = strdup(str)) == NULL)
74 		fatal("xstrdup: %s", strerror(errno));
75 	return cp;
76 }
77 
78 int
79 xasprintf(char **ret, const char *fmt, ...)
80 {
81 	va_list ap;
82 	int i;
83 
84 	va_start(ap, fmt);
85 	i = vasprintf(ret, fmt, ap);
86 	va_end(ap);
87 
88 	if (i == -1)
89 		fatal("xasprintf: %s", strerror(errno));
90 
91 	return i;
92 }
93 
94 int
95 xsnprintf(char *str, size_t len, const char *fmt, ...)
96 {
97 	va_list ap;
98 	int i;
99 
100 	if (len > INT_MAX)
101 		fatal("xsnprintf: len > INT_MAX");
102 
103 	va_start(ap, fmt);
104 	i = vsnprintf(str, len, fmt, ap);
105 	va_end(ap);
106 
107 	if (i < 0 || i >= (int)len)
108 		fatal("xsnprintf: overflow");
109 
110 	return i;
111 }
112