1 /*
2  * Copyright (C) the libgit2 contributors. All rights reserved.
3  *
4  * This file is part of libgit2, distributed under the GNU GPL v2 with
5  * a Linking Exception. For full terms see the included COPYING file.
6  */
7 #ifndef INCLUDE_util_h__
8 #define INCLUDE_util_h__
9 
10 #include "common.h"
11 
12 #ifndef GIT_WIN32
13 # include <ctype.h>
14 #endif
15 
16 #include "git2/buffer.h"
17 
18 #include "buffer.h"
19 #include "common.h"
20 #include "strnlen.h"
21 #include "thread.h"
22 
23 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
24 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
25 #define MSB(x, bits) ((x) & (~UINT64_C(0) << (bitsizeof(x) - (bits))))
26 #ifndef min
27 # define min(a,b) ((a) < (b) ? (a) : (b))
28 #endif
29 #ifndef max
30 # define max(a,b) ((a) > (b) ? (a) : (b))
31 #endif
32 
33 #if defined(__GNUC__)
34 # define GIT_CONTAINER_OF(ptr, type, member) \
35 	__builtin_choose_expr( \
36 	    __builtin_offsetof(type, member) == 0 && \
37 	    __builtin_types_compatible_p(__typeof__(&((type *) 0)->member), __typeof__(ptr)), \
38 		((type *) (ptr)), \
39 		(void)0)
40 #else
41 # define GIT_CONTAINER_OF(ptr, type, member) (type *)(ptr)
42 #endif
43 
44 #define GIT_DATE_RFC2822_SZ  32
45 
46 /**
47  * Return the length of a constant string.
48  * We are aware that `strlen` performs the same task and is usually
49  * optimized away by the compiler, whilst being safer because it returns
50  * valid values when passed a pointer instead of a constant string; however
51  * this macro will transparently work with wide-char and single-char strings.
52  */
53 #define CONST_STRLEN(x) ((sizeof(x)/sizeof(x[0])) - 1)
54 
55 #define STRCMP_CASESELECT(IGNORE_CASE, STR1, STR2) \
56 	((IGNORE_CASE) ? strcasecmp((STR1), (STR2)) : strcmp((STR1), (STR2)))
57 
58 #define CASESELECT(IGNORE_CASE, ICASE, CASE) \
59 	((IGNORE_CASE) ? (ICASE) : (CASE))
60 
61 extern int git__prefixcmp(const char *str, const char *prefix);
62 extern int git__prefixcmp_icase(const char *str, const char *prefix);
63 extern int git__prefixncmp(const char *str, size_t str_n, const char *prefix);
64 extern int git__prefixncmp_icase(const char *str, size_t str_n, const char *prefix);
65 extern int git__suffixcmp(const char *str, const char *suffix);
66 
git__signum(int val)67 GIT_INLINE(int) git__signum(int val)
68 {
69 	return ((val > 0) - (val < 0));
70 }
71 
72 extern int git__strntol32(int32_t *n, const char *buff, size_t buff_len, const char **end_buf, int base);
73 extern int git__strntol64(int64_t *n, const char *buff, size_t buff_len, const char **end_buf, int base);
74 
75 
76 extern void git__hexdump(const char *buffer, size_t n);
77 extern uint32_t git__hash(const void *key, int len, uint32_t seed);
78 
79 /* 32-bit cross-platform rotl */
80 #ifdef _MSC_VER /* use built-in method in MSVC */
81 #	define git__rotl(v, s) (uint32_t)_rotl(v, s)
82 #else /* use bitops in GCC; with o2 this gets optimized to a rotl instruction */
83 #	define git__rotl(v, s) (uint32_t)(((uint32_t)(v) << (s)) | ((uint32_t)(v) >> (32 - (s))))
84 #endif
85 
86 extern char *git__strtok(char **end, const char *sep);
87 extern char *git__strsep(char **end, const char *sep);
88 
89 extern void git__strntolower(char *str, size_t len);
90 extern void git__strtolower(char *str);
91 
92 #ifdef GIT_WIN32
git__tolower(int c)93 GIT_INLINE(int) git__tolower(int c)
94 {
95 	return (c >= 'A' && c <= 'Z') ? (c + 32) : c;
96 }
97 #else
98 # define git__tolower(a) tolower(a)
99 #endif
100 
101 extern size_t git__linenlen(const char *buffer, size_t buffer_len);
102 
git__next_line(const char * s)103 GIT_INLINE(const char *) git__next_line(const char *s)
104 {
105 	while (*s && *s != '\n') s++;
106 	while (*s == '\n' || *s == '\r') s++;
107 	return s;
108 }
109 
git__memrchr(const void * s,int c,size_t n)110 GIT_INLINE(const void *) git__memrchr(const void *s, int c, size_t n)
111 {
112 	const unsigned char *cp;
113 
114 	if (n != 0) {
115 		cp = (unsigned char *)s + n;
116 		do {
117 			if (*(--cp) == (unsigned char)c)
118 				return cp;
119 		} while (--n != 0);
120 	}
121 
122 	return NULL;
123 }
124 
125 extern const void * git__memmem(const void *haystack, size_t haystacklen,
126 				const void *needle, size_t needlelen);
127 
128 typedef int (*git__tsort_cmp)(const void *a, const void *b);
129 
130 extern void git__tsort(void **dst, size_t size, git__tsort_cmp cmp);
131 
132 typedef int (*git__sort_r_cmp)(const void *a, const void *b, void *payload);
133 
134 extern void git__tsort_r(
135 	void **dst, size_t size, git__sort_r_cmp cmp, void *payload);
136 
137 extern void git__qsort_r(
138 	void *els, size_t nel, size_t elsize, git__sort_r_cmp cmp, void *payload);
139 
140 /**
141  * @param position If non-NULL, this will be set to the position where the
142  * 		element is or would be inserted if not found.
143  * @return 0 if found; GIT_ENOTFOUND if not found
144  */
145 extern int git__bsearch(
146 	void **array,
147 	size_t array_len,
148 	const void *key,
149 	int (*compare)(const void *key, const void *element),
150 	size_t *position);
151 
152 extern int git__bsearch_r(
153 	void **array,
154 	size_t array_len,
155 	const void *key,
156 	int (*compare_r)(const void *key, const void *element, void *payload),
157 	void *payload,
158 	size_t *position);
159 
160 #define git__strcmp strcmp
161 #define git__strncmp strncmp
162 
163 extern int git__strcmp_cb(const void *a, const void *b);
164 extern int git__strcasecmp_cb(const void *a, const void *b);
165 
166 extern int git__strcasecmp(const char *a, const char *b);
167 extern int git__strncasecmp(const char *a, const char *b, size_t sz);
168 
169 extern int git__strcasesort_cmp(const char *a, const char *b);
170 
171 /*
172  * Compare some NUL-terminated `a` to a possibly non-NUL terminated
173  * `b` of length `b_len`; like `strncmp` but ensuring that
174  * `strlen(a) == b_len` as well.
175  */
git__strlcmp(const char * a,const char * b,size_t b_len)176 GIT_INLINE(int) git__strlcmp(const char *a, const char *b, size_t b_len)
177 {
178 	int cmp = strncmp(a, b, b_len);
179 	return cmp ? cmp : (int)a[b_len];
180 }
181 
182 typedef struct {
183 	git_atomic32 refcount;
184 	void *owner;
185 } git_refcount;
186 
187 typedef void (*git_refcount_freeptr)(void *r);
188 
189 #define GIT_REFCOUNT_INC(r) { \
190 	git_atomic32_inc(&(r)->rc.refcount);	\
191 }
192 
193 #define GIT_REFCOUNT_DEC(_r, do_free) { \
194 	git_refcount *r = &(_r)->rc; \
195 	int val = git_atomic32_dec(&r->refcount); \
196 	if (val <= 0 && r->owner == NULL) { do_free(_r); } \
197 }
198 
199 #define GIT_REFCOUNT_OWN(r, o) { \
200 	(void)git_atomic_swap((r)->rc.owner, o); \
201 }
202 
203 #define GIT_REFCOUNT_OWNER(r) git_atomic_load((r)->rc.owner)
204 
205 #define GIT_REFCOUNT_VAL(r) git_atomic32_get((r)->rc.refcount)
206 
207 
208 static signed char from_hex[] = {
209 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 00 */
210 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 */
211 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20 */
212  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 30 */
213 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 40 */
214 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 50 */
215 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 60 */
216 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 70 */
217 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80 */
218 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90 */
219 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a0 */
220 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* b0 */
221 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* c0 */
222 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* d0 */
223 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* e0 */
224 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* f0 */
225 };
226 
git__fromhex(char h)227 GIT_INLINE(int) git__fromhex(char h)
228 {
229 	return from_hex[(unsigned char) h];
230 }
231 
git__ishex(const char * str)232 GIT_INLINE(int) git__ishex(const char *str)
233 {
234 	unsigned i;
235 	for (i=0; str[i] != '\0'; i++)
236 		if (git__fromhex(str[i]) < 0)
237 			return 0;
238 	return 1;
239 }
240 
git__size_t_bitmask(size_t v)241 GIT_INLINE(size_t) git__size_t_bitmask(size_t v)
242 {
243 	v--;
244 	v |= v >> 1;
245 	v |= v >> 2;
246 	v |= v >> 4;
247 	v |= v >> 8;
248 	v |= v >> 16;
249 
250 	return v;
251 }
252 
git__size_t_powerof2(size_t v)253 GIT_INLINE(size_t) git__size_t_powerof2(size_t v)
254 {
255 	return git__size_t_bitmask(v) + 1;
256 }
257 
git__isupper(int c)258 GIT_INLINE(bool) git__isupper(int c)
259 {
260 	return (c >= 'A' && c <= 'Z');
261 }
262 
git__isalpha(int c)263 GIT_INLINE(bool) git__isalpha(int c)
264 {
265 	return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
266 }
267 
git__isdigit(int c)268 GIT_INLINE(bool) git__isdigit(int c)
269 {
270 	return (c >= '0' && c <= '9');
271 }
272 
git__isspace(int c)273 GIT_INLINE(bool) git__isspace(int c)
274 {
275 	return (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == '\v');
276 }
277 
git__isspace_nonlf(int c)278 GIT_INLINE(bool) git__isspace_nonlf(int c)
279 {
280 	return (c == ' ' || c == '\t' || c == '\f' || c == '\r' || c == '\v');
281 }
282 
git__iswildcard(int c)283 GIT_INLINE(bool) git__iswildcard(int c)
284 {
285 	return (c == '*' || c == '?' || c == '[');
286 }
287 
git__isxdigit(int c)288 GIT_INLINE(bool) git__isxdigit(int c)
289 {
290 	return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
291 }
292 
293 /*
294  * Parse a string value as a boolean, just like Core Git does.
295  *
296  * Valid values for true are: 'true', 'yes', 'on'
297  * Valid values for false are: 'false', 'no', 'off'
298  */
299 extern int git__parse_bool(int *out, const char *value);
300 
301 /*
302  * Parse a string into a value as a git_time_t.
303  *
304  * Sample valid input:
305  * - "yesterday"
306  * - "July 17, 2003"
307  * - "2003-7-17 08:23"
308  */
309 extern int git__date_parse(git_time_t *out, const char *date);
310 
311 /*
312  * Format a git_time as a RFC2822 string
313  *
314  * @param out buffer to store formatted date; a '\\0' terminator will automatically be added.
315  * @param len size of the buffer; should be atleast `GIT_DATE_RFC2822_SZ` in size;
316  * @param date the date to be formatted
317  * @return 0 if successful; -1 on error
318  */
319 extern int git__date_rfc2822_fmt(char *out, size_t len, const git_time *date);
320 
321 /*
322  * Unescapes a string in-place.
323  *
324  * Edge cases behavior:
325  * - "jackie\" -> "jacky\"
326  * - "chan\\" -> "chan\"
327  */
328 extern size_t git__unescape(char *str);
329 
330 /*
331  * Safely zero-out memory, making sure that the compiler
332  * doesn't optimize away the operation.
333  */
git__memzero(void * data,size_t size)334 GIT_INLINE(void) git__memzero(void *data, size_t size)
335 {
336 #ifdef _MSC_VER
337 	SecureZeroMemory((PVOID)data, size);
338 #else
339 	volatile uint8_t *scan = (volatile uint8_t *)data;
340 
341 	while (size--)
342 		*scan++ = 0x0;
343 #endif
344 }
345 
346 #ifdef GIT_WIN32
347 
git__timer(void)348 GIT_INLINE(double) git__timer(void)
349 {
350 	/* GetTickCount64 returns the number of milliseconds that have
351 	 * elapsed since the system was started. */
352 	return (double) GetTickCount64() / (double) 1000;
353 }
354 
355 #elif __APPLE__
356 
357 #include <mach/mach_time.h>
358 
git__timer(void)359 GIT_INLINE(double) git__timer(void)
360 {
361    uint64_t time = mach_absolute_time();
362    static double scaling_factor = 0;
363 
364    if (scaling_factor == 0) {
365        mach_timebase_info_data_t info;
366        (void)mach_timebase_info(&info);
367        scaling_factor = (double)info.numer / (double)info.denom;
368    }
369 
370    return (double)time * scaling_factor / 1.0E9;
371 }
372 
373 #elif defined(__amigaos4__)
374 
375 #include <proto/timer.h>
376 
git__timer(void)377 GIT_INLINE(double) git__timer(void)
378 {
379 	struct TimeVal tv;
380 	ITimer->GetUpTime(&tv);
381 	return (double)tv.Seconds + (double)tv.Microseconds / 1.0E6;
382 }
383 
384 #else
385 
386 #include <sys/time.h>
387 
git__timer(void)388 GIT_INLINE(double) git__timer(void)
389 {
390 	struct timeval tv;
391 
392 #ifdef CLOCK_MONOTONIC
393 	struct timespec tp;
394 	if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
395 		return (double) tp.tv_sec + (double) tp.tv_nsec / 1.0E9;
396 #endif
397 
398 	/* Fall back to using gettimeofday */
399 	gettimeofday(&tv, NULL);
400 	return (double)tv.tv_sec + (double)tv.tv_usec / 1.0E6;
401 }
402 
403 #endif
404 
405 extern int git__getenv(git_buf *out, const char *name);
406 
407 extern int git__online_cpus(void);
408 
git__noop(void)409 GIT_INLINE(int) git__noop(void) { return 0; }
410 
411 #include "alloc.h"
412 
413 #endif
414