dte test coverage


Directory: ./
File: src/util/xmalloc.c
Date: 2025-09-07 23:01:39
Exec Total Coverage
Lines: 32 32 100.0%
Functions: 7 7 100.0%
Branches: 3 6 50.0%

Line Branch Exec Source
1 #include <errno.h>
2 #include <limits.h>
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include "xmalloc.h"
7 #include "debug.h"
8 #include "xsnprintf.h"
9
10 84518 static void *check_alloc(void *alloc)
11 {
12
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→4) taken 84518 times.
84518 FATAL_ERROR_ON(alloc == NULL, ENOMEM);
13 84518 return alloc;
14 }
15
16 // Like malloc(3), but calling fatal_error() on OOM and forbidding
17 // zero-sized allocations (thus never returning NULL)
18 50387 void *xmalloc(size_t size)
19 {
20 50387 BUG_ON(size == 0);
21 50387 return check_alloc(malloc(size));
22 }
23
24 3857 void *xcalloc(size_t nmemb, size_t size)
25 {
26 3857 bool overflow = calloc_args_have_ub_overflow(nmemb, size);
27
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→4) taken 3857 times.
3857 FATAL_ERROR_ON(overflow, EOVERFLOW);
28 3857 BUG_ON(nmemb == 0 || size == 0);
29 3857 return check_alloc(calloc(nmemb, size)); // NOLINT(*-unsafe-functions)
30 }
31
32 14081 void *xrealloc(void *ptr, size_t size)
33 {
34 14081 BUG_ON(size == 0);
35 14081 return check_alloc(realloc(ptr, size));
36 }
37
38 16193 char *xstrdup(const char *str)
39 {
40 16193 return check_alloc(strdup(str)); // NOLINT(*-unsafe-functions)
41 }
42
43 VPRINTF(1)
44 2 static char *xvasprintf(const char *format, va_list ap)
45 {
46 2 va_list ap2;
47 2 va_copy(ap2, ap);
48 2 int n = vsnprintf(NULL, 0, format, ap2);
49 2 va_end(ap2);
50
51
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→6) taken 2 times.
2 if (unlikely(n < 0 || n == INT_MAX || n >= SIZE_MAX)) {
52 fatal_error(__func__, n < 0 ? errno : EOVERFLOW);
53 }
54
55 2 char *str = xmalloc(n + 1);
56 2 size_t m = xvsnprintf(str, n + 1, format, ap);
57 2 BUG_ON(m != n);
58 2 return str;
59 }
60
61 2 char *xasprintf(const char *format, ...)
62 {
63 2 va_list ap;
64 2 va_start(ap, format);
65 2 char *str = xvasprintf(format, ap);
66 2 va_end(ap);
67 2 return str;
68 }
69