Coverage Report

Created: 2023-12-12 06:10

/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
  Licensed under the Apache License, Version 2.0 (the "License");
7
  you may not use this file except in compliance with the License.
8
  You may obtain a copy of the License at
9
10
      http://www.apache.org/licenses/LICENSE-2.0
11
12
  Unless required by applicable law or agreed to in writing, software
13
  distributed under the License is distributed on an "AS IS" BASIS,
14
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
  See the License for the specific language governing permissions and
16
  limitations under the License.
17
18
  To the extent this program is licensed as part of the Enterprise
19
  versions of CFEngine, the applicable Commercial Open Source License
20
  (COSL) may apply to this file if you as a licensee so wish it. See
21
  included file COSL.txt.
22
*/
23
24
#define ALLOC_IMPL
25
#include <platform.h>
26
#include <alloc.h>
27
#include <cleanup.h>
28
29
static void *CheckResult(void *ptr, const char *fn, bool check_result)
30
2.46M
{
31
2.46M
    if ((ptr == NULL) && (check_result))
32
0
    {
33
0
        fputs(fn, stderr);
34
0
        fputs("CRITICAL: Unable to allocate memory\n", stderr);
35
0
        DoCleanupAndExit(255);
36
0
    }
37
2.46M
    return ptr;
38
2.46M
}
39
40
void *xmalloc(size_t size)
41
0
{
42
0
    return CheckResult(malloc(size), "xmalloc", size != 0);
43
0
}
44
45
void *xcalloc(size_t nmemb, size_t size)
46
1.37M
{
47
1.37M
    return CheckResult(calloc(nmemb, size), "xcalloc", (nmemb != 0) && (size != 0));
48
1.37M
}
49
50
void *xrealloc(void *ptr, size_t size)
51
0
{
52
0
    return CheckResult(realloc(ptr, size), "xrealloc", size != 0);
53
0
}
54
55
char *xstrdup(const char *str)
56
121k
{
57
121k
    return CheckResult(strdup(str), "xstrdup", true);
58
121k
}
59
60
char *xstrndup(const char *str, size_t n)
61
961k
{
62
961k
    return CheckResult(strndup(str, n), "xstrndup", true);
63
961k
}
64
65
void *xmemdup(const void *data, size_t size)
66
0
{
67
0
    return CheckResult(memdup(data, size), "xmemdup", size != 0);
68
0
}
69
70
int xasprintf(char **strp, const char *fmt, ...)
71
0
{
72
0
    va_list ap;
73
74
0
    va_start(ap, fmt);
75
0
    int res = xvasprintf(strp, fmt, ap);
76
77
0
    va_end(ap);
78
0
    return res;
79
0
}
80
81
int xvasprintf(char **strp, const char *fmt, va_list ap)
82
0
{
83
0
    int res = vasprintf(strp, fmt, ap);
84
85
0
    CheckResult(res == -1 ? NULL : *strp, "xvasprintf", true);
86
0
    return res;
87
0
}