• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: MIT
2 /*
3  * Utility functions for libfsverity
4  *
5  * Copyright 2020 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 
12 #include "lib_private.h"
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 
xmalloc(size_t size)18 static void *xmalloc(size_t size)
19 {
20 	void *p = malloc(size);
21 
22 	if (!p)
23 		libfsverity_error_msg("out of memory (tried to allocate %zu bytes)",
24 				      size);
25 	return p;
26 }
27 
libfsverity_zalloc(size_t size)28 void *libfsverity_zalloc(size_t size)
29 {
30 	void *p = xmalloc(size);
31 
32 	if (!p)
33 		return NULL;
34 	return memset(p, 0, size);
35 }
36 
libfsverity_memdup(const void * mem,size_t size)37 void *libfsverity_memdup(const void *mem, size_t size)
38 {
39 	void *p = xmalloc(size);
40 
41 	if (!p)
42 		return NULL;
43 	return memcpy(p, mem, size);
44 }
45 
46 static void (*libfsverity_error_cb)(const char *msg);
47 
48 LIBEXPORT void
libfsverity_set_error_callback(void (* cb)(const char * msg))49 libfsverity_set_error_callback(void (*cb)(const char *msg))
50 {
51 	libfsverity_error_cb = cb;
52 }
53 
libfsverity_do_error_msg(const char * format,va_list va)54 void libfsverity_do_error_msg(const char *format, va_list va)
55 {
56 	int saved_errno = errno;
57 	char *msg = NULL;
58 
59 	if (!libfsverity_error_cb)
60 		return;
61 
62 	if (vasprintf(&msg, format, va) < 0)
63 		goto out;
64 
65 	(*libfsverity_error_cb)(msg);
66 
67 	free(msg);
68 out:
69 	errno = saved_errno;
70 }
71 
libfsverity_error_msg(const char * format,...)72 void libfsverity_error_msg(const char *format, ...)
73 {
74 	va_list va;
75 
76 	va_start(va, format);
77 	libfsverity_do_error_msg(format, va);
78 	va_end(va);
79 }
80 
libfsverity_warn_on(const char * condition,const char * file,int line)81 void libfsverity_warn_on(const char *condition, const char *file, int line)
82 {
83 	fprintf(stderr, "libfsverity internal error! %s at %s:%d\n",
84 		condition, file, line);
85 }
86 
libfsverity_bug_on(const char * condition,const char * file,int line)87 void libfsverity_bug_on(const char *condition, const char *file, int line)
88 {
89 	fprintf(stderr, "libfsverity internal error! %s at %s:%d\n"
90 		"Non-recoverable, aborting program.\n", condition, file, line);
91 	abort();
92 }
93 
libfsverity_mem_is_zeroed(const void * mem,size_t size)94 bool libfsverity_mem_is_zeroed(const void *mem, size_t size)
95 {
96 	const u8 *p = mem;
97 	size_t i;
98 
99 	for (i = 0; i < size; i++) {
100 		if (p[i])
101 			return false;
102 	}
103 	return true;
104 }
105