1 /* SPDX-License-Identifier: MIT */ 2 /* 3 * Common definitions for libfsverity and the 'fsverity' program 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 COMMON_COMMON_DEFS_H 12 #define COMMON_COMMON_DEFS_H 13 14 #include <stdbool.h> 15 #include <stddef.h> 16 #include <stdint.h> 17 18 #include "win32_defs.h" 19 20 typedef uint8_t u8; 21 typedef uint16_t u16; 22 typedef uint32_t u32; 23 typedef uint64_t u64; 24 25 #ifndef __force 26 # ifdef __CHECKER__ 27 # define __force __attribute__((force)) 28 # else 29 # define __force 30 # endif 31 #endif 32 33 #ifndef __printf 34 # define __printf(fmt_idx, vargs_idx) \ 35 __attribute__((format(printf, fmt_idx, vargs_idx))) 36 #endif 37 38 #ifndef __noreturn 39 # define __noreturn __attribute__((noreturn)) 40 #endif 41 42 #ifndef __cold 43 # define __cold __attribute__((cold)) 44 #endif 45 46 #define min(a, b) ({ \ 47 __typeof__(a) _a = (a); \ 48 __typeof__(b) _b = (b); \ 49 _a < _b ? _a : _b; \ 50 }) 51 52 #define max(a, b) ({ \ 53 __typeof__(a) _a = (a); \ 54 __typeof__(b) _b = (b); \ 55 _a > _b ? _a : _b; \ 56 }) 57 58 #define roundup(x, y) ({ \ 59 __typeof__(y) _y = (y); \ 60 (((x) + _y - 1) / _y) * _y; \ 61 }) 62 63 #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0])) 64 65 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) 66 is_power_of_2(unsigned long n)67static inline bool is_power_of_2(unsigned long n) 68 { 69 return n != 0 && ((n & (n - 1)) == 0); 70 } 71 ilog2(unsigned long n)72static inline int ilog2(unsigned long n) 73 { 74 return (8 * sizeof(n) - 1) - __builtin_clzl(n); 75 } 76 77 /* ========== Endianness conversion ========== */ 78 79 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ 80 # define cpu_to_le16(v) ((__force __le16)(u16)(v)) 81 # define le16_to_cpu(v) ((__force u16)(__le16)(v)) 82 # define cpu_to_le32(v) ((__force __le32)(u32)(v)) 83 # define le32_to_cpu(v) ((__force u32)(__le32)(v)) 84 # define cpu_to_le64(v) ((__force __le64)(u64)(v)) 85 # define le64_to_cpu(v) ((__force u64)(__le64)(v)) 86 #else 87 # define cpu_to_le16(v) ((__force __le16)__builtin_bswap16(v)) 88 # define le16_to_cpu(v) (__builtin_bswap16((__force u16)(v))) 89 # define cpu_to_le32(v) ((__force __le32)__builtin_bswap32(v)) 90 # define le32_to_cpu(v) (__builtin_bswap32((__force u32)(v))) 91 # define cpu_to_le64(v) ((__force __le64)__builtin_bswap64(v)) 92 # define le64_to_cpu(v) (__builtin_bswap64((__force u64)(v))) 93 #endif 94 95 #endif /* COMMON_COMMON_DEFS_H */ 96