]> mj.ucw.cz Git - libucw.git/blob - ucw/lib.h
Random: Defined random_gen_seed() to simplify old programs.
[libucw.git] / ucw / lib.h
1 /*
2  *      The UCW Library -- Miscellaneous Functions
3  *
4  *      (c) 1997--2018 Martin Mares <mj@ucw.cz>
5  *      (c) 2005--2014 Tomas Valla <tom@ucw.cz>
6  *      (c) 2006 Robert Spalek <robert@ucw.cz>
7  *      (c) 2007 Pavel Charvat <pchar@ucw.cz>
8  *
9  *      This software may be freely distributed and used according to the terms
10  *      of the GNU Lesser General Public License.
11  */
12
13 #ifndef _UCW_LIB_H
14 #define _UCW_LIB_H
15
16 #include <ucw/config.h>
17 #include <stdarg.h>
18 #include <stdbool.h>
19
20 #ifdef CONFIG_UCW_CLEAN_ABI
21 #define assert_failed ucw_assert_failed
22 #define assert_failed_msg ucw_assert_failed_msg
23 #define assert_failed_noinfo ucw_assert_failed_noinfo
24 #define big_alloc ucw_big_alloc
25 #define big_alloc_zero ucw_big_alloc_zero
26 #define big_free ucw_big_free
27 #define die ucw_die
28 #define log_die_hook ucw_log_die_hook
29 #define log_file ucw_log_file
30 #define log_fork ucw_log_fork
31 #define log_init ucw_log_init
32 #define log_pid ucw_log_pid
33 #define log_title ucw_log_title
34 #define msg ucw_msg
35 #define page_alloc ucw_page_alloc
36 #define page_alloc_zero ucw_page_alloc_zero
37 #define page_free ucw_page_free
38 #define page_realloc ucw_page_realloc
39 #define random_set_seed ucw_random_set_seed
40 #define random_gen_seed ucw_random_gen_seed
41 #define random_max ucw_random_max
42 #define random_max_u64 ucw_random_max_u64
43 #define random_u32 ucw_random_u32
44 #define random_u64 ucw_random_u64
45 #define vdie ucw_vdie
46 #define vmsg ucw_vmsg
47 #define xfree ucw_xfree
48 #define xmalloc ucw_xmalloc
49 #define xmalloc_zero ucw_xmalloc_zero
50 #define xrealloc ucw_xrealloc
51 #define xstrdup ucw_xstrdup
52 #endif
53
54 /*** === Macros for handling structures, offsets and alignment ***/
55
56 #define CHECK_PTR_TYPE(x, type) ((x)-(type)(x) + (type)(x))             /** Check that a pointer @x is of type @type. Fail compilation if not. **/
57 #define PTR_TO(s, i) &((s*)0)->i                                        /** Return OFFSETOF() in form of a pointer. **/
58 #define OFFSETOF(s, i) ((uint)offsetof(s, i))                           /** Offset of item @i from the start of structure @s **/
59 #define SKIP_BACK(s, i, p) ((s *)((char *)p - OFFSETOF(s, i)))          /** Given a pointer @p to item @i of structure @s, return a pointer to the start of the struct. **/
60
61 /** Align an integer @s to the nearest higher multiple of @a (which should be a power of two) **/
62 #define ALIGN_TO(s, a) (((s)+a-1)&~(a-1))
63
64 /** Align a pointer @p to the nearest higher multiple of @s. **/
65 #define ALIGN_PTR(p, s) ((uintptr_t)(p) % (s) ? (typeof(p))((uintptr_t)(p) + (s) - (uintptr_t)(p) % (s)) : (p))
66
67 #define UNALIGNED_PART(ptr, type) (((uintptr_t) (ptr)) % sizeof(type))
68
69 /*** === Other utility macros ***/
70
71 #define MIN(a,b) (((a)<(b))?(a):(b))                    /** Minimum of two numbers **/
72 #define MAX(a,b) (((a)>(b))?(a):(b))                    /** Maximum of two numbers **/
73 #define CLAMP(x,min,max) ({ typeof(x) _t=x; (_t < min) ? min : (_t > max) ? max : _t; })        /** Clip a number @x to interval [@min,@max] **/
74 #define ABS(x) ((x) < 0 ? -(x) : (x))                   /** Absolute value **/
75 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))          /** The number of elements of an array **/
76 #define STRINGIFY(x) #x                                 /** Convert macro parameter to a string **/
77 #define STRINGIFY_EXPANDED(x) STRINGIFY(x)              /** Convert an expanded macro parameter to a string **/
78 #define GLUE(x,y) x##y                                  /** Glue two tokens together **/
79 #define GLUE_(x,y) x##_##y                              /** Glue two tokens together, separating them by an underscore **/
80
81 #define COMPARE(x,y) do { if ((x)<(y)) return -1; if ((x)>(y)) return 1; } while(0)             /** Numeric comparison function for qsort() **/
82 #define REV_COMPARE(x,y) COMPARE(y,x)                                                           /** Reverse numeric comparison **/
83 #define COMPARE_LT(x,y) do { if ((x)<(y)) return 1; if ((x)>(y)) return 0; } while(0)
84 #define COMPARE_GT(x,y) COMPARE_LT(y,x)
85
86 #define ROL(x, bits) (((x) << (bits)) | ((uint)(x) >> (sizeof(uint)*8 - (bits))))               /** Bitwise rotation of an unsigned int to the left **/
87 #define ROR(x, bits) (((uint)(x) >> (bits)) | ((x) << (sizeof(uint)*8 - (bits))))               /** Bitwise rotation of an unsigned int to the right **/
88
89 /*** === Shortcuts for GCC Extensions ***/
90
91 #ifdef __GNUC__
92
93 #undef inline
94 #define NONRET __attribute__((noreturn))                                /** Function does not return **/
95 #define UNUSED __attribute__((unused))                                  /** Variable/parameter is knowingly unused **/
96 #define CONSTRUCTOR __attribute__((constructor))                        /** Call function upon start of program **/
97 #define CONSTRUCTOR_WITH_PRIORITY(p) __attribute__((constructor(p)))    /** Define constructor with a given priority **/
98 #define PACKED __attribute__((packed))                                  /** Structure should be packed **/
99 #define CONST __attribute__((const))                                    /** Function depends only on arguments **/
100 #define PURE __attribute__((pure))                                      /** Function depends only on arguments and global vars **/
101 #define FORMAT_CHECK(x,y,z) __attribute__((format(x,y,z)))              /** Checking of printf-like format strings **/
102 #define likely(x) __builtin_expect((x),1)                               /** Use `if (likely(@x))` if @x is almost always true **/
103 #define unlikely(x) __builtin_expect((x),0)                             /** Use `if (unlikely(@x))` to hint that @x is almost always false **/
104 #define ALWAYS_INLINE inline __attribute__((always_inline))             /** Forcibly inline **/
105 #define NO_INLINE __attribute__((noinline))                             /** Forcibly uninline **/
106 #define LIKE_MALLOC __attribute__((malloc))                             /** Function returns a "new" pointer **/
107 #define SENTINEL_CHECK __attribute__((sentinel))                        /** The last argument must be NULL **/
108
109 #else
110 #error This program requires the GNU C compiler.
111 #endif
112
113 /***
114  * [[logging]]
115  *
116  * === Basic logging functions (see <<log:,Logging>> and <ucw/log.h> for more)
117  ***/
118
119 enum log_levels {                       /** The available log levels to pass to msg() and friends. **/
120   L_DEBUG=0,                            // 'D' - Debugging
121   L_INFO,                               // 'I' - Informational
122   L_WARN,                               // 'W' - Warning
123   L_ERROR,                              // 'E' - Error, but non-critical
124   L_INFO_R,                             // 'i' - An alternative set of levels for messages caused by remote events
125   L_WARN_R,                             // 'w'   (e.g., a packet received via network)
126   L_ERROR_R,                            // 'e'
127   L_FATAL,                              // '!' - Fatal error
128   L_MAX
129 };
130
131 #define LOG_LEVEL_NAMES P(DEBUG) P(INFO) P(WARN) P(ERROR) P(INFO_R) P(WARN_R) P(ERROR_R) P(FATAL)
132
133 // Return the letter associated with a given severity level
134 #define LS_LEVEL_LETTER(level) ("DIWEiwe!###"[( level )])
135
136 #define L_SIGHANDLER    0x80000000      /** Avoid operations that are unsafe in signal handlers **/
137 #define L_LOGGER_ERR    0x40000000      /** Used internally to avoid infinite reporting of logging errors **/
138
139 /**
140  * This is the basic printf-like function for logging a message.
141  * The @flags contain the log level and possibly other flag bits (like `L_SIGHANDLER`).
142  * Does not change the value of errno.
143  **/
144 void msg(uint flags, const char *fmt, ...) FORMAT_CHECK(printf,2,3);
145 void vmsg(uint flags, const char *fmt, va_list args);           /** A vararg version of msg(). **/
146 void die(const char *, ...) NONRET FORMAT_CHECK(printf,1,2);    /** Log a fatal error message and exit the program. **/
147 void vdie(const char *fmt, va_list args) NONRET;                /** va_list version of die() **/
148
149 extern char *log_title;                 /** An optional log message title. Set to program name by log_init(). **/
150 extern int log_pid;                     /** An optional PID printed in each log message. Set to 0 if it shouldn't be logged. **/
151 extern void (*log_die_hook)(void);      /** An optional function called just before die() exists. **/   // API: log_die_hook
152
153 void log_init(const char *argv0);       /** Set @log_title to the program name extracted from @argv[0]. **/
154 void log_fork(void);                    /** Call after fork() to update @log_pid. **/
155 void log_file(const char *name);        /** Establish logging to the named file. Also redirect stderr there. **/
156
157 void assert_failed(const char *assertion, const char *file, int line) NONRET;
158 void assert_failed_msg(const char *assertion, const char *file, int line, const char *fmt, ...) NONRET FORMAT_CHECK(printf,4,5);
159 void assert_failed_noinfo(void) NONRET;
160
161 #ifdef DEBUG_ASSERTS
162 /**
163  * Check an assertion. If the condition @x is false, stop the program with a fatal error.
164  * Assertion checks are compiled only when `DEBUG_ASSERTS` is defined.
165  **/
166 #define ASSERT(x) ({ if (unlikely(!(x))) assert_failed(#x, __FILE__, __LINE__); 1; })
167
168 /**
169  * Check an assertion with a debug message. If the condition @cond is false,
170  * print the message and stop the program with fatal error.
171  * Assertion checks are compiled only when `DEBUG_ASSERTS` is defined.
172  **/
173 #define ASSERT_MSG(cond,str,x...) ({ if (unlikely(!(cond))) assert_failed_msg(#cond, __FILE__, __LINE__, str,##x); 1; })
174
175 #else
176 #define ASSERT(x) ({ if (__builtin_constant_p(x) && !(x)) assert_failed_noinfo(); 1; })
177 #define ASSERT_MSG(cond,str,x...) ASSERT(cond)
178 #endif
179
180 #define COMPILE_ASSERT(name,x) typedef char _COMPILE_ASSERT_##name[!!(x)-1]
181
182 #ifdef LOCAL_DEBUG
183 #define DBG(x,y...) msg(L_DEBUG, x,##y) /** If `LOCAL_DEBUG` is defined before including <ucw/lib.h>, log a debug message. Otherwise do nothing. **/
184 /**
185  * If `LOCAL_DEBUG` is defined before including <ucw/lib.h>, log current
186  * file name and line number. Otherwise do nothing.
187  **/
188 #define DBG_SPOT msg(L_DEBUG, "%s:%d (%s)", __FILE__, __LINE__, __func__)
189 #else
190 #define DBG(x,y...) do { } while(0)
191 #define DBG_SPOT do { } while(0)
192 #endif
193
194 #ifdef DEBUG_ASSERTS
195 /**
196  * Sometimes, we may want to check that a pointer points to a valid memory
197  * location before we start using it for anything more complicated. This
198  * macro checks pointer validity by reading the byte it points to.
199  **/
200 #define ASSERT_READABLE(ptr) ({ volatile char *__p = (ptr); *__p; })
201 /** Like the previous macro, but it checks writeability, too. **/
202 #define ASSERT_WRITEABLE(ptr) ({ volatile char *__p = (ptr); *__p = *__p; })
203 #else
204 #define ASSERT_READABLE(ptr) do { } while(0)
205 #define ASSERT_WRITEABLE(ptr) do { } while(0)
206 #endif
207
208 /*** === Memory allocation ***/
209
210 /*
211  * Unfortunately, several libraries we might want to link to define
212  * their own xmalloc and we don't want to interfere with them, hence
213  * the renaming.
214  */
215 #define xmalloc ucw_xmalloc
216 #define xrealloc ucw_xrealloc
217 #define xfree ucw_xfree
218
219 void *xmalloc(size_t) LIKE_MALLOC;              /** Allocate memory and die() if there is none. **/
220 void *xrealloc(void *, size_t);                 /** Reallocate memory and die() if there is none. **/
221 void xfree(void *);                             /** Free memory allocated by xmalloc() or xrealloc(). **/
222
223 void *xmalloc_zero(size_t) LIKE_MALLOC;         /** Allocate memory and fill it by zeroes. **/
224 char *xstrdup(const char *) LIKE_MALLOC;        /** Make a xmalloc()'ed copy of a string. Returns NULL for NULL string. **/
225
226 /* bigalloc.c */
227
228 void *page_alloc(u64 len) LIKE_MALLOC;          // Internal: allocates a multiple of CPU_PAGE_SIZE bytes with mmap
229 void *page_alloc_zero(u64 len) LIKE_MALLOC;
230 void page_free(void *start, u64 len);
231 void *page_realloc(void *start, u64 old_len, u64 new_len);
232
233 void *big_alloc(u64 len) LIKE_MALLOC;           /** Allocate a large memory block in the most efficient way available. **/
234 void *big_alloc_zero(u64 len) LIKE_MALLOC;      /** Allocate and clear a large memory block. **/
235 void big_free(void *start, u64 len);            /** Free block allocated by @big_alloc() or @big_alloc_zero(). **/
236
237 /*** === Random numbers (random-legacy.c) ***/
238
239 void random_set_seed(uint seed);                /** Initialize seed value for the legacy interface below. **/
240 uint random_gen_seed(void);                     /** Combines fastrand_gen_seed_value() and random_set_seed(). **/
241 uint random_u32(void);                          /** Return a pseudorandom 32-bit number. **/
242 uint random_max(uint max);                      /** Return a pseudorandom 30-bit number in range [0,@max). **/
243 u64 random_u64(void);                           /** Return a pseudorandom 64-bit number. **/
244 u64 random_max_u64(u64 max);                    /** Return a pseudorandom 64-bit number in range [0,@max). **/
245
246 #endif