Coverage Report

Created: 2023-06-07 07:02

/src/core/libntech/libutils/alloc.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
  Copyright 2023 Northern.tech AS
3
4
  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
5
6
  This program is free software; you can redistribute it and/or modify it
7
  under the terms of the GNU General Public License as published by the
8
  Free Software Foundation; version 3.
9
10
  This program is distributed in the hope that it will be useful,
11
  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
  GNU General Public License for more details.
14
15
  You should have received a copy of the GNU General Public License
16
  along with this program; if not, write to the Free Software
17
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
18
19
  To the extent this program is licensed as part of the Enterprise
20
  versions of CFEngine, the applicable Commercial Open Source License
21
  (COSL) may apply to this file if you as a licensee so wish it. See
22
  included file COSL.txt.
23
*/
24
25
#define ALLOC_IMPL
26
#include <platform.h>
27
#include <alloc.h>
28
#include <cleanup.h>
29
30
static void *CheckResult(void *ptr, const char *fn, bool check_result)
31
2.32M
{
32
2.32M
    if ((ptr == NULL) && (check_result))
33
0
    {
34
0
        fputs(fn, stderr);
35
0
        fputs("CRITICAL: Unable to allocate memory\n", stderr);
36
0
        DoCleanupAndExit(255);
37
0
    }
38
2.32M
    return ptr;
39
2.32M
}
40
41
void *xmalloc(size_t size)
42
0
{
43
0
    return CheckResult(malloc(size), "xmalloc", size != 0);
44
0
}
45
46
void *xcalloc(size_t nmemb, size_t size)
47
1.27M
{
48
1.27M
    return CheckResult(calloc(nmemb, size), "xcalloc", (nmemb != 0) && (size != 0));
49
1.27M
}
50
51
void *xrealloc(void *ptr, size_t size)
52
0
{
53
0
    return CheckResult(realloc(ptr, size), "xrealloc", size != 0);
54
0
}
55
56
char *xstrdup(const char *str)
57
95.2k
{
58
95.2k
    return CheckResult(strdup(str), "xstrdup", true);
59
95.2k
}
60
61
char *xstrndup(const char *str, size_t n)
62
955k
{
63
955k
    return CheckResult(strndup(str, n), "xstrndup", true);
64
955k
}
65
66
void *xmemdup(const void *data, size_t size)
67
0
{
68
0
    return CheckResult(memdup(data, size), "xmemdup", size != 0);
69
0
}
70
71
int xasprintf(char **strp, const char *fmt, ...)
72
0
{
73
0
    va_list ap;
74
75
0
    va_start(ap, fmt);
76
0
    int res = xvasprintf(strp, fmt, ap);
77
78
0
    va_end(ap);
79
0
    return res;
80
0
}
81
82
int xvasprintf(char **strp, const char *fmt, va_list ap)
83
0
{
84
0
    int res = vasprintf(strp, fmt, ap);
85
86
0
    CheckResult(res == -1 ? NULL : *strp, "xvasprintf", true);
87
0
    return res;
88
0
}