]> git.ipfire.org Git - thirdparty/git.git/blame - git-compat-util.h
wrapper: use a CSPRNG to generate random file names
[thirdparty/git.git] / git-compat-util.h
CommitLineData
4050c0df
JH
1#ifndef GIT_COMPAT_UTIL_H
2#define GIT_COMPAT_UTIL_H
3
7bc341e2 4#if __STDC_VERSION__ - 0 < 199901L
5/*
6 * Git is in a testing period for mandatory C99 support in the compiler. If
7 * your compiler is reasonably recent, you can try to enable C99 support (or,
8 * for MSVC, C11 support). If you encounter a problem and can't enable C99
9 * support with your compiler (such as with "-std=gnu99") and don't have access
10 * to one with this support, such as GCC or Clang, you can remove this #if
11 * directive, but please report the details of your system to
12 * git@vger.kernel.org.
13 */
14#error "Required C99 support is in a test phase. Please see git-compat-util.h for more details."
15#endif
16
556702f8
JH
17#ifdef USE_MSVC_CRTDBG
18/*
19 * For these to work they must appear very early in each
20 * file -- before most of the standard header files.
21 */
22#include <stdlib.h>
23#include <crtdbg.h>
24#endif
25
b97e9116
MW
26#define _FILE_OFFSET_BITS 64
27
89c855ed
EP
28
29/* Derived from Linux "Features Test Macro" header
30 * Convenience macros to test the versions of gcc (or
31 * a compatible compiler).
32 * Use them like this:
33 * #if GIT_GNUC_PREREQ (2,8)
34 * ... code requiring gcc 2.8 or later ...
35 * #endif
36*/
37#if defined(__GNUC__) && defined(__GNUC_MINOR__)
38# define GIT_GNUC_PREREQ(maj, min) \
39 ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
40#else
41 #define GIT_GNUC_PREREQ(maj, min) 0
42#endif
43
44
8f1d2e6f 45#ifndef FLEX_ARRAY
8e973991
JH
46/*
47 * See if our compiler is known to support flexible array members.
48 */
203ee91f 49#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && (!defined(__SUNPRO_C) || (__SUNPRO_C > 0x580))
8e973991
JH
50# define FLEX_ARRAY /* empty */
51#elif defined(__GNUC__)
52# if (__GNUC__ >= 3)
53# define FLEX_ARRAY /* empty */
54# else
55# define FLEX_ARRAY 0 /* older GNU extension */
56# endif
57#endif
58
59/*
60 * Otherwise, default to safer but a bit wasteful traditional style
61 */
62#ifndef FLEX_ARRAY
63# define FLEX_ARRAY 1
8f1d2e6f
JH
64#endif
65#endif
66
89c855ed
EP
67
68/*
69 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
70 * @cond: the compile-time condition which must be true.
71 *
72 * Your compile will fail if the condition isn't true, or can't be evaluated
73 * by the compiler. This can be used in an expression: its value is "0".
74 *
75 * Example:
76 * #define foo_to_char(foo) \
77 * ((char *)(foo) \
78 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
79 */
80#define BUILD_ASSERT_OR_ZERO(cond) \
81 (sizeof(char [1 - 2*!(cond)]) - 1)
82
e2c6f7cd 83#if GIT_GNUC_PREREQ(3, 1)
89c855ed
EP
84 /* &arr[0] degrades to a pointer: a different type from an array */
85# define BARF_UNLESS_AN_ARRAY(arr) \
86 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
87 __typeof__(&(arr)[0])))
e2c6f7cd
CB
88#else
89# define BARF_UNLESS_AN_ARRAY(arr) 0
89c855ed
EP
90#endif
91/*
92 * ARRAY_SIZE - get the number of elements in a visible array
68b69211 93 * @x: the array whose size you want.
89c855ed
EP
94 *
95 * This does not work on pointers, or arrays declared as [], or
96 * function parameters. With correct compiler support, such usage
97 * will cause a build error (see the build_assert_or_zero macro).
98 */
99#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
100
f630cfda 101#define bitsizeof(x) (CHAR_BIT * sizeof(x))
b4f2a6ac 102
c03c8315
EFL
103#define maximum_signed_value_of_type(a) \
104 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
105
1368f650
JN
106#define maximum_unsigned_value_of_type(a) \
107 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
108
c03c8315
EFL
109/*
110 * Signed integer overflow is undefined in C, so here's a helper macro
111 * to detect if the sum of two integers will overflow.
112 *
113 * Requires: a >= 0, typeof(a) equals typeof(b)
114 */
115#define signed_add_overflows(a, b) \
116 ((b) > maximum_signed_value_of_type(a) - (a))
117
1368f650
JN
118#define unsigned_add_overflows(a, b) \
119 ((b) > maximum_unsigned_value_of_type(a) - (a))
120
320d0b49
JK
121/*
122 * Returns true if the multiplication of "a" and "b" will
123 * overflow. The types of "a" and "b" must match and must be unsigned.
124 * Note that this macro evaluates "a" twice!
125 */
126#define unsigned_mult_overflows(a, b) \
127 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
128
e2ffeae3
JS
129/*
130 * Returns true if the left shift of "a" by "shift" bits will
131 * overflow. The type of "a" must be unsigned.
132 */
133#define unsigned_left_shift_overflows(a, shift) \
134 ((shift) < bitsizeof(a) && \
135 (a) > maximum_unsigned_value_of_type(a) >> (shift))
136
8723f216
NP
137#ifdef __GNUC__
138#define TYPEOF(x) (__typeof__(x))
139#else
140#define TYPEOF(x)
141#endif
142
f630cfda 143#define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
db7244bd 144#define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
8723f216 145
98cb6f30
PH
146#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
147
cf606e3d
AW
148/* Approximation of the length of the decimal representation of this type. */
149#define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
150
9e12400d
CMAB
151#ifdef __MINGW64__
152#define _POSIX_C_SOURCE 1
153#elif defined(__sun__)
4cb18a49
BC
154 /*
155 * On Solaris, when _XOPEN_EXTENDED is set, its header file
156 * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
157 * setting to say we are XPG5 or XPG6. Also on Solaris,
158 * XPG6 programs must be compiled with a c99 compiler, while
159 * non XPG6 programs must be compiled with a pre-c99 compiler.
160 */
161# if __STDC_VERSION__ - 0 >= 199901L
162# define _XOPEN_SOURCE 600
163# else
164# define _XOPEN_SOURCE 500
165# endif
6555b196 166#elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
6c109904 167 !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
3a0a3a89
RJ
168 !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
169 !defined(__CYGWIN__)
85023577
JH
170#define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
171#define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
c902c9a6 172#endif
fb952206
JR
173#define _ALL_SOURCE 1
174#define _GNU_SOURCE 1
175#define _BSD_SOURCE 1
f978a99f 176#define _DEFAULT_SOURCE 1
9a695fbf 177#define _NETBSD_SOURCE 1
9398b859 178#define _SGI_SOURCE 1
85023577 179
380395d0 180#if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
3571e78a 181# if !defined(_WIN32_WINNT)
2939a1f7 182# define _WIN32_WINNT 0x0600
41f29991 183# endif
435bdf8c
MSO
184#define WIN32_LEAN_AND_MEAN /* stops windows.h including winsock.h */
185#include <winsock2.h>
bb390b1f
CMAB
186#ifndef NO_UNIX_SOCKETS
187#include <afunix.h>
188#endif
435bdf8c 189#include <windows.h>
380395d0 190#define GIT_WINDOWS_NATIVE
05cd988d 191#ifdef HAVE_RTLGENRANDOM
192/* This is required to get access to RtlGenRandom. */
193#define SystemFunction036 NTAPI SystemFunction036
194#include <NTSecAPI.h>
195#undef SystemFunction036
196#endif
435bdf8c
MSO
197#endif
198
4050c0df
JH
199#include <unistd.h>
200#include <stdio.h>
201#include <sys/stat.h>
202#include <fcntl.h>
203#include <stddef.h>
204#include <stdlib.h>
205#include <stdarg.h>
206#include <string.h>
b3e103da 207#ifdef HAVE_STRINGS_H
6c109904
JS
208#include <strings.h> /* for strcasecmp() */
209#endif
4050c0df
JH
210#include <errno.h>
211#include <limits.h>
b2d05e06 212#ifdef NEEDS_SYS_PARAM_H
4050c0df 213#include <sys/param.h>
6ede7205 214#endif
4050c0df
JH
215#include <sys/types.h>
216#include <dirent.h>
85023577
JH
217#include <sys/time.h>
218#include <time.h>
219#include <signal.h>
f4626df5
JS
220#include <assert.h>
221#include <regex.h>
222#include <utime.h>
088d8802 223#include <syslog.h>
2648ccc2
ĐTCD
224#if !defined(NO_POLL_H)
225#include <poll.h>
226#elif !defined(NO_SYS_POLL_H)
fdc12114 227#include <sys/poll.h>
2844923d 228#else
2648ccc2 229/* Pull the compat stuff */
2844923d
MD
230#include <poll.h>
231#endif
9529080d
KM
232#ifdef HAVE_BSD_SYSCTL
233#include <sys/sysctl.h>
234#endif
2f0aaaf9 235
496f2569 236#if defined(__CYGWIN__)
1cadad6f 237#include "compat/win32/path-utils.h"
496f2569 238#endif
cfc755d3
VR
239#if defined(__MINGW32__)
240/* pull in Windows compatibility stuff */
1cadad6f 241#include "compat/win32/path-utils.h"
cfc755d3
VR
242#include "compat/mingw.h"
243#elif defined(_MSC_VER)
22c3634c 244#include "compat/win32/path-utils.h"
cfc755d3
VR
245#include "compat/msvc.h"
246#else
1e8fef60 247#include <sys/utsname.h>
f4626df5 248#include <sys/wait.h>
ebae9ff9 249#include <sys/resource.h>
85023577 250#include <sys/socket.h>
80bbe72b 251#include <sys/ioctl.h>
eb80042c 252#include <termios.h>
2600973f 253#ifndef NO_SYS_SELECT_H
80bbe72b 254#include <sys/select.h>
2600973f 255#endif
85023577
JH
256#include <netinet/in.h>
257#include <netinet/tcp.h>
258#include <arpa/inet.h>
259#include <netdb.h>
260#include <pwd.h>
e2770979 261#include <sys/un.h>
2844923d 262#ifndef NO_INTTYPES_H
007e2ba6 263#include <inttypes.h>
2844923d
MD
264#else
265#include <stdint.h>
266#endif
05cd988d 267#ifdef HAVE_ARC4RANDOM_LIBBSD
268#include <bsd/stdlib.h>
269#endif
270#ifdef HAVE_GETRANDOM
271#include <sys/random.h>
272#endif
6c109904
JS
273#ifdef NO_INTPTR_T
274/*
c70e1b04 275 * On I16LP32, ILP32 and LP64 "long" is the safe bet, however
6c109904
JS
276 * on LLP86, IL33LLP64 and P64 it needs to be "long long",
277 * while on IP16 and IP16L32 it is "int" (resp. "short")
278 * Size needs to match (or exceed) 'sizeof(void *)'.
279 * We can't take "long long" here as not everybody has it.
280 */
281typedef long intptr_t;
282typedef unsigned long uintptr_t;
283#endif
fb952206 284#undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
85023577 285#include <grp.h>
fb952206 286#define _ALL_SOURCE 1
41b20017 287#endif
85023577 288
76759c7d
TB
289/* used on Mac OS X */
290#ifdef PRECOMPOSE_UNICODE
291#include "compat/precompose_utf8.h"
292#else
5c327502 293static inline const char *precompose_argv_prefix(int argc, const char **argv, const char *prefix)
15b52a44 294{
5c327502 295 return prefix;
15b52a44 296}
5020774a
TB
297static inline const char *precompose_string_if_needed(const char *in)
298{
299 return in;
300}
301
fdf72966 302#define probe_utf8_pathname_composition()
76759c7d
TB
303#endif
304
0539ecfd
JS
305#ifdef MKDIR_WO_TRAILING_SLASH
306#define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
55454427 307int compat_mkdir_wo_trailing_slash(const char*, mode_t);
0539ecfd
JS
308#endif
309
7f9e848c
JS
310#ifdef NO_STRUCT_ITIMERVAL
311struct itimerval {
312 struct timeval it_interval;
313 struct timeval it_value;
981ff520 314};
7f9e848c
JS
315#endif
316
317#ifdef NO_SETITIMER
15b52a44 318static inline int setitimer(int which, const struct itimerval *value, struct itimerval *newvalue) {
14639a47 319 return 0; /* pretend success */
15b52a44 320}
7f9e848c
JS
321#endif
322
e1c06886
DA
323#ifndef NO_LIBGEN_H
324#include <libgen.h>
325#else
326#define basename gitbasename
55454427 327char *gitbasename(char *);
824682ab 328#define dirname gitdirname
55454427 329char *gitdirname(char *);
e1c06886
DA
330#endif
331
85023577
JH
332#ifndef NO_ICONV
333#include <iconv.h>
334#endif
4050c0df 335
684ec6c6 336#ifndef NO_OPENSSL
88c03eb5 337#ifdef __APPLE__
b195aa00 338#define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
88c03eb5
KM
339#include <AvailabilityMacros.h>
340#undef DEPRECATED_ATTRIBUTE
341#define DEPRECATED_ATTRIBUTE
342#undef __AVAILABILITY_MACROS_USES_AVAILABILITY
343#endif
684ec6c6
RS
344#include <openssl/ssl.h>
345#include <openssl/err.h>
346#endif
347
9806f5a7
NTND
348#ifdef HAVE_SYSINFO
349# include <sys/sysinfo.h>
350#endif
351
3b130ade
DM
352/* On most systems <netdb.h> would have given us this, but
353 * not on some systems (e.g. z/OS).
354 */
355#ifndef NI_MAXHOST
356#define NI_MAXHOST 1025
357#endif
358
359#ifndef NI_MAXSERV
360#define NI_MAXSERV 32
361#endif
362
d0c2449f
JH
363/* On most systems <limits.h> would have given us this, but
364 * not on some systems (e.g. GNU/Hurd).
365 */
366#ifndef PATH_MAX
367#define PATH_MAX 4096
368#endif
369
28f4aee3
JS
370typedef uintmax_t timestamp_t;
371#define PRItime PRIuMAX
372#define parse_timestamp strtoumax
373#define TIME_MAX UINTMAX_MAX
2e09c012 374#define TIME_MIN 0
1aeb7e75 375
80ba074f
JS
376#ifndef PATH_SEP
377#define PATH_SEP ':'
378#endif
379
cb6a22c0
CW
380#ifdef HAVE_PATHS_H
381#include <paths.h>
382#endif
383#ifndef _PATH_DEFPATH
384#define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
385#endif
386
70fc5793
JS
387#ifndef platform_core_config
388static inline int noop_core_config(const char *var, const char *value, void *cb)
389{
390 return 0;
391}
392#define platform_core_config noop_core_config
393#endif
394
684dd4c2
MT
395int lstat_cache_aware_rmdir(const char *path);
396#if !defined(__MINGW32__) && !defined(_MSC_VER)
397#define rmdir lstat_cache_aware_rmdir
398#endif
399
25fe217b 400#ifndef has_dos_drive_prefix
bf728346
RS
401static inline int git_has_dos_drive_prefix(const char *path)
402{
403 return 0;
404}
405#define has_dos_drive_prefix git_has_dos_drive_prefix
25fe217b
JS
406#endif
407
2f36eed9
JS
408#ifndef skip_dos_drive_prefix
409static inline int git_skip_dos_drive_prefix(char **path)
410{
411 return 0;
412}
413#define skip_dos_drive_prefix git_skip_dos_drive_prefix
414#endif
415
bf728346
RS
416#ifndef is_dir_sep
417static inline int git_is_dir_sep(int c)
418{
419 return c == '/';
420}
421#define is_dir_sep git_is_dir_sep
c2369bdf
CZ
422#endif
423
bf728346
RS
424#ifndef offset_1st_component
425static inline int git_offset_1st_component(const char *path)
426{
427 return is_dir_sep(path[0]);
428}
429#define offset_1st_component git_offset_1st_component
25fe217b
JS
430#endif
431
d2c84dad
JS
432#ifndef is_valid_path
433#define is_valid_path(path) 1
434#endif
435
d1c69255 436#ifndef find_last_dir_sep
bf728346
RS
437static inline char *git_find_last_dir_sep(const char *path)
438{
439 return strrchr(path, '/');
440}
441#define find_last_dir_sep git_find_last_dir_sep
d1c69255
TN
442#endif
443
05ac8582
AK
444#ifndef has_dir_sep
445static inline int git_has_dir_sep(const char *path)
446{
447 return !!strchr(path, '/');
448}
449#define has_dir_sep(path) git_has_dir_sep(path)
450#endif
451
501afcb8
JS
452#ifndef query_user_email
453#define query_user_email() NULL
454#endif
455
1305ef37
RB
456#ifdef __TANDEM
457#include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
458#include <floss.h(floss_getpwuid)>
459#ifndef NSIG
460/*
461 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
462 * known, by detective work using kill -l as a list is all signals
463 * instead of signal.h where it should be.
464 */
465# define NSIG 100
466#endif
467#endif
468
e4ac953b 469#if defined(__HP_cc) && (__HP_cc >= 61000)
b6ab349b
MR
470#define NORETURN __attribute__((noreturn))
471#define NORETURN_PTR
6520c846 472#elif defined(__GNUC__) && !defined(NO_NORETURN)
4050c0df 473#define NORETURN __attribute__((__noreturn__))
18660bc9 474#define NORETURN_PTR __attribute__((__noreturn__))
aba7dea8
RJ
475#elif defined(_MSC_VER)
476#define NORETURN __declspec(noreturn)
477#define NORETURN_PTR
4050c0df
JH
478#else
479#define NORETURN
18660bc9 480#define NORETURN_PTR
8cd7ebc8 481#ifndef __GNUC__
4050c0df
JH
482#ifndef __attribute__
483#define __attribute__(x)
484#endif
485#endif
8cd7ebc8 486#endif
4050c0df 487
9fe3edc4
RJ
488/* The sentinel attribute is valid from gcc version 4.0 */
489#if defined(__GNUC__) && (__GNUC__ >= 4)
490#define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
491#else
492#define LAST_ARG_MUST_BE_NULL
493#endif
494
bbd8eb3e
CMAB
495#define MAYBE_UNUSED __attribute__((__unused__))
496
51ea5519
NP
497#include "compat/bswap.h"
498
cebcab18 499#include "wildmatch.h"
cebcab18 500
9ccc0c08
RS
501struct strbuf;
502
4050c0df 503/* General helper functions */
55454427
DL
504void vreportf(const char *prefix, const char *err, va_list params);
505NORETURN void usage(const char *err);
b199d714
DL
506NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
507NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
508NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
509int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
510int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
511void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
512void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
4050c0df 513
f2be034c
BG
514#ifndef NO_OPENSSL
515#ifdef APPLE_COMMON_CRYPTO
516#include "compat/apple-common-crypto.h"
517#else
518#include <openssl/evp.h>
519#include <openssl/hmac.h>
520#endif /* APPLE_COMMON_CRYPTO */
521#include <openssl/x509v3.h>
522#endif /* NO_OPENSSL */
523
e208f9cc
JK
524/*
525 * Let callers be aware of the constant return value; this can help
9798f7e5
MK
526 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
527 * because some compilers may not support variadic macros. Since we're only
528 * trying to help gcc, anyway, it's OK; other compilers will fall back to
529 * using the function as usual.
e208f9cc 530 */
ff0a80af 531#if defined(__GNUC__)
87fe5df3
JK
532static inline int const_error(void)
533{
534 return -1;
535}
536#define error(...) (error(__VA_ARGS__), const_error())
4df5e918 537#define error_errno(...) (error_errno(__VA_ARGS__), const_error())
e208f9cc
JK
538#endif
539
5710dcce
JK
540typedef void (*report_fn)(const char *, va_list params);
541
542void set_die_routine(NORETURN_PTR report_fn routine);
543void set_error_routine(report_fn routine);
544report_fn get_error_routine(void);
545void set_warn_routine(report_fn routine);
546report_fn get_warn_routine(void);
55454427 547void set_die_is_recursing_routine(int (*routine)(void));
39a3f5ea 548
55454427
DL
549int starts_with(const char *str, const char *prefix);
550int istarts_with(const char *str, const char *prefix);
698a68be 551
cf4fff57
JK
552/*
553 * If the string "str" begins with the string found in "prefix", return 1.
554 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
555 * the string right after the prefix).
556 *
557 * Otherwise, return 0 and leave "out" untouched.
558 *
559 * Examples:
560 *
561 * [extract branch name, fail if not a branch]
562 * if (!skip_prefix(ref, "refs/heads/", &branch)
563 * return -1;
564 *
565 * [skip prefix if present, otherwise use whole string]
566 * skip_prefix(name, "refs/heads/", &name);
567 */
568static inline int skip_prefix(const char *str, const char *prefix,
569 const char **out)
fbca5837 570{
ba399c46 571 do {
cf4fff57
JK
572 if (!*prefix) {
573 *out = str;
574 return 1;
575 }
ba399c46 576 } while (*str++ == *prefix++);
cf4fff57 577 return 0;
fbca5837
MV
578}
579
afaef55e
CC
580/*
581 * If the string "str" is the same as the string in "prefix", then the "arg"
582 * parameter is set to the "def" parameter and 1 is returned.
583 * If the string "str" begins with the string found in "prefix" and then a
584 * "=" sign, then the "arg" parameter is set to "str + strlen(prefix) + 1"
585 * (i.e., to the point in the string right after the prefix and the "=" sign),
586 * and 1 is returned.
587 *
588 * Otherwise, return 0 and leave "arg" untouched.
589 *
590 * When we accept both a "--key" and a "--key=<val>" option, this function
591 * can be used instead of !strcmp(arg, "--key") and then
592 * skip_prefix(arg, "--key=", &arg) to parse such an option.
593 */
594int skip_to_optional_arg_default(const char *str, const char *prefix,
595 const char **arg, const char *def);
596
597static inline int skip_to_optional_arg(const char *str, const char *prefix,
598 const char **arg)
599{
600 return skip_to_optional_arg_default(str, prefix, arg, "");
601}
602
ae989a61
JK
603/*
604 * Like skip_prefix, but promises never to read past "len" bytes of the input
605 * buffer, and returns the remaining number of bytes in "out" via "outlen".
606 */
607static inline int skip_prefix_mem(const char *buf, size_t len,
608 const char *prefix,
609 const char **out, size_t *outlen)
610{
611 size_t prefix_len = strlen(prefix);
612 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
613 *out = buf + prefix_len;
614 *outlen = len - prefix_len;
615 return 1;
616 }
617 return 0;
618}
619
35480f0b
JK
620/*
621 * If buf ends with suffix, return 1 and subtract the length of the suffix
622 * from *len. Otherwise, return 0 and leave *len untouched.
623 */
624static inline int strip_suffix_mem(const char *buf, size_t *len,
625 const char *suffix)
626{
627 size_t suflen = strlen(suffix);
628 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
629 return 0;
630 *len -= suflen;
631 return 1;
632}
633
634/*
635 * If str ends with suffix, return 1 and set *len to the size of the string
636 * without the suffix. Otherwise, return 0 and set *len to the size of the
637 * string.
638 *
639 * Note that we do _not_ NUL-terminate str to the new length.
640 */
641static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
642{
643 *len = strlen(str);
644 return strip_suffix_mem(str, len, suffix);
645}
646
f52a35fd
JK
647static inline int ends_with(const char *str, const char *suffix)
648{
649 size_t len;
650 return strip_suffix(str, suffix, &len);
651}
652
568edcb9
RS
653#define SWAP(a, b) do { \
654 void *_swap_a_ptr = &(a); \
655 void *_swap_b_ptr = &(b); \
656 unsigned char _swap_buffer[sizeof(a)]; \
657 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
658 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
659 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
660 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
661} while (0)
662
b130a72b 663#if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
4050c0df
JH
664
665#ifndef PROT_READ
666#define PROT_READ 1
667#define PROT_WRITE 2
668#define MAP_PRIVATE 1
4050c0df
JH
669#endif
670
d6779124
SP
671#define mmap git_mmap
672#define munmap git_munmap
55454427
DL
673void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
674int git_munmap(void *start, size_t length);
4050c0df 675
b130a72b
JL
676#else /* NO_MMAP || USE_WIN32_MMAP */
677
678#include <sys/mman.h>
679
680#endif /* NO_MMAP || USE_WIN32_MMAP */
681
682#ifdef NO_MMAP
683
5faaf246 684/* This value must be multiple of (pagesize * 2) */
8c82534d
SP
685#define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
686
4050c0df
JH
687#else /* NO_MMAP */
688
5faaf246 689/* This value must be multiple of (pagesize * 2) */
22bac0ea
SP
690#define DEFAULT_PACKED_GIT_WINDOW_SIZE \
691 (sizeof(void*) >= 8 \
692 ? 1 * 1024 * 1024 * 1024 \
693 : 32 * 1024 * 1024)
4050c0df
JH
694
695#endif /* NO_MMAP */
696
fcf3a21a
GV
697#ifndef MAP_FAILED
698#define MAP_FAILED ((void *)-1)
699#endif
700
fdb2a2a6
JH
701#ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
702#define on_disk_bytes(st) ((st).st_size)
703#else
704#define on_disk_bytes(st) ((st).st_blocks * 512)
705#endif
706
d543d9c0
DM
707#ifdef NEEDS_MODE_TRANSLATION
708#undef S_IFMT
709#undef S_IFREG
710#undef S_IFDIR
711#undef S_IFLNK
712#undef S_IFBLK
713#undef S_IFCHR
714#undef S_IFIFO
715#undef S_IFSOCK
716#define S_IFMT 0170000
717#define S_IFREG 0100000
718#define S_IFDIR 0040000
719#define S_IFLNK 0120000
720#define S_IFBLK 0060000
721#define S_IFCHR 0020000
722#define S_IFIFO 0010000
723#define S_IFSOCK 0140000
724#ifdef stat
725#undef stat
726#endif
727#define stat(path, buf) git_stat(path, buf)
55454427 728int git_stat(const char *, struct stat *);
d543d9c0
DM
729#ifdef fstat
730#undef fstat
731#endif
732#define fstat(fd, buf) git_fstat(fd, buf)
55454427 733int git_fstat(int, struct stat *);
d543d9c0
DM
734#ifdef lstat
735#undef lstat
736#endif
737#define lstat(path, buf) git_lstat(path, buf)
55454427 738int git_lstat(const char *, struct stat *);
d543d9c0
DM
739#endif
740
22bac0ea 741#define DEFAULT_PACKED_GIT_LIMIT \
be4ca290 742 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
8c82534d 743
6900679c
SH
744#ifdef NO_PREAD
745#define pread git_pread
55454427 746ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
6900679c 747#endif
14086b0a
SP
748/*
749 * Forward decl that will remind us if its twin in cache.h changes.
750 * This function is used in compat/pread.c. But we can't include
751 * cache.h there.
752 */
55454427 753ssize_t read_in_full(int fd, void *buf, size_t count);
6900679c 754
4050c0df
JH
755#ifdef NO_SETENV
756#define setenv gitsetenv
55454427 757int gitsetenv(const char *, const char *, int);
4050c0df
JH
758#endif
759
ca5bb5d5
SP
760#ifdef NO_MKDTEMP
761#define mkdtemp gitmkdtemp
55454427 762char *gitmkdtemp(char *);
ca5bb5d5 763#endif
0620b39b 764
731043fd
JR
765#ifdef NO_UNSETENV
766#define unsetenv gitunsetenv
a38989bd 767int gitunsetenv(const char *);
731043fd
JR
768#endif
769
4050c0df
JH
770#ifdef NO_STRCASESTR
771#define strcasestr gitstrcasestr
55454427 772char *gitstrcasestr(const char *haystack, const char *needle);
4050c0df
JH
773#endif
774
817151e6
PE
775#ifdef NO_STRLCPY
776#define strlcpy gitstrlcpy
55454427 777size_t gitstrlcpy(char *, const char *, size_t);
817151e6
PE
778#endif
779
bc6b4f52
JR
780#ifdef NO_STRTOUMAX
781#define strtoumax gitstrtoumax
55454427 782uintmax_t gitstrtoumax(const char *, char **, int);
97000ba6 783#define strtoimax gitstrtoimax
55454427 784intmax_t gitstrtoimax(const char *, char **, int);
bc6b4f52
JR
785#endif
786
fa0c87c3
AR
787#ifdef NO_HSTRERROR
788#define hstrerror githstrerror
55454427 789const char *githstrerror(int herror);
fa0c87c3
AR
790#endif
791
b21b9f1d
RS
792#ifdef NO_MEMMEM
793#define memmem gitmemmem
794void *gitmemmem(const void *haystack, size_t haystacklen,
ec36c42a 795 const void *needle, size_t needlelen);
b21b9f1d
RS
796#endif
797
ca2baa3f
RS
798#ifdef OVERRIDE_STRDUP
799#ifdef strdup
800#undef strdup
801#endif
802#define strdup gitstrdup
803char *gitstrdup(const char *s);
804#endif
b21b9f1d 805
40036bed
MK
806#ifdef NO_GETPAGESIZE
807#define getpagesize() sysconf(_SC_PAGESIZE)
808#endif
809
05d1ed61
BW
810#ifndef O_CLOEXEC
811#define O_CLOEXEC 0
812#endif
813
cba22528 814#ifdef FREAD_READS_DIRECTORIES
b0a642ac
RJ
815# if !defined(SUPPRESS_FOPEN_REDEFINITION)
816# ifdef fopen
817# undef fopen
818# endif
819# define fopen(a,b) git_fopen(a,b)
820# endif
55454427 821FILE *git_fopen(const char*, const char*);
cba22528
BC
822#endif
823
c4582f93 824#ifdef SNPRINTF_RETURNS_BOGUS
ab03803c
BS
825#ifdef snprintf
826#undef snprintf
827#endif
c4582f93 828#define snprintf git_snprintf
b199d714 829int git_snprintf(char *str, size_t maxsize,
ad6dad09 830 const char *format, ...);
ab03803c
BS
831#ifdef vsnprintf
832#undef vsnprintf
833#endif
c4582f93 834#define vsnprintf git_vsnprintf
55454427 835int git_vsnprintf(char *str, size_t maxsize,
ad6dad09 836 const char *format, va_list ap);
c4582f93
MR
837#endif
838
2b081012
JK
839#ifdef OPEN_RETURNS_EINTR
840#undef open
841#define open git_open_with_retry
842int git_open_with_retry(const char *path, int flag, ...);
843#endif
844
726c8ef5
JS
845#ifdef __GLIBC_PREREQ
846#if __GLIBC_PREREQ(2, 1)
847#define HAVE_STRCHRNUL
848#endif
849#endif
850
851#ifndef HAVE_STRCHRNUL
659c69cf 852#define strchrnul gitstrchrnul
9e79f00f
AE
853static inline char *gitstrchrnul(const char *s, int c)
854{
855 while (*s && *s != c)
856 s++;
857 return (char *)s;
858}
659c69cf
RS
859#endif
860
da523cc5
MP
861#ifdef NO_INET_PTON
862int inet_pton(int af, const char *src, void *dst);
863#endif
864
865#ifdef NO_INET_NTOP
866const char *inet_ntop(int af, const void *src, char *dst, size_t size);
867#endif
868
0f4b6db3
EB
869#ifdef NO_PTHREADS
870#define atexit git_atexit
55454427 871int git_atexit(void (*handler)(void));
0f4b6db3
EB
872#endif
873
320d0b49
JK
874static inline size_t st_add(size_t a, size_t b)
875{
876 if (unsigned_add_overflows(a, b))
877 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
878 (uintmax_t)a, (uintmax_t)b);
879 return a + b;
880}
d616fbf2
ES
881#define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
882#define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
320d0b49
JK
883
884static inline size_t st_mult(size_t a, size_t b)
885{
886 if (unsigned_mult_overflows(a, b))
887 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
888 (uintmax_t)a, (uintmax_t)b);
889 return a * b;
890}
891
892static inline size_t st_sub(size_t a, size_t b)
893{
894 if (a < b)
895 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
896 (uintmax_t)a, (uintmax_t)b);
897 return a - b;
898}
a9a74636 899
e2ffeae3
JS
900static inline size_t st_left_shift(size_t a, unsigned shift)
901{
902 if (unsigned_left_shift_overflows(a, shift))
903 die("size_t overflow: %"PRIuMAX" << %u",
904 (uintmax_t)a, shift);
905 return a << shift;
906}
907
908static inline unsigned long cast_size_t_to_ulong(size_t a)
909{
910 if (a != (unsigned long)a)
911 die("object too large to read on this platform: %"
912 PRIuMAX" is cut off to %lu",
913 (uintmax_t)a, (unsigned long)a);
914 return (unsigned long)a;
915}
916
61f76a36
KS
917#ifdef HAVE_ALLOCA_H
918# include <alloca.h>
919# define xalloca(size) (alloca(size))
920# define xalloca_free(p) do {} while (0)
921#else
922# define xalloca(size) (xmalloc(size))
923# define xalloca_free(p) (free(p))
924#endif
55454427
DL
925char *xstrdup(const char *str);
926void *xmalloc(size_t size);
927void *xmallocz(size_t size);
928void *xmallocz_gently(size_t size);
929void *xmemdupz(const void *data, size_t len);
930char *xstrndup(const char *str, size_t len);
931void *xrealloc(void *ptr, size_t size);
932void *xcalloc(size_t nmemb, size_t size);
3540c71e 933void xsetenv(const char *name, const char *value, int overwrite);
55454427 934void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
dc059294 935const char *mmap_os_err(void);
55454427 936void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
b199d714 937int xopen(const char *path, int flags, ...);
55454427
DL
938ssize_t xread(int fd, void *buf, size_t len);
939ssize_t xwrite(int fd, const void *buf, size_t len);
940ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
941int xdup(int fd);
942FILE *xfopen(const char *path, const char *mode);
943FILE *xfdopen(int fd, const char *mode);
944int xmkstemp(char *temp_filename);
945int xmkstemp_mode(char *temp_filename, int mode);
946char *xgetcwd(void);
947FILE *fopen_for_writing(const char *path);
948FILE *fopen_or_warn(const char *path, const char *mode);
f21a47b2 949
14570dc6 950/*
951 * Like strncmp, but only return zero if s is NUL-terminated and exactly len
952 * characters long. If it is not, consider it greater than t.
953 */
954int xstrncmpz(const char *s, const char *t, size_t len);
955
481df65f
ÆAB
956/*
957 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
958 * that ptr is used twice, so don't pass e.g. ptr++.
959 */
960#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
961
e7792a74 962#define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
f1121499 963#define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
e7792a74 964#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
3ac22f82 965
60566cbb
RS
966#define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
967 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
968static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
969{
970 if (n)
971 memcpy(dst, src, st_mult(size, n));
972}
973
57839807
RS
974#define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
975 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
976static inline void move_array(void *dst, const void *src, size_t n, size_t size)
977{
978 if (n)
979 memmove(dst, src, st_mult(size, n));
980}
981
36895391
JK
982/*
983 * These functions help you allocate structs with flex arrays, and copy
984 * the data directly into the array. For example, if you had:
985 *
986 * struct foo {
987 * int bar;
988 * char name[FLEX_ARRAY];
989 * };
990 *
991 * you can do:
992 *
993 * struct foo *f;
994 * FLEX_ALLOC_MEM(f, name, src, len);
995 *
996 * to allocate a "foo" with the contents of "src" in the "name" field.
997 * The resulting struct is automatically zero'd, and the flex-array field
998 * is NUL-terminated (whether the incoming src buffer was or not).
999 *
1000 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
1001 * but do want to store a pointer to some extra data in the same allocated
1002 * block. For example, if you have:
1003 *
1004 * struct foo {
1005 * char *name;
1006 * int bar;
1007 * };
1008 *
1009 * you can do:
1010 *
1011 * struct foo *f;
0bb1519f 1012 * FLEXPTR_ALLOC_STR(f, name, src);
36895391
JK
1013 *
1014 * and "name" will point to a block of memory after the struct, which will be
1015 * freed along with the struct (but the pointer can be repointed anywhere).
1016 *
1017 * The *_STR variants accept a string parameter rather than a ptr/len
1018 * combination.
1019 *
1020 * Note that these macros will evaluate the first parameter multiple
1021 * times, and it must be assignable as an lvalue.
1022 */
1023#define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
e9451782
RS
1024 size_t flex_array_len_ = (len); \
1025 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1026 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
36895391
JK
1027} while (0)
1028#define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
0ac52a38
RS
1029 size_t flex_array_len_ = (len); \
1030 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1031 memcpy((x) + 1, (buf), flex_array_len_); \
36895391
JK
1032 (x)->ptrname = (void *)((x)+1); \
1033} while(0)
1034#define FLEX_ALLOC_STR(x, flexname, str) \
1035 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
1036#define FLEXPTR_ALLOC_STR(x, ptrname, str) \
1037 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
1038
d64ea0f8
JK
1039static inline char *xstrdup_or_null(const char *str)
1040{
1041 return str ? xstrdup(str) : NULL;
1042}
1043
dc49cd76
SP
1044static inline size_t xsize_t(off_t len)
1045{
aafa5df0 1046 if (len < 0 || (uintmax_t) len > SIZE_MAX)
46be82df 1047 die("Cannot handle files this big");
aafa5df0 1048 return (size_t) len;
dc49cd76
SP
1049}
1050
7b03c89e 1051__attribute__((format (printf, 3, 4)))
b199d714 1052int xsnprintf(char *dst, size_t max, const char *fmt, ...);
7b03c89e 1053
da25bdb7
RS
1054#ifndef HOST_NAME_MAX
1055#define HOST_NAME_MAX 256
1056#endif
1057
55454427 1058int xgethostname(char *buf, size_t len);
5781a9a2 1059
f1589d10 1060/* in ctype.c, for kwset users */
189c860c 1061extern const unsigned char tolower_trans_tbl[256];
f1589d10 1062
4050c0df 1063/* Sane ctype - no locale, and works with signed chars */
c2e9364a 1064#undef isascii
4050c0df
JH
1065#undef isspace
1066#undef isdigit
1067#undef isalpha
1068#undef isalnum
0fcec2ce 1069#undef isprint
43ccdf56
NK
1070#undef islower
1071#undef isupper
4050c0df
JH
1072#undef tolower
1073#undef toupper
1c149ab2
NTND
1074#undef iscntrl
1075#undef ispunct
1076#undef isxdigit
2adf7247 1077
ca5ab7d1 1078extern const unsigned char sane_ctype[256];
4050c0df
JH
1079#define GIT_SPACE 0x01
1080#define GIT_DIGIT 0x02
1081#define GIT_ALPHA 0x04
8cc32992 1082#define GIT_GLOB_SPECIAL 0x08
f9b7cce6 1083#define GIT_REGEX_SPECIAL 0x10
2f6c9760 1084#define GIT_PATHSPEC_MAGIC 0x20
1c149ab2
NTND
1085#define GIT_CNTRL 0x40
1086#define GIT_PUNCT 0x80
4050c0df 1087#define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
c2e9364a 1088#define isascii(x) (((x) & ~0x7f) == 0)
4050c0df
JH
1089#define isspace(x) sane_istest(x,GIT_SPACE)
1090#define isdigit(x) sane_istest(x,GIT_DIGIT)
1091#define isalpha(x) sane_istest(x,GIT_ALPHA)
1092#define isalnum(x) sane_istest(x,GIT_ALPHA | GIT_DIGIT)
0fcec2ce 1093#define isprint(x) ((x) >= 0x20 && (x) <= 0x7e)
43ccdf56
NK
1094#define islower(x) sane_iscase(x, 1)
1095#define isupper(x) sane_iscase(x, 0)
8cc32992 1096#define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
f9b7cce6 1097#define is_regex_special(x) sane_istest(x,GIT_GLOB_SPECIAL | GIT_REGEX_SPECIAL)
1c149ab2
NTND
1098#define iscntrl(x) (sane_istest(x,GIT_CNTRL))
1099#define ispunct(x) sane_istest(x, GIT_PUNCT | GIT_REGEX_SPECIAL | \
1100 GIT_GLOB_SPECIAL | GIT_PATHSPEC_MAGIC)
50a71776 1101#define isxdigit(x) (hexval_table[(unsigned char)(x)] != -1)
4050c0df
JH
1102#define tolower(x) sane_case((unsigned char)(x), 0x20)
1103#define toupper(x) sane_case((unsigned char)(x), 0)
2f6c9760 1104#define is_pathspec_magic(x) sane_istest(x,GIT_PATHSPEC_MAGIC)
4050c0df
JH
1105
1106static inline int sane_case(int x, int high)
1107{
1108 if (sane_istest(x, GIT_ALPHA))
1109 x = (x & ~0x20) | high;
1110 return x;
1111}
1112
43ccdf56
NK
1113static inline int sane_iscase(int x, int is_lower)
1114{
1115 if (!sane_istest(x, GIT_ALPHA))
1116 return 0;
1117
1118 if (is_lower)
1119 return (x & 0x20) != 0;
1120 else
1121 return (x & 0x20) == 0;
1122}
1123
41a80924
JK
1124/*
1125 * Like skip_prefix, but compare case-insensitively. Note that the comparison
1126 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
1127 * locale-specific conversions).
1128 */
1129static inline int skip_iprefix(const char *str, const char *prefix,
1130 const char **out)
1131{
1132 do {
1133 if (!*prefix) {
1134 *out = str;
1135 return 1;
1136 }
1137 } while (tolower(*str++) == tolower(*prefix++));
1138 return 0;
1139}
1140
6aead43d
JM
1141static inline int strtoul_ui(char const *s, int base, unsigned int *result)
1142{
1143 unsigned long ul;
1144 char *p;
1145
1146 errno = 0;
e6f2599c
MM
1147 /* negative values would be accepted by strtoul */
1148 if (strchr(s, '-'))
1149 return -1;
6aead43d
JM
1150 ul = strtoul(s, &p, base);
1151 if (errno || *p || p == s || (unsigned int) ul != ul)
1152 return -1;
1153 *result = ul;
1154 return 0;
1155}
1156
7791ecbc
JH
1157static inline int strtol_i(char const *s, int base, int *result)
1158{
1159 long ul;
1160 char *p;
1161
1162 errno = 0;
1163 ul = strtol(s, &p, base);
1164 if (errno || *p || p == s || (int) ul != ul)
1165 return -1;
1166 *result = ul;
1167 return 0;
1168}
1169
97fff610
JS
1170void git_stable_qsort(void *base, size_t nmemb, size_t size,
1171 int(*compar)(const void *, const void *));
43fe901b 1172#ifdef INTERNAL_QSORT
97fff610 1173#define qsort git_stable_qsort
43fe901b
BD
1174#endif
1175
dbc540c7
RS
1176#define QSORT(base, n, compar) sane_qsort((base), (n), sizeof(*(base)), compar)
1177static inline void sane_qsort(void *base, size_t nmemb, size_t size,
1178 int(*compar)(const void *, const void *))
1179{
1180 if (nmemb > 1)
1181 qsort(base, nmemb, size, compar);
1182}
1183
97fff610
JS
1184#define STABLE_QSORT(base, n, compar) \
1185 git_stable_qsort((base), (n), sizeof(*(base)), compar)
1186
04ee8b87
RS
1187#ifndef HAVE_ISO_QSORT_S
1188int git_qsort_s(void *base, size_t nmemb, size_t size,
1189 int (*compar)(const void *, const void *, void *), void *ctx);
1190#define qsort_s git_qsort_s
1191#endif
1192
3ca86994
RS
1193#define QSORT_S(base, n, compar, ctx) do { \
1194 if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
c3c3486b 1195 BUG("qsort_s() failed"); \
3ca86994
RS
1196} while (0)
1197
2f895225
JS
1198#ifndef REG_STARTEND
1199#error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
1200#endif
1201
1202static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
1203 size_t nmatch, regmatch_t pmatch[], int eflags)
1204{
1205 assert(nmatch > 0 && pmatch);
1206 pmatch[0].rm_so = 0;
1207 pmatch[0].rm_eo = size;
1208 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
1209}
1210
81a24b52
AR
1211#ifndef DIR_HAS_BSD_GROUP_SEMANTICS
1212# define FORCE_DIR_SET_GID S_ISGID
1213#else
1214# define FORCE_DIR_SET_GID 0
1215#endif
1216
c06ff490
KB
1217#ifdef NO_NSEC
1218#undef USE_NSEC
1219#define ST_CTIME_NSEC(st) 0
1220#define ST_MTIME_NSEC(st) 0
1221#else
c567383b
BG
1222#ifdef USE_ST_TIMESPEC
1223#define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
1224#define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
1225#else
c06ff490
KB
1226#define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
1227#define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
1228#endif
c567383b 1229#endif
c06ff490 1230
34779c53
JS
1231#ifdef UNRELIABLE_FSTAT
1232#define fstat_is_reliable() 0
1233#else
1234#define fstat_is_reliable() 1
1235#endif
1236
ab8632ae 1237#ifndef va_copy
26db0f2e
JN
1238/*
1239 * Since an obvious implementation of va_list would be to make it a
1240 * pointer into the stack frame, a simple assignment will work on
1241 * many systems. But let's try to be more portable.
1242 */
1243#ifdef __va_copy
1244#define va_copy(dst, src) __va_copy(dst, src)
1245#else
1246#define va_copy(dst, src) ((dst) = (src))
1247#endif
ab8632ae
JK
1248#endif
1249
765dc168
JK
1250/*
1251 * This is always defined as a first step towards making the use of variadic
1252 * macros unconditional. If it causes compilation problems on your platform,
1253 * please report it to the Git mailing list at git@vger.kernel.org.
1254 */
e05bed96 1255#define HAVE_VARIADIC_MACROS 1
e05bed96 1256
746ea4ad
RJ
1257/* usage.c: only to be used for testing BUG() implementation (see test-tool) */
1258extern int BUG_exit_code;
1259
d8193743
JK
1260#ifdef HAVE_VARIADIC_MACROS
1261__attribute__((format (printf, 3, 4))) NORETURN
1262void BUG_fl(const char *file, int line, const char *fmt, ...);
1263#define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
1264#else
1265__attribute__((format (printf, 1, 2))) NORETURN
1266void BUG(const char *fmt, ...);
1267#endif
1268
fc71db39
AR
1269/*
1270 * Preserves errno, prints a message, but gives no warning for ENOENT.
1054af7d
RS
1271 * Returns 0 on success, which includes trying to unlink an object that does
1272 * not exist.
fc71db39
AR
1273 */
1274int unlink_or_warn(const char *path);
9ccc0c08
RS
1275 /*
1276 * Tries to unlink file. Returns 0 if unlink succeeded
1277 * or the file already didn't exist. Returns -1 and
1278 * appends a message to err suitable for
1279 * 'error("%s", err->buf)' on error.
1280 */
1281int unlink_or_msg(const char *file, struct strbuf *err);
d1723296 1282/*
1054af7d
RS
1283 * Preserves errno, prints a message, but gives no warning for ENOENT.
1284 * Returns 0 on success, which includes trying to remove a directory that does
1285 * not exist.
d1723296
PC
1286 */
1287int rmdir_or_warn(const char *path);
80d706af
PC
1288/*
1289 * Calls the correct function out of {unlink,rmdir}_or_warn based on
1290 * the supplied file mode.
1291 */
1292int remove_or_warn(unsigned int mode, const char *path);
fc71db39 1293
e5c52c98
JN
1294/*
1295 * Call access(2), but warn for any error except "missing file"
1296 * (ENOENT or ENOTDIR).
1297 */
4698c8fe
JN
1298#define ACCESS_EACCES_OK (1U << 0)
1299int access_or_warn(const char *path, int mode, unsigned flag);
1300int access_or_die(const char *path, int mode, unsigned flag);
ba8bd830 1301
11dc1fcb
NTND
1302/* Warn on an inaccessible file if errno indicates this is an error */
1303int warn_on_fopen_errors(const char *path);
55b38a48 1304
00611d84
JK
1305/*
1306 * Open with O_NOFOLLOW, or equivalent. Note that the fallback equivalent
1307 * may be racy. Do not use this as protection against an attacker who can
1308 * simultaneously create paths.
1309 */
1310int open_nofollow(const char *path, int flags);
1311
1b56cdf9
KM
1312#ifndef SHELL_PATH
1313# define SHELL_PATH "/bin/sh"
1314#endif
1315
f43cce23 1316#ifndef _POSIX_THREAD_SAFE_FUNCTIONS
15b52a44
JH
1317static inline void flockfile(FILE *fh)
1318{
1319 ; /* nothing */
1320}
1321static inline void funlockfile(FILE *fh)
1322{
1323 ; /* nothing */
1324}
f43cce23
JK
1325#define getc_unlocked(fh) getc(fh)
1326#endif
1327
18a4f6be
NTND
1328#ifdef FILENO_IS_A_MACRO
1329int git_fileno(FILE *stream);
400caafb 1330# ifndef COMPAT_CODE_FILENO
18a4f6be
NTND
1331# undef fileno
1332# define fileno(p) git_fileno(p)
1333# endif
1334#endif
1335
400caafb
CC
1336#ifdef NEED_ACCESS_ROOT_HANDLER
1337int git_access(const char *path, int mode);
1338# ifndef COMPAT_CODE_ACCESS
1339# ifdef access
1340# undef access
1341# endif
1342# define access(path, mode) git_access(path, mode)
1343# endif
1344#endif
1345
dc5a18b3
JH
1346/*
1347 * Our code often opens a path to an optional file, to work on its
1348 * contents when we can successfully open it. We can ignore a failure
1349 * to open if such an optional file does not exist, but we do want to
1350 * report a failure in opening for other reasons (e.g. we got an I/O
1351 * error, or the file is there, but we lack the permission to open).
1352 *
1353 * Call this function after seeing an error from open() or fopen() to
1354 * see if the errno indicates a missing file that we can safely ignore.
1355 */
1356static inline int is_missing_file_error(int errno_)
1357{
1358 return (errno_ == ENOENT || errno_ == ENOTDIR);
1359}
1360
55454427 1361int cmd_main(int, const char **);
5c238e29 1362
ee4512ed
JH
1363/*
1364 * Intercept all calls to exit() and route them to trace2 to
1365 * optionally emit a message before calling the real exit().
1366 */
1367int trace2_cmd_exit_fl(const char *file, int line, int code);
1368#define exit(code) exit(trace2_cmd_exit_fl(__FILE__, __LINE__, (code)))
1369
0e5bba53
JK
1370/*
1371 * You can mark a stack variable with UNLEAK(var) to avoid it being
1372 * reported as a leak by tools like LSAN or valgrind. The argument
1373 * should generally be the variable itself (not its address and not what
1374 * it points to). It's safe to use this on pointers which may already
1375 * have been freed, or on pointers which may still be in use.
1376 *
1377 * Use this _only_ for a variable that leaks by going out of scope at
1378 * program exit (so only from cmd_* functions or their direct helpers).
1379 * Normal functions, especially those which may be called multiple
1380 * times, should actually free their memory. This is only meant as
1381 * an annotation, and does nothing in non-leak-checking builds.
1382 */
1383#ifdef SUPPRESS_ANNOTATED_LEAKS
55454427 1384void unleak_memory(const void *ptr, size_t len);
5de3de32 1385#define UNLEAK(var) unleak_memory(&(var), sizeof(var))
0e5bba53 1386#else
5de3de32 1387#define UNLEAK(var) do {} while (0)
0e5bba53
JK
1388#endif
1389
c8af66ab
JK
1390/*
1391 * This include must come after system headers, since it introduces macros that
1392 * replace system names.
1393 */
1394#include "banned.h"
1395
973d5eea
EW
1396/*
1397 * container_of - Get the address of an object containing a field.
1398 *
1399 * @ptr: pointer to the field.
1400 * @type: type of the object.
1401 * @member: name of the field within the object.
1402 */
1403#define container_of(ptr, type, member) \
1404 ((type *) ((char *)(ptr) - offsetof(type, member)))
1405
f0e63c41
EW
1406/*
1407 * helper function for `container_of_or_null' to avoid multiple
1408 * evaluation of @ptr
1409 */
1410static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1411{
1412 return ptr ? (char *)ptr - offset : NULL;
1413}
1414
1415/*
1416 * like `container_of', but allows returned value to be NULL
1417 */
1418#define container_of_or_null(ptr, type, member) \
1419 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1420
23dee69f 1421/*
abcb66c6 1422 * like offsetof(), but takes a pointer to a variable of type which
23dee69f
EW
1423 * contains @member, instead of a specified type.
1424 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1425 * everywhere.
1426 */
1427#if defined(__GNUC__) /* clang sets this, too */
1428#define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1429#else /* !__GNUC__ */
1430#define OFFSETOF_VAR(ptr, member) \
1431 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1432#endif /* !__GNUC__ */
1433
a76b138d
HWN
1434void sleep_millisec(int millisec);
1435
05cd988d 1436/*
1437 * Generate len bytes from the system cryptographically secure PRNG.
1438 * Returns 0 on success and -1 on error, setting errno. The inability to
1439 * satisfy the full request is an error.
1440 */
1441int csprng_bytes(void *buf, size_t len);
1442
5c238e29 1443#endif