File: util.h

package info (click to toggle)
efivar 37-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,648 kB
  • sloc: ansic: 10,605; makefile: 234; asm: 34
file content (384 lines) | stat: -rw-r--r-- 16,126 bytes parent folder | download | duplicates (2)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
 * Copyright 2011-2014 Red Hat, Inc.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author(s): Peter Jones <pjones@redhat.com>
 */
#ifndef EFIVAR_UTIL_H
#define EFIVAR_UTIL_H 1

#include <alloca.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <tgmath.h>
#include <unistd.h>

#define UNUSED __attribute__((__unused__))
#define HIDDEN __attribute__((__visibility__ ("hidden")))
#define PUBLIC __attribute__((__visibility__ ("default")))
#define DESTRUCTOR __attribute__((destructor))
#define CONSTRUCTOR __attribute__((constructor))
#define ALIAS(x) __attribute__((weak, alias (#x)))
#define NONNULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
#define PRINTF(...) __attribute__((__format__(printf, __VA_ARGS__)))
#define FLATTEN __attribute__((__flatten__))
#define PACKED __attribute__((__packed__))
#define VERSION(sym, ver) __asm__(".symver " # sym "," # ver)

/*
 * I'm not actually sure when these appear, but they're present in the
 * version in front of me.
 */
#if defined(__GNUC__) && defined(__GNUC_MINOR__)
#if __GNUC__ >= 5 && __GNUC_MINOR__ >= 1
#define int_add(a, b, c) __builtin_add_overflow(a, b, c)
#define long_add(a, b, c) __builtin_add_overflow(a, b, c)
#define long_mult(a, b, c) __builtin_mul_overflow(a, b, c)
#define ulong_add(a, b, c) __builtin_add_overflow(a, b, c)
#define ulong_mult(a, b, c) __builtin_mul_overflow(a, b, c)
#endif
#endif
#ifndef int_add
#define int_add(a, b, c) ({                                             \
                const int _limit = INT_MAX;                             \
                int _ret;                                               \
                _ret = _limit - ((unsigned long long)a) >               \
                          ((unsigned long long)b);                      \
                if (!_ret)                                              \
                        *(c) = ((a) + (b));                             \
                _ret;                                                   \
        })
#endif
#ifndef long_add
#define long_add(a, b, c) ({                                            \
                const long _limit = LONG_MAX;                           \
                int _ret;                                               \
                _ret = _limit - ((unsigned long long)a) >               \
                           ((unsigned long long)b);                     \
                if (!_ret)                                              \
                        *(c) = ((a) + (b));                             \
                _ret;                                                   \
        })
#endif
#ifndef long_mult
#define long_mult(a, b, c) ({                                           \
                const long _limit = LONG_MAX;                           \
                int _ret = 1;                                           \
                if ((a) == 0 || (b) == 0)                               \
                        _ret = 0;                                       \
                else                                                    \
                        _ret = _limit / (a) < (b);                      \
                if (!_ret)                                              \
                        *(c) = ((a) * (b));                             \
                _ret;                                                   \
        })
#endif
#ifndef ulong_add
#define ulong_add(a, b, c) ({                                           \
                const unsigned long _limit = ULONG_MAX;                 \
                int _ret;                                               \
                _ret = _limit - ((unsigned long long)a) >               \
                            ((unsigned long long)b);                    \
                if (!_ret)                                              \
                        *(c) = ((a) + (b));                             \
                _ret;                                                   \
        })
#endif
#ifndef ulong_mult
#define ulong_mult(a, b, c) ({                                          \
                const unsigned long _limit = ULONG_MAX;                 \
                int _ret = 1;                                           \
                if ((a) == 0 || (b) == 0)                               \
                        _ret = 0;                                       \
                else                                                    \
                        _ret = _limit / (a) < (b);                      \
                if (!_ret)                                              \
                        *(c) = ((a) * (b));                             \
                _ret;                                                   \
        })
#endif

#if defined(__GNUC__) && defined(__GNUC_MINOR__)
#if __GNUC__ >= 5 && __GNUC_MINOR__ >= 1
#define add(a, b, c) _Generic((c),                                      \
                              int *: int_add(a,b,c),                    \
                              long *: long_add(a,b,c),                  \
                              unsigned long *: ulong_add(a,b,c))
#define mult(a, b, c) _Generic((c),                                     \
                              long *: long_mult(a,b,c),                 \
                              unsigned long *: ulong_mult(a,b,c))
#endif
#endif

#ifndef add
#define add(a, b, c) ({                                                 \
                (*(c)) = ((a) + (b));                                   \
                })
#endif
#ifndef mult
#define mult(a, b, c) ({                                                \
                (*(c)) = ((a) * (b));                                   \
                })
#endif

