http-walker: reduce O(n) ops with doubly-linked list
[git] / git-compat-util.h
1 #ifndef GIT_COMPAT_UTIL_H
2 #define GIT_COMPAT_UTIL_H
3
4 #define _FILE_OFFSET_BITS 64
5
6
7 /* Derived from Linux "Features Test Macro" header
8  * Convenience macros to test the versions of gcc (or
9  * a compatible compiler).
10  * Use them like this:
11  *  #if GIT_GNUC_PREREQ (2,8)
12  *   ... code requiring gcc 2.8 or later ...
13  *  #endif
14 */
15 #if defined(__GNUC__) && defined(__GNUC_MINOR__)
16 # define GIT_GNUC_PREREQ(maj, min) \
17         ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
18 #else
19  #define GIT_GNUC_PREREQ(maj, min) 0
20 #endif
21
22
23 #ifndef FLEX_ARRAY
24 /*
25  * See if our compiler is known to support flexible array members.
26  */
27 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && (!defined(__SUNPRO_C) || (__SUNPRO_C > 0x580))
28 # define FLEX_ARRAY /* empty */
29 #elif defined(__GNUC__)
30 # if (__GNUC__ >= 3)
31 #  define FLEX_ARRAY /* empty */
32 # else
33 #  define FLEX_ARRAY 0 /* older GNU extension */
34 # endif
35 #endif
36
37 /*
38  * Otherwise, default to safer but a bit wasteful traditional style
39  */
40 #ifndef FLEX_ARRAY
41 # define FLEX_ARRAY 1
42 #endif
43 #endif
44
45
46 /*
47  * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
48  * @cond: the compile-time condition which must be true.
49  *
50  * Your compile will fail if the condition isn't true, or can't be evaluated
51  * by the compiler.  This can be used in an expression: its value is "0".
52  *
53  * Example:
54  *      #define foo_to_char(foo)                                        \
55  *               ((char *)(foo)                                         \
56  *                + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
57  */
58 #define BUILD_ASSERT_OR_ZERO(cond) \
59         (sizeof(char [1 - 2*!(cond)]) - 1)
60
61 #if GIT_GNUC_PREREQ(3, 1)
62  /* &arr[0] degrades to a pointer: a different type from an array */
63 # define BARF_UNLESS_AN_ARRAY(arr)                                              \
64         BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
65                                                            __typeof__(&(arr)[0])))
66 #else
67 # define BARF_UNLESS_AN_ARRAY(arr) 0
68 #endif
69 /*
70  * ARRAY_SIZE - get the number of elements in a visible array
71  *  <at> x: the array whose size you want.
72  *
73  * This does not work on pointers, or arrays declared as [], or
74  * function parameters.  With correct compiler support, such usage
75  * will cause a build error (see the build_assert_or_zero macro).
76  */
77 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
78
79 #define bitsizeof(x)  (CHAR_BIT * sizeof(x))
80
81 #define maximum_signed_value_of_type(a) \
82     (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
83
84 #define maximum_unsigned_value_of_type(a) \
85     (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
86
87 /*
88  * Signed integer overflow is undefined in C, so here's a helper macro
89  * to detect if the sum of two integers will overflow.
90  *
91  * Requires: a >= 0, typeof(a) equals typeof(b)
92  */
93 #define signed_add_overflows(a, b) \
94     ((b) > maximum_signed_value_of_type(a) - (a))
95
96 #define unsigned_add_overflows(a, b) \
97     ((b) > maximum_unsigned_value_of_type(a) - (a))
98
99 /*
100  * Returns true if the multiplication of "a" and "b" will
101  * overflow. The types of "a" and "b" must match and must be unsigned.
102  * Note that this macro evaluates "a" twice!
103  */
104 #define unsigned_mult_overflows(a, b) \
105     ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
106
107 #ifdef __GNUC__
108 #define TYPEOF(x) (__typeof__(x))
109 #else
110 #define TYPEOF(x)
111 #endif
112
113 #define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
114 #define HAS_MULTI_BITS(i)  ((i) & ((i) - 1))  /* checks if an integer has more than 1 bit set */
115
116 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
117
118 /* Approximation of the length of the decimal representation of this type. */
119 #define decimal_length(x)       ((int)(sizeof(x) * 2.56 + 0.5) + 1)
120
121 #if defined(__sun__)
122  /*
123   * On Solaris, when _XOPEN_EXTENDED is set, its header file
124   * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
125   * setting to say we are XPG5 or XPG6.  Also on Solaris,
126   * XPG6 programs must be compiled with a c99 compiler, while
127   * non XPG6 programs must be compiled with a pre-c99 compiler.
128   */
129 # if __STDC_VERSION__ - 0 >= 199901L
130 # define _XOPEN_SOURCE 600
131 # else
132 # define _XOPEN_SOURCE 500
133 # endif
134 #elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
135       !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
136       !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
137       !defined(__CYGWIN__)
138 #define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
139 #define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
140 #endif
141 #define _ALL_SOURCE 1
142 #define _GNU_SOURCE 1
143 #define _BSD_SOURCE 1
144 #define _DEFAULT_SOURCE 1
145 #define _NETBSD_SOURCE 1
146 #define _SGI_SOURCE 1
147
148 #if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
149 # if defined (_MSC_VER) && !defined(_WIN32_WINNT)
150 #  define _WIN32_WINNT 0x0502
151 # endif
152 #define WIN32_LEAN_AND_MEAN  /* stops windows.h including winsock.h */
153 #include <winsock2.h>
154 #include <windows.h>
155 #define GIT_WINDOWS_NATIVE
156 #endif
157
158 #include <unistd.h>
159 #include <stdio.h>
160 #include <sys/stat.h>
161 #include <fcntl.h>
162 #include <stddef.h>
163 #include <stdlib.h>
164 #include <stdarg.h>
165 #include <string.h>
166 #ifdef HAVE_STRINGS_H
167 #include <strings.h> /* for strcasecmp() */
168 #endif
169 #include <errno.h>
170 #include <limits.h>
171 #ifdef NEEDS_SYS_PARAM_H
172 #include <sys/param.h>
173 #endif
174 #include <sys/types.h>
175 #include <dirent.h>
176 #include <sys/time.h>
177 #include <time.h>
178 #include <signal.h>
179 #include <assert.h>
180 #include <regex.h>
181 #include <utime.h>
182 #include <syslog.h>
183 #ifndef NO_SYS_POLL_H
184 #include <sys/poll.h>
185 #else
186 #include <poll.h>
187 #endif
188 #ifdef HAVE_BSD_SYSCTL
189 #include <sys/sysctl.h>
190 #endif
191
192 #if defined(__MINGW32__)
193 /* pull in Windows compatibility stuff */
194 #include "compat/mingw.h"
195 #elif defined(_MSC_VER)
196 #include "compat/msvc.h"
197 #else
198 #include <sys/utsname.h>
199 #include <sys/wait.h>
200 #include <sys/resource.h>
201 #include <sys/socket.h>
202 #include <sys/ioctl.h>
203 #include <termios.h>
204 #ifndef NO_SYS_SELECT_H
205 #include <sys/select.h>
206 #endif
207 #include <netinet/in.h>
208 #include <netinet/tcp.h>
209 #include <arpa/inet.h>
210 #include <netdb.h>
211 #include <pwd.h>
212 #include <sys/un.h>
213 #ifndef NO_INTTYPES_H
214 #include <inttypes.h>
215 #else
216 #include <stdint.h>
217 #endif
218 #ifdef NO_INTPTR_T
219 /*
220  * On I16LP32, ILP32 and LP64 "long" is the save bet, however
221  * on LLP86, IL33LLP64 and P64 it needs to be "long long",
222  * while on IP16 and IP16L32 it is "int" (resp. "short")
223  * Size needs to match (or exceed) 'sizeof(void *)'.
224  * We can't take "long long" here as not everybody has it.
225  */
226 typedef long intptr_t;
227 typedef unsigned long uintptr_t;
228 #endif
229 #undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
230 #include <grp.h>
231 #define _ALL_SOURCE 1
232 #endif
233
234 /* used on Mac OS X */
235 #ifdef PRECOMPOSE_UNICODE
236 #include "compat/precompose_utf8.h"
237 #else
238 #define precompose_str(in,i_nfd2nfc)
239 #define precompose_argv(c,v)
240 #define probe_utf8_pathname_composition()
241 #endif
242
243 #ifdef MKDIR_WO_TRAILING_SLASH
244 #define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
245 extern int compat_mkdir_wo_trailing_slash(const char*, mode_t);
246 #endif
247
248 #ifdef NO_STRUCT_ITIMERVAL
249 struct itimerval {
250         struct timeval it_interval;
251         struct timeval it_value;
252 };
253 #endif
254
255 #ifdef NO_SETITIMER
256 #define setitimer(which,value,ovalue)
257 #endif
258
259 #ifndef NO_LIBGEN_H
260 #include <libgen.h>
261 #else
262 #define basename gitbasename
263 extern char *gitbasename(char *);
264 #define dirname gitdirname
265 extern char *gitdirname(char *);
266 #endif
267
268 #ifndef NO_ICONV
269 #include <iconv.h>
270 #endif
271
272 #ifndef NO_OPENSSL
273 #ifdef __APPLE__
274 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
275 #include <AvailabilityMacros.h>
276 #undef DEPRECATED_ATTRIBUTE
277 #define DEPRECATED_ATTRIBUTE
278 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
279 #endif
280 #include <openssl/ssl.h>
281 #include <openssl/err.h>
282 #endif
283
284 /* On most systems <netdb.h> would have given us this, but
285  * not on some systems (e.g. z/OS).
286  */
287 #ifndef NI_MAXHOST
288 #define NI_MAXHOST 1025
289 #endif
290
291 #ifndef NI_MAXSERV
292 #define NI_MAXSERV 32
293 #endif
294
295 /* On most systems <limits.h> would have given us this, but
296  * not on some systems (e.g. GNU/Hurd).
297  */
298 #ifndef PATH_MAX
299 #define PATH_MAX 4096
300 #endif
301
302 #ifndef PRIuMAX
303 #define PRIuMAX "llu"
304 #endif
305
306 #ifndef SCNuMAX
307 #define SCNuMAX PRIuMAX
308 #endif
309
310 #ifndef PRIu32
311 #define PRIu32 "u"
312 #endif
313
314 #ifndef PRIx32
315 #define PRIx32 "x"
316 #endif
317
318 #ifndef PRIo32
319 #define PRIo32 "o"
320 #endif
321
322 #ifndef PATH_SEP
323 #define PATH_SEP ':'
324 #endif
325
326 #ifdef HAVE_PATHS_H
327 #include <paths.h>
328 #endif
329 #ifndef _PATH_DEFPATH
330 #define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
331 #endif
332
333 #ifndef has_dos_drive_prefix
334 static inline int git_has_dos_drive_prefix(const char *path)
335 {
336         return 0;
337 }
338 #define has_dos_drive_prefix git_has_dos_drive_prefix
339 #endif
340
341 #ifndef skip_dos_drive_prefix
342 static inline int git_skip_dos_drive_prefix(char **path)
343 {
344         return 0;
345 }
346 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
347 #endif
348
349 #ifndef is_dir_sep
350 static inline int git_is_dir_sep(int c)
351 {
352         return c == '/';
353 }
354 #define is_dir_sep git_is_dir_sep
355 #endif
356
357 #ifndef offset_1st_component
358 static inline int git_offset_1st_component(const char *path)
359 {
360         return is_dir_sep(path[0]);
361 }
362 #define offset_1st_component git_offset_1st_component
363 #endif
364
365 #ifndef find_last_dir_sep
366 static inline char *git_find_last_dir_sep(const char *path)
367 {
368         return strrchr(path, '/');
369 }
370 #define find_last_dir_sep git_find_last_dir_sep
371 #endif
372
373 #if defined(__HP_cc) && (__HP_cc >= 61000)
374 #define NORETURN __attribute__((noreturn))
375 #define NORETURN_PTR
376 #elif defined(__GNUC__) && !defined(NO_NORETURN)
377 #define NORETURN __attribute__((__noreturn__))
378 #define NORETURN_PTR __attribute__((__noreturn__))
379 #elif defined(_MSC_VER)
380 #define NORETURN __declspec(noreturn)
381 #define NORETURN_PTR
382 #else
383 #define NORETURN
384 #define NORETURN_PTR
385 #ifndef __GNUC__
386 #ifndef __attribute__
387 #define __attribute__(x)
388 #endif
389 #endif
390 #endif
391
392 /* The sentinel attribute is valid from gcc version 4.0 */
393 #if defined(__GNUC__) && (__GNUC__ >= 4)
394 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
395 #else
396 #define LAST_ARG_MUST_BE_NULL
397 #endif
398
399 #include "compat/bswap.h"
400
401 #include "wildmatch.h"
402
403 struct strbuf;
404
405 /* General helper functions */
406 extern void vreportf(const char *prefix, const char *err, va_list params);
407 extern NORETURN void usage(const char *err);
408 extern NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
409 extern NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
410 extern NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
411 extern int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
412 extern int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
413 extern void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
414 extern void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
415
416 #ifndef NO_OPENSSL
417 #ifdef APPLE_COMMON_CRYPTO
418 #include "compat/apple-common-crypto.h"
419 #else
420 #include <openssl/evp.h>
421 #include <openssl/hmac.h>
422 #endif /* APPLE_COMMON_CRYPTO */
423 #include <openssl/x509v3.h>
424 #endif /* NO_OPENSSL */
425
426 /*
427  * Let callers be aware of the constant return value; this can help
428  * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
429  * because some compilers may not support variadic macros. Since we're only
430  * trying to help gcc, anyway, it's OK; other compilers will fall back to
431  * using the function as usual.
432  */
433 #if defined(__GNUC__)
434 static inline int const_error(void)
435 {
436         return -1;
437 }
438 #define error(...) (error(__VA_ARGS__), const_error())
439 #endif
440
441 extern void set_die_routine(NORETURN_PTR void (*routine)(const char *err, va_list params));
442 extern void set_error_routine(void (*routine)(const char *err, va_list params));
443 extern void set_die_is_recursing_routine(int (*routine)(void));
444 extern void set_error_handle(FILE *);
445
446 extern int starts_with(const char *str, const char *prefix);
447
448 /*
449  * If the string "str" begins with the string found in "prefix", return 1.
450  * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
451  * the string right after the prefix).
452  *
453  * Otherwise, return 0 and leave "out" untouched.
454  *
455  * Examples:
456  *
457  *   [extract branch name, fail if not a branch]
458  *   if (!skip_prefix(ref, "refs/heads/", &branch)
459  *      return -1;
460  *
461  *   [skip prefix if present, otherwise use whole string]
462  *   skip_prefix(name, "refs/heads/", &name);
463  */
464 static inline int skip_prefix(const char *str, const char *prefix,
465                               const char **out)
466 {
467         do {
468                 if (!*prefix) {
469                         *out = str;
470                         return 1;
471                 }
472         } while (*str++ == *prefix++);
473         return 0;
474 }
475
476 /*
477  * If buf ends with suffix, return 1 and subtract the length of the suffix
478  * from *len. Otherwise, return 0 and leave *len untouched.
479  */
480 static inline int strip_suffix_mem(const char *buf, size_t *len,
481                                    const char *suffix)
482 {
483         size_t suflen = strlen(suffix);
484         if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
485                 return 0;
486         *len -= suflen;
487         return 1;
488 }
489
490 /*
491  * If str ends with suffix, return 1 and set *len to the size of the string
492  * without the suffix. Otherwise, return 0 and set *len to the size of the
493  * string.
494  *
495  * Note that we do _not_ NUL-terminate str to the new length.
496  */
497 static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
498 {
499         *len = strlen(str);
500         return strip_suffix_mem(str, len, suffix);
501 }
502
503 static inline int ends_with(const char *str, const char *suffix)
504 {
505         size_t len;
506         return strip_suffix(str, suffix, &len);
507 }
508
509 #if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
510
511 #ifndef PROT_READ
512 #define PROT_READ 1
513 #define PROT_WRITE 2
514 #define MAP_PRIVATE 1
515 #endif
516
517 #define mmap git_mmap
518 #define munmap git_munmap
519 extern void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
520 extern int git_munmap(void *start, size_t length);
521
522 #else /* NO_MMAP || USE_WIN32_MMAP */
523
524 #include <sys/mman.h>
525
526 #endif /* NO_MMAP || USE_WIN32_MMAP */
527
528 #ifdef NO_MMAP
529
530 /* This value must be multiple of (pagesize * 2) */
531 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
532
533 #else /* NO_MMAP */
534
535 /* This value must be multiple of (pagesize * 2) */
536 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
537         (sizeof(void*) >= 8 \
538                 ?  1 * 1024 * 1024 * 1024 \
539                 : 32 * 1024 * 1024)
540
541 #endif /* NO_MMAP */
542
543 #ifndef MAP_FAILED
544 #define MAP_FAILED ((void *)-1)
545 #endif
546
547 #ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
548 #define on_disk_bytes(st) ((st).st_size)
549 #else
550 #define on_disk_bytes(st) ((st).st_blocks * 512)
551 #endif
552
553 #ifdef NEEDS_MODE_TRANSLATION
554 #undef S_IFMT
555 #undef S_IFREG
556 #undef S_IFDIR
557 #undef S_IFLNK
558 #undef S_IFBLK
559 #undef S_IFCHR
560 #undef S_IFIFO
561 #undef S_IFSOCK
562 #define S_IFMT   0170000
563 #define S_IFREG  0100000
564 #define S_IFDIR  0040000
565 #define S_IFLNK  0120000
566 #define S_IFBLK  0060000
567 #define S_IFCHR  0020000
568 #define S_IFIFO  0010000
569 #define S_IFSOCK 0140000
570 #ifdef stat
571 #undef stat
572 #endif
573 #define stat(path, buf) git_stat(path, buf)
574 extern int git_stat(const char *, struct stat *);
575 #ifdef fstat
576 #undef fstat
577 #endif
578 #define fstat(fd, buf) git_fstat(fd, buf)
579 extern int git_fstat(int, struct stat *);
580 #ifdef lstat
581 #undef lstat
582 #endif
583 #define lstat(path, buf) git_lstat(path, buf)
584 extern int git_lstat(const char *, struct stat *);
585 #endif
586
587 #define DEFAULT_PACKED_GIT_LIMIT \
588         ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? 8192 : 256))
589
590 #ifdef NO_PREAD
591 #define pread git_pread
592 extern ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
593 #endif
594 /*
595  * Forward decl that will remind us if its twin in cache.h changes.
596  * This function is used in compat/pread.c.  But we can't include
597  * cache.h there.
598  */
599 extern ssize_t read_in_full(int fd, void *buf, size_t count);
600
601 #ifdef NO_SETENV
602 #define setenv gitsetenv
603 extern int gitsetenv(const char *, const char *, int);
604 #endif
605
606 #ifdef NO_MKDTEMP
607 #define mkdtemp gitmkdtemp
608 extern char *gitmkdtemp(char *);
609 #endif
610
611 #ifdef NO_MKSTEMPS
612 #define mkstemps gitmkstemps
613 extern int gitmkstemps(char *, int);
614 #endif
615
616 #ifdef NO_UNSETENV
617 #define unsetenv gitunsetenv
618 extern void gitunsetenv(const char *);
619 #endif
620
621 #ifdef NO_STRCASESTR
622 #define strcasestr gitstrcasestr
623 extern char *gitstrcasestr(const char *haystack, const char *needle);
624 #endif
625
626 #ifdef NO_STRLCPY
627 #define strlcpy gitstrlcpy
628 extern size_t gitstrlcpy(char *, const char *, size_t);
629 #endif
630
631 #ifdef NO_STRTOUMAX
632 #define strtoumax gitstrtoumax
633 extern uintmax_t gitstrtoumax(const char *, char **, int);
634 #define strtoimax gitstrtoimax
635 extern intmax_t gitstrtoimax(const char *, char **, int);
636 #endif
637
638 #ifdef NO_HSTRERROR
639 #define hstrerror githstrerror
640 extern const char *githstrerror(int herror);
641 #endif
642
643 #ifdef NO_MEMMEM
644 #define memmem gitmemmem
645 void *gitmemmem(const void *haystack, size_t haystacklen,
646                 const void *needle, size_t needlelen);
647 #endif
648
649 #ifdef NO_GETPAGESIZE
650 #define getpagesize() sysconf(_SC_PAGESIZE)
651 #endif
652
653 #ifdef FREAD_READS_DIRECTORIES
654 #ifdef fopen
655 #undef fopen
656 #endif
657 #define fopen(a,b) git_fopen(a,b)
658 extern FILE *git_fopen(const char*, const char*);
659 #endif
660
661 #ifdef SNPRINTF_RETURNS_BOGUS
662 #ifdef snprintf
663 #undef snprintf
664 #endif
665 #define snprintf git_snprintf
666 extern int git_snprintf(char *str, size_t maxsize,
667                         const char *format, ...);
668 #ifdef vsnprintf
669 #undef vsnprintf
670 #endif
671 #define vsnprintf git_vsnprintf
672 extern int git_vsnprintf(char *str, size_t maxsize,
673                          const char *format, va_list ap);
674 #endif
675
676 #ifdef __GLIBC_PREREQ
677 #if __GLIBC_PREREQ(2, 1)
678 #define HAVE_STRCHRNUL
679 #endif
680 #endif
681
682 #ifndef HAVE_STRCHRNUL
683 #define strchrnul gitstrchrnul
684 static inline char *gitstrchrnul(const char *s, int c)
685 {
686         while (*s && *s != c)
687                 s++;
688         return (char *)s;
689 }
690 #endif
691
692 #ifdef NO_INET_PTON
693 int inet_pton(int af, const char *src, void *dst);
694 #endif
695
696 #ifdef NO_INET_NTOP
697 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
698 #endif
699
700 #ifdef NO_PTHREADS
701 #define atexit git_atexit
702 extern int git_atexit(void (*handler)(void));
703 #endif
704
705 extern void release_pack_memory(size_t);
706
707 typedef void (*try_to_free_t)(size_t);
708 extern try_to_free_t set_try_to_free_routine(try_to_free_t);
709
710 static inline size_t st_add(size_t a, size_t b)
711 {
712         if (unsigned_add_overflows(a, b))
713                 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
714                     (uintmax_t)a, (uintmax_t)b);
715         return a + b;
716 }
717 #define st_add3(a,b,c)   st_add(st_add((a),(b)),(c))
718 #define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
719
720 static inline size_t st_mult(size_t a, size_t b)
721 {
722         if (unsigned_mult_overflows(a, b))
723                 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
724                     (uintmax_t)a, (uintmax_t)b);
725         return a * b;
726 }
727
728 static inline size_t st_sub(size_t a, size_t b)
729 {
730         if (a < b)
731                 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
732                     (uintmax_t)a, (uintmax_t)b);
733         return a - b;
734 }
735
736 #ifdef HAVE_ALLOCA_H
737 # include <alloca.h>
738 # define xalloca(size)      (alloca(size))
739 # define xalloca_free(p)    do {} while (0)
740 #else
741 # define xalloca(size)      (xmalloc(size))
742 # define xalloca_free(p)    (free(p))
743 #endif
744 extern char *xstrdup(const char *str);
745 extern void *xmalloc(size_t size);
746 extern void *xmallocz(size_t size);
747 extern void *xmallocz_gently(size_t size);
748 extern void *xmemdupz(const void *data, size_t len);
749 extern char *xstrndup(const char *str, size_t len);
750 extern void *xrealloc(void *ptr, size_t size);
751 extern void *xcalloc(size_t nmemb, size_t size);
752 extern void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
753 extern void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
754 extern int xopen(const char *path, int flags, ...);
755 extern ssize_t xread(int fd, void *buf, size_t len);
756 extern ssize_t xwrite(int fd, const void *buf, size_t len);
757 extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
758 extern int xdup(int fd);
759 extern FILE *xfopen(const char *path, const char *mode);
760 extern FILE *xfdopen(int fd, const char *mode);
761 extern int xmkstemp(char *template);
762 extern int xmkstemp_mode(char *template, int mode);
763 extern int odb_mkstemp(char *template, size_t limit, const char *pattern);
764 extern int odb_pack_keep(char *name, size_t namesz, const unsigned char *sha1);
765 extern char *xgetcwd(void);
766 extern FILE *fopen_for_writing(const char *path);
767
768 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
769 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
770
771 /*
772  * These functions help you allocate structs with flex arrays, and copy
773  * the data directly into the array. For example, if you had:
774  *
775  *   struct foo {
776  *     int bar;
777  *     char name[FLEX_ARRAY];
778  *   };
779  *
780  * you can do:
781  *
782  *   struct foo *f;
783  *   FLEX_ALLOC_MEM(f, name, src, len);
784  *
785  * to allocate a "foo" with the contents of "src" in the "name" field.
786  * The resulting struct is automatically zero'd, and the flex-array field
787  * is NUL-terminated (whether the incoming src buffer was or not).
788  *
789  * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
790  * but do want to store a pointer to some extra data in the same allocated
791  * block. For example, if you have:
792  *
793  *   struct foo {
794  *     char *name;
795  *     int bar;
796  *   };
797  *
798  * you can do:
799  *
800  *   struct foo *f;
801  *   FLEX_ALLOC_STR(f, name, src);
802  *
803  * and "name" will point to a block of memory after the struct, which will be
804  * freed along with the struct (but the pointer can be repointed anywhere).
805  *
806  * The *_STR variants accept a string parameter rather than a ptr/len
807  * combination.
808  *
809  * Note that these macros will evaluate the first parameter multiple
810  * times, and it must be assignable as an lvalue.
811  */
812 #define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
813         (x) = NULL; /* silence -Wuninitialized for offset calculation */ \
814         (x) = xalloc_flex(sizeof(*(x)), (char *)(&((x)->flexname)) - (char *)(x), (buf), (len)); \
815 } while (0)
816 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
817         (x) = xalloc_flex(sizeof(*(x)), sizeof(*(x)), (buf), (len)); \
818         (x)->ptrname = (void *)((x)+1); \
819 } while(0)
820 #define FLEX_ALLOC_STR(x, flexname, str) \
821         FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
822 #define FLEXPTR_ALLOC_STR(x, ptrname, str) \
823         FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
824
825 static inline void *xalloc_flex(size_t base_len, size_t offset,
826                                 const void *src, size_t src_len)
827 {
828         unsigned char *ret = xcalloc(1, st_add3(base_len, src_len, 1));
829         memcpy(ret + offset, src, src_len);
830         return ret;
831 }
832
833 static inline char *xstrdup_or_null(const char *str)
834 {
835         return str ? xstrdup(str) : NULL;
836 }
837
838 static inline size_t xsize_t(off_t len)
839 {
840         if (len > (size_t) len)
841                 die("Cannot handle files this big");
842         return (size_t)len;
843 }
844
845 __attribute__((format (printf, 3, 4)))
846 extern int xsnprintf(char *dst, size_t max, const char *fmt, ...);
847
848 /* in ctype.c, for kwset users */
849 extern const unsigned char tolower_trans_tbl[256];
850
851 /* Sane ctype - no locale, and works with signed chars */
852 #undef isascii
853 #undef isspace
854 #undef isdigit
855 #undef isalpha
856 #undef isalnum
857 #undef isprint
858 #undef islower
859 #undef isupper
860 #undef tolower
861 #undef toupper
862 #undef iscntrl
863 #undef ispunct
864 #undef isxdigit
865
866 extern const unsigned char sane_ctype[256];
867 #define GIT_SPACE 0x01
868 #define GIT_DIGIT 0x02
869 #define GIT_ALPHA 0x04
870 #define GIT_GLOB_SPECIAL 0x08
871 #define GIT_REGEX_SPECIAL 0x10
872 #define GIT_PATHSPEC_MAGIC 0x20
873 #define GIT_CNTRL 0x40
874 #define GIT_PUNCT 0x80
875 #define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
876 #define isascii(x) (((x) & ~0x7f) == 0)
877 #define isspace(x) sane_istest(x,GIT_SPACE)
878 #define isdigit(x) sane_istest(x,GIT_DIGIT)
879 #define isalpha(x) sane_istest(x,GIT_ALPHA)
880 #define isalnum(x) sane_istest(x,GIT_ALPHA | GIT_DIGIT)
881 #define isprint(x) ((x) >= 0x20 && (x) <= 0x7e)
882 #define islower(x) sane_iscase(x, 1)
883 #define isupper(x) sane_iscase(x, 0)
884 #define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
885 #define is_regex_special(x) sane_istest(x,GIT_GLOB_SPECIAL | GIT_REGEX_SPECIAL)
886 #define iscntrl(x) (sane_istest(x,GIT_CNTRL))
887 #define ispunct(x) sane_istest(x, GIT_PUNCT | GIT_REGEX_SPECIAL | \
888                 GIT_GLOB_SPECIAL | GIT_PATHSPEC_MAGIC)
889 #define isxdigit(x) (hexval_table[(unsigned char)(x)] != -1)
890 #define tolower(x) sane_case((unsigned char)(x), 0x20)
891 #define toupper(x) sane_case((unsigned char)(x), 0)
892 #define is_pathspec_magic(x) sane_istest(x,GIT_PATHSPEC_MAGIC)
893
894 static inline int sane_case(int x, int high)
895 {
896         if (sane_istest(x, GIT_ALPHA))
897                 x = (x & ~0x20) | high;
898         return x;
899 }
900
901 static inline int sane_iscase(int x, int is_lower)
902 {
903         if (!sane_istest(x, GIT_ALPHA))
904                 return 0;
905
906         if (is_lower)
907                 return (x & 0x20) != 0;
908         else
909                 return (x & 0x20) == 0;
910 }
911
912 static inline int strtoul_ui(char const *s, int base, unsigned int *result)
913 {
914         unsigned long ul;
915         char *p;
916
917         errno = 0;
918         /* negative values would be accepted by strtoul */
919         if (strchr(s, '-'))
920                 return -1;
921         ul = strtoul(s, &p, base);
922         if (errno || *p || p == s || (unsigned int) ul != ul)
923                 return -1;
924         *result = ul;
925         return 0;
926 }
927
928 static inline int strtol_i(char const *s, int base, int *result)
929 {
930         long ul;
931         char *p;
932
933         errno = 0;
934         ul = strtol(s, &p, base);
935         if (errno || *p || p == s || (int) ul != ul)
936                 return -1;
937         *result = ul;
938         return 0;
939 }
940
941 #ifdef INTERNAL_QSORT
942 void git_qsort(void *base, size_t nmemb, size_t size,
943                int(*compar)(const void *, const void *));
944 #define qsort git_qsort
945 #endif
946
947 #ifndef DIR_HAS_BSD_GROUP_SEMANTICS
948 # define FORCE_DIR_SET_GID S_ISGID
949 #else
950 # define FORCE_DIR_SET_GID 0
951 #endif
952
953 #ifdef NO_NSEC
954 #undef USE_NSEC
955 #define ST_CTIME_NSEC(st) 0
956 #define ST_MTIME_NSEC(st) 0
957 #else
958 #ifdef USE_ST_TIMESPEC
959 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
960 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
961 #else
962 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
963 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
964 #endif
965 #endif
966
967 #ifdef UNRELIABLE_FSTAT
968 #define fstat_is_reliable() 0
969 #else
970 #define fstat_is_reliable() 1
971 #endif
972
973 #ifndef va_copy
974 /*
975  * Since an obvious implementation of va_list would be to make it a
976  * pointer into the stack frame, a simple assignment will work on
977  * many systems.  But let's try to be more portable.
978  */
979 #ifdef __va_copy
980 #define va_copy(dst, src) __va_copy(dst, src)
981 #else
982 #define va_copy(dst, src) ((dst) = (src))
983 #endif
984 #endif
985
986 #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__C99_MACRO_WITH_VA_ARGS)
987 #define HAVE_VARIADIC_MACROS 1
988 #endif
989
990 /*
991  * Preserves errno, prints a message, but gives no warning for ENOENT.
992  * Returns 0 on success, which includes trying to unlink an object that does
993  * not exist.
994  */
995 int unlink_or_warn(const char *path);
996  /*
997   * Tries to unlink file.  Returns 0 if unlink succeeded
998   * or the file already didn't exist.  Returns -1 and
999   * appends a message to err suitable for
1000   * 'error("%s", err->buf)' on error.
1001   */
1002 int unlink_or_msg(const char *file, struct strbuf *err);
1003 /*
1004  * Preserves errno, prints a message, but gives no warning for ENOENT.
1005  * Returns 0 on success, which includes trying to remove a directory that does
1006  * not exist.
1007  */
1008 int rmdir_or_warn(const char *path);
1009 /*
1010  * Calls the correct function out of {unlink,rmdir}_or_warn based on
1011  * the supplied file mode.
1012  */
1013 int remove_or_warn(unsigned int mode, const char *path);
1014
1015 /*
1016  * Call access(2), but warn for any error except "missing file"
1017  * (ENOENT or ENOTDIR).
1018  */
1019 #define ACCESS_EACCES_OK (1U << 0)
1020 int access_or_warn(const char *path, int mode, unsigned flag);
1021 int access_or_die(const char *path, int mode, unsigned flag);
1022
1023 /* Warn on an inaccessible file that ought to be accessible */
1024 void warn_on_inaccessible(const char *path);
1025
1026 #ifdef GMTIME_UNRELIABLE_ERRORS
1027 struct tm *git_gmtime(const time_t *);
1028 struct tm *git_gmtime_r(const time_t *, struct tm *);
1029 #define gmtime git_gmtime
1030 #define gmtime_r git_gmtime_r
1031 #endif
1032
1033 #if !defined(USE_PARENS_AROUND_GETTEXT_N) && defined(__GNUC__)
1034 #define USE_PARENS_AROUND_GETTEXT_N 1
1035 #endif
1036
1037 #ifndef SHELL_PATH
1038 # define SHELL_PATH "/bin/sh"
1039 #endif
1040
1041 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
1042 #define flockfile(fh)
1043 #define funlockfile(fh)
1044 #define getc_unlocked(fh) getc(fh)
1045 #endif
1046
1047 #endif