1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <unistd.h>
4 
5 #include "memory-util.h"
6 
page_size(void)7 size_t page_size(void) {
8         static thread_local size_t pgsz = 0;
9         long r;
10 
11         if (_likely_(pgsz > 0))
12                 return pgsz;
13 
14         r = sysconf(_SC_PAGESIZE);
15         assert(r > 0);
16 
17         pgsz = (size_t) r;
18         return pgsz;
19 }
20 
memeqbyte(uint8_t byte,const void * data,size_t length)21 bool memeqbyte(uint8_t byte, const void *data, size_t length) {
22         /* Does the buffer consist entirely of the same specific byte value?
23          * Copied from https://github.com/systemd/casync/, copied in turn from
24          * https://github.com/rustyrussell/ccan/blob/master/ccan/mem/mem.c#L92,
25          * which is licensed CC-0.
26          */
27 
28         const uint8_t *p = data;
29 
30         /* Check first 16 bytes manually */
31         for (size_t i = 0; i < 16; i++, length--) {
32                 if (length == 0)
33                         return true;
34                 if (p[i] != byte)
35                         return false;
36         }
37 
38         /* Now we know first 16 bytes match, memcmp() with self.  */
39         return memcmp(data, p + 16, length) == 0;
40 }
41 
42 #if !HAVE_EXPLICIT_BZERO
43 /*
44  * The pointer to memset() is volatile so that compiler must de-reference the pointer and can't assume that
45  * it points to any function in particular (such as memset(), which it then might further "optimize"). This
46  * approach is inspired by openssl's crypto/mem_clr.c.
47  */
48 typedef void *(*memset_t)(void *,int,size_t);
49 
50 static volatile memset_t memset_func = memset;
51 
explicit_bzero_safe(void * p,size_t l)52 void* explicit_bzero_safe(void *p, size_t l) {
53         if (l > 0)
54                 memset_func(p, '\0', l);
55 
56         return p;
57 }
58 #endif
59