GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/cvs/xmalloc.c Lines: 29 42 69.0 %
Date: 2017-11-07 Branches: 12 24 50.0 %

Line Branch Exec Source
1
/* $OpenBSD: xmalloc.c,v 1.13 2015/11/17 18:25:02 tobias 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
4136
	if (size == 0)
32
		fatal("xmalloc: zero size");
33
2068
	ptr = malloc(size);
34
2068
	if (ptr == NULL)
35
		fatal("xmalloc: allocating %zu bytes: %s",
36
		    size, strerror(errno));
37
2068
	return ptr;
38
}
39
40
void *
41
xcalloc(size_t nmemb, size_t size)
42
{
43
	void *ptr;
44
45
5202
	if (size == 0 || nmemb == 0)
46
		fatal("xcalloc: zero size");
47
2601
	ptr = calloc(nmemb, size);
48
2601
	if (ptr == NULL)
49
		fatal("xcalloc: allocating %zu * %zu bytes: %s",
50
		    nmemb, size, strerror(errno));
51
2601
	return ptr;
52
}
53
54
void *
55
xreallocarray(void *ptr, size_t nmemb, size_t size)
56
{
57
	void *new_ptr;
58
59
42
	if (nmemb == 0 || size == 0)
60
		fatal("xreallocarray: zero size");
61
21
	new_ptr = reallocarray(ptr, nmemb, size);
62
21
	if (new_ptr == NULL)
63
		fatal("xreallocarray: allocating %zu * %zu bytes: %s",
64
		    nmemb, size, strerror(errno));
65
21
	return new_ptr;
66
}
67
68
char *
69
xstrdup(const char *str)
70
{
71
	char *cp;
72
73
5690
	if ((cp = strdup(str)) == NULL)
74
		fatal("xstrdup: %s", strerror(errno));
75
2845
	return cp;
76
}
77
78
int
79
xasprintf(char **ret, const char *fmt, ...)
80
{
81
74
	va_list ap;
82
	int i;
83
84
37
	va_start(ap, fmt);
85
37
	i = vasprintf(ret, fmt, ap);
86
37
	va_end(ap);
87
88

74
	if (i < 0 || *ret == NULL)
89
		fatal("xasprintf: %s", strerror(errno));
90
91
37
	return i;
92
37
}
93
94
int
95
xsnprintf(char *str, size_t len, const char *fmt, ...)
96
{
97
3752
	va_list ap;
98
	int i;
99
100
1876
	if (len > INT_MAX)
101
		fatal("xsnprintf: len > INT_MAX");
102
103
1876
	va_start(ap, fmt);
104
1876
	i = vsnprintf(str, len, fmt, ap);
105
1876
	va_end(ap);
106
107

3752
	if (i < 0 || i >= (int)len)
108
		fatal("xsnprintf: overflow");
109
110
1876
	return i;
111
1876
}