static inline int UNUSED
read_file(int fd, uint8_t **result, size_t *bufsize)
{
        uint8_t *p;
        size_t size = 4096;
        size_t filesize = 0;
        ssize_t s = 0;
        uint8_t *buf, *newbuf;

        if (!(newbuf = calloc(size, sizeof (uint8_t)))) {
                efi_error("could not allocate memory");
                *result = buf = NULL;
                *bufsize = 0;
                return -1;
        }
        buf = newbuf;

        do {
                p = buf + filesize;
                /* size - filesize shouldn't exceed SSIZE_MAX because we're
                 * only allocating 4096 bytes at a time and we're checking that
                 * before doing so. */
                s = read(fd, p, size - filesize);
                if (s < 0 && errno == EAGAIN) {
                        /*
                         * if we got EAGAIN, there's a good chance we've hit
                         * the kernel rate limiter.  Doing more reads is just
                         * going to make it worse, so instead, give it a rest.
                         */
                        sched_yield();
                        continue;
                } else if (s < 0) {
                        int saved_errno = errno;
                        free(buf);
                        *result = buf = NULL;
                        *bufsize = 0;
                        errno = saved_errno;
                        efi_error("could not read from file");
                        return -1;
                }
                filesize += s;
                /* only exit for empty reads */
                if (s == 0)
                        break;
                if (filesize >= size) {
                        /* See if we're going to overrun and return an error
                         * instead. */
                        if (size > (size_t)-1 - 4096) {
                                free(buf);
                                *result = buf = NULL;
                                *bufsize = 0;
                                errno = ENOMEM;
                                efi_error("could not read from file");
                                return -1;
                        }
                        newbuf = realloc(buf, size + 4096);
                        if (newbuf == NULL) {
                                int saved_errno = errno;
                                free(buf);
                                *result = buf = NULL;
                                *bufsize = 0;
                                errno = saved_errno;
                                efi_error("could not allocate memory");
                                return -1;
                        }
                        buf = newbuf;
                        memset(buf + size, '\0', 4096);
                        size += 4096;
                }
        } while (1);

        newbuf = realloc(buf, filesize+1);
        if (!newbuf) {
                free(buf);
                *result = buf = NULL;
                efi_error("could not allocate memory");
                return -1;
        }
        newbuf[filesize] = '\0';
        *result = newbuf;
        *bufsize = filesize+1;
        return 0;
}

static inline uint64_t UNUSED
lcm(uint64_t x, uint64_t y)
{
        uint64_t m = x, n = y, o;
        while ((o = m % n)) {
                m = n;
                n = o;
        }
        return (x / n) * y;
}

#ifndef strndupa
#define strndupa(s, l)                                                  \
       (__extension__ ({                                                \
                const char *__in = (s);                                 \
                size_t __len = strnlen (__in, (l));                     \
                char *__out = (char *) alloca (__len + 1);              \
                strncpy(__out, __in, __len);                            \
                __out[__len] = '\0';                                    \
                __out;                                                  \
        }))
#endif

#define asprintfa(str, fmt, args...)                                    \
        ({                                                              \
                char *_tmp = NULL;                                      \
                int _rc;                                                \
                *(str) = NULL;                                          \
                _rc = asprintf((str), (fmt), ## args);                  \
                if (_rc > 0) {                                          \
                        _tmp = strdupa(*(str));                         \
                        if (!_tmp) {                                    \
                                _rc = -1;                               \
                        } else {                                        \
                                free(*(str));                           \
                                *(str) = _tmp;                          \
                        }                                               \
                } else {                                                \
                        _rc = -1;                                       \
                }                                                       \
                _rc;                                                    \
        })

#define vasprintfa(str, fmt, ap)                                        \
        ({                                                              \
                char *_tmp = NULL;                                      \
                int _rc;                                                \
                *(str) = NULL;                                          \
                _rc = vasprintf((str), (fmt), (ap));                    \
                if (_rc > 0) {                                          \
                        _tmp = strdupa(*(str));                         \
                        if (!_tmp) {                                    \
                                _rc = -1;                               \
                        } else {                                        \
                                free(*(str));                           \
                                *(str) = _tmp;                          \
                        }                                               \
                } else {                                                \
                        _rc = -1;                                       \
                }                                                       \
                _rc;                                                    \
        })

static inline ssize_t
get_file(uint8_t **result, const char * const fmt, ...)
{
        char *path;
        uint8_t *buf = NULL;
        size_t bufsize = 0;
        ssize_t rc;
        va_list ap;
        int error;
        int fd;

        if (result == NULL) {
                efi_error("invalid parameter 'result'");
                return -1;
        }

        va_start(ap, fmt);
        rc = vasprintfa(&path, fmt, ap);
        va_end(ap);
        if (rc < 0) {
                efi_error("could not allocate memory");
                return -1;
        }

        fd = open(path, O_RDONLY);
        if (fd < 0) {
                efi_error("could not open file \"%s\" for reading",
                          path);
                return -1;
        }

        rc = read_file(fd, &buf, &bufsize);
        error = errno;
        close(fd);
        errno = error;

        if (rc < 0 || bufsize < 1) {
                /*
                 * I don't think this can happen, but I can't convince
                 * cov-scan
                 */
                if (buf)
                        free(buf);
                *result = NULL;
                efi_error("could not read file \"%s\"", path);
                return -1;
        }

        *result = buf;
        return bufsize;
}

static inline void UNUSED
swizzle_guid_to_uuid(efi_guid_t *guid)
{
        uint32_t *u32;
        uint16_t *u16;

        u32 = (uint32_t *)guid;
        u32[0] = __builtin_bswap32(u32[0]);
        u16 = (uint16_t *)&u32[1];
        u16[0] = __builtin_bswap16(u16[0]);
        u16[1] = __builtin_bswap16(u16[1]);
}

#define log_(file, line, func, level, fmt, args...)                     \
        ({                                                              \
                if (efi_get_verbose() >= level) {                       \
                        FILE *logfile_ = efi_get_logfile();             \
                        int len_ = strlen(fmt);                         \
                        fprintf(logfile_, "%s:%d %s(): ",               \
                                file, line, func);                      \
                        fprintf(logfile_, fmt, ## args);                \
                        if (!len_ || fmt[len_ - 1] != '\n')             \
                                fprintf(logfile_, "\n");                \
                }                                                       \
        })

#define LOG_VERBOSE 0
#define LOG_DEBUG 1
#ifdef log
#undef log
#endif
#define log(level, fmt, args...) log_(__FILE__, __LINE__, __func__, level, fmt, ## args)
#define debug(fmt, args...) log(LOG_DEBUG, fmt, ## args)

#endif /* EFIVAR_UTIL_H */