1 /* SPDX-License-Identifier: MIT */
2 /*
3  * Utility functions for programs
4  *
5  * Copyright 2018 Google LLC
6  *
7  * Use of this source code is governed by an MIT-style
8  * license that can be found in the LICENSE file or at
9  * https://opensource.org/licenses/MIT.
10  */
11 #ifndef PROGRAMS_UTILS_H
12 #define PROGRAMS_UTILS_H
13 
14 #include "libfsverity.h"
15 #include "../common/common_defs.h"
16 
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 void *xmalloc(size_t size);
22 void *xzalloc(size_t size);
23 void *xmemdup(const void *mem, size_t size);
24 char *xstrdup(const char *s);
25 
26 __printf(1, 2) __cold void error_msg(const char *format, ...);
27 __printf(1, 2) __cold void error_msg_errno(const char *format, ...);
28 __printf(1, 2) __cold __noreturn void fatal_error(const char *format, ...);
29 __cold __noreturn void assertion_failed(const char *expr,
30 					const char *file, int line);
31 
32 #define ASSERT(e) ({ if (!(e)) assertion_failed(#e, __FILE__, __LINE__); })
33 
34 void install_libfsverity_error_handler(void);
35 
36 struct filedes {
37 	int fd;
38 	char *name;		/* filename, for logging or error messages */
39 };
40 
41 bool open_file(struct filedes *file, const char *filename, int flags, int mode);
42 bool get_file_size(struct filedes *file, u64 *size_ret);
43 bool full_read(struct filedes *file, void *buf, size_t count);
44 bool full_write(struct filedes *file, const void *buf, size_t count);
45 bool filedes_close(struct filedes *file);
46 int read_callback(void *file, void *buf, size_t count);
47 
48 bool hex2bin(const char *hex, u8 *bin, size_t bin_len);
49 void bin2hex(const u8 *bin, size_t bin_len, char *hex);
50 
51 #endif /* PROGRAMS_UTILS_H */
52