-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.c
109 lines (84 loc) · 1.47 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <ctype.h>
#include <errno.h>
#include <sys/random.h>
#include "utils.h"
ssize_t xsnprintf(char *str, size_t size, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = vsnprintf(str, size, format, args);
va_end(args);
if (ret < 0)
return -1;
if ((size_t)ret >= size)
return -1;
return ret;
}
bool streq_isgraph(const char *a, const char *b)
{
while (1) {
while (isspace(*a))
a++;
while (isspace(*b))
b++;
if (*a == 0 && *b == 0)
return true;
if (*a != *b)
return false;
a++;
b++;
}
}
char *join(const char **data, char c)
{
size_t len = 0;
for (const char **elem = data; *elem; elem++) {
len += strlen(*elem);
len++;
}
char *out = malloc(len + 1);
if (!out)
return NULL;
char *p = out;
for (const char **elem = data; *elem; elem++) {
p = stpcpy(p, *elem);
*p++ = c;
}
*(p-1) = 0;
return out;
}
void wipe(void *p, size_t size)
{
volatile uint8_t *p8 = (volatile uint8_t *)p;
for (size_t i = 0; i < size; i++)
*p8 = 0;
asm volatile ("" ::: "memory");
}
void free_indirect(void *p)
{
free(*(void**)p);
}
#ifndef TESTING
int randombytes(uint8_t *out, size_t len)
{
while (len) {
ssize_t ret;
ret = getrandom(out, len, 0);
if (ret < 0) {
if (errno == EINTR)
continue;
perror("could not get randomness");
return -1;
}
out += ret;
len -= ret;
}
return 0;
}
#endif