The eighteenth batch
[git.git] / git-compat-util.h
blobe4a306dd5639b58a4ec4d2a6269fb649348fb4e7
1 #ifndef GIT_COMPAT_UTIL_H
2 #define GIT_COMPAT_UTIL_H
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.
14 #error "Required C99 support is in a test phase. Please see git-compat-util.h for more details."
15 #endif
17 #ifdef USE_MSVC_CRTDBG
19 * For these to work they must appear very early in each
20 * file -- before most of the standard header files.
22 #include <stdlib.h>
23 #include <crtdbg.h>
24 #endif
26 struct strbuf;
29 #define _FILE_OFFSET_BITS 64
32 /* Derived from Linux "Features Test Macro" header
33 * Convenience macros to test the versions of gcc (or
34 * a compatible compiler).
35 * Use them like this:
36 * #if GIT_GNUC_PREREQ (2,8)
37 * ... code requiring gcc 2.8 or later ...
38 * #endif
40 #if defined(__GNUC__) && defined(__GNUC_MINOR__)
41 # define GIT_GNUC_PREREQ(maj, min) \
42 ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
43 #else
44 #define GIT_GNUC_PREREQ(maj, min) 0
45 #endif
48 #ifndef FLEX_ARRAY
50 * See if our compiler is known to support flexible array members.
54 * Check vendor specific quirks first, before checking the
55 * __STDC_VERSION__, as vendor compilers can lie and we need to be
56 * able to work them around. Note that by not defining FLEX_ARRAY
57 * here, we can fall back to use the "safer but a bit wasteful" one
58 * later.
60 #if defined(__SUNPRO_C) && (__SUNPRO_C <= 0x580)
61 #elif defined(__GNUC__)
62 # if (__GNUC__ >= 3)
63 # define FLEX_ARRAY /* empty */
64 # else
65 # define FLEX_ARRAY 0 /* older GNU extension */
66 # endif
67 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
68 # define FLEX_ARRAY /* empty */
69 #endif
72 * Otherwise, default to safer but a bit wasteful traditional style
74 #ifndef FLEX_ARRAY
75 # define FLEX_ARRAY 1
76 #endif
77 #endif
81 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
82 * @cond: the compile-time condition which must be true.
84 * Your compile will fail if the condition isn't true, or can't be evaluated
85 * by the compiler. This can be used in an expression: its value is "0".
87 * Example:
88 * #define foo_to_char(foo) \
89 * ((char *)(foo) \
90 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
92 #define BUILD_ASSERT_OR_ZERO(cond) \
93 (sizeof(char [1 - 2*!(cond)]) - 1)
95 #if GIT_GNUC_PREREQ(3, 1)
96 /* &arr[0] degrades to a pointer: a different type from an array */
97 # define BARF_UNLESS_AN_ARRAY(arr) \
98 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
99 __typeof__(&(arr)[0])))
100 # define BARF_UNLESS_COPYABLE(dst, src) \
101 BUILD_ASSERT_OR_ZERO(__builtin_types_compatible_p(__typeof__(*(dst)), \
102 __typeof__(*(src))))
103 #else
104 # define BARF_UNLESS_AN_ARRAY(arr) 0
105 # define BARF_UNLESS_COPYABLE(dst, src) \
106 BUILD_ASSERT_OR_ZERO(0 ? ((*(dst) = *(src)), 0) : \
107 sizeof(*(dst)) == sizeof(*(src)))
108 #endif
110 * ARRAY_SIZE - get the number of elements in a visible array
111 * @x: the array whose size you want.
113 * This does not work on pointers, or arrays declared as [], or
114 * function parameters. With correct compiler support, such usage
115 * will cause a build error (see the build_assert_or_zero macro).
117 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
119 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
121 #define maximum_signed_value_of_type(a) \
122 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
124 #define maximum_unsigned_value_of_type(a) \
125 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
128 * Signed integer overflow is undefined in C, so here's a helper macro
129 * to detect if the sum of two integers will overflow.
131 * Requires: a >= 0, typeof(a) equals typeof(b)
133 #define signed_add_overflows(a, b) \
134 ((b) > maximum_signed_value_of_type(a) - (a))
136 #define unsigned_add_overflows(a, b) \
137 ((b) > maximum_unsigned_value_of_type(a) - (a))
140 * Returns true if the multiplication of "a" and "b" will
141 * overflow. The types of "a" and "b" must match and must be unsigned.
142 * Note that this macro evaluates "a" twice!
144 #define unsigned_mult_overflows(a, b) \
145 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
148 * Returns true if the left shift of "a" by "shift" bits will
149 * overflow. The type of "a" must be unsigned.
151 #define unsigned_left_shift_overflows(a, shift) \
152 ((shift) < bitsizeof(a) && \
153 (a) > maximum_unsigned_value_of_type(a) >> (shift))
155 #ifdef __GNUC__
156 #define TYPEOF(x) (__typeof__(x))
157 #else
158 #define TYPEOF(x)
159 #endif
161 #define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
162 #define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
164 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
166 /* Approximation of the length of the decimal representation of this type. */
167 #define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
169 #ifdef __MINGW64__
170 #define _POSIX_C_SOURCE 1
171 #elif defined(__sun__)
173 * On Solaris, when _XOPEN_EXTENDED is set, its header file
174 * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
175 * setting to say we are XPG5 or XPG6. Also on Solaris,
176 * XPG6 programs must be compiled with a c99 compiler, while
177 * non XPG6 programs must be compiled with a pre-c99 compiler.
179 # if __STDC_VERSION__ - 0 >= 199901L
180 # define _XOPEN_SOURCE 600
181 # else
182 # define _XOPEN_SOURCE 500
183 # endif
184 #elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
185 !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
186 !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
187 !defined(__CYGWIN__)
188 #define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
189 #define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
190 #endif
191 #define _ALL_SOURCE 1
192 #define _GNU_SOURCE 1
193 #define _BSD_SOURCE 1
194 #define _DEFAULT_SOURCE 1
195 #define _NETBSD_SOURCE 1
196 #define _SGI_SOURCE 1
199 * UNUSED marks a function parameter that is always unused. It also
200 * can be used to annotate a function, a variable, or a type that is
201 * always unused.
203 * A callback interface may dictate that a function accepts a
204 * parameter at that position, but the implementation of the function
205 * may not need to use the parameter. In such a case, mark the parameter
206 * with UNUSED.
208 * When a parameter may be used or unused, depending on conditional
209 * compilation, consider using MAYBE_UNUSED instead.
211 #if GIT_GNUC_PREREQ(4, 5)
212 #define UNUSED __attribute__((unused)) \
213 __attribute__((deprecated ("parameter declared as UNUSED")))
214 #elif defined(__GNUC__)
215 #define UNUSED __attribute__((unused)) \
216 __attribute__((deprecated))
217 #else
218 #define UNUSED
219 #endif
221 #if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
222 # if !defined(_WIN32_WINNT)
223 # define _WIN32_WINNT 0x0600
224 # endif
225 #define WIN32_LEAN_AND_MEAN /* stops windows.h including winsock.h */
226 #include <winsock2.h>
227 #ifndef NO_UNIX_SOCKETS
228 #include <afunix.h>
229 #endif
230 #include <windows.h>
231 #define GIT_WINDOWS_NATIVE
232 #endif
234 #if defined(NO_UNIX_SOCKETS) || !defined(GIT_WINDOWS_NATIVE)
235 static inline int _have_unix_sockets(void)
237 #if defined(NO_UNIX_SOCKETS)
238 return 0;
239 #else
240 return 1;
241 #endif
243 #define have_unix_sockets _have_unix_sockets
244 #endif
246 #include <unistd.h>
247 #include <stdio.h>
248 #include <sys/stat.h>
249 #include <fcntl.h>
250 #include <stddef.h>
251 #include <stdlib.h>
252 #include <stdarg.h>
253 #include <stdbool.h>
254 #include <string.h>
255 #ifdef HAVE_STRINGS_H
256 #include <strings.h> /* for strcasecmp() */
257 #endif
258 #include <errno.h>
259 #include <limits.h>
260 #include <locale.h>
261 #ifdef NEEDS_SYS_PARAM_H
262 #include <sys/param.h>
263 #endif
264 #include <sys/types.h>
265 #include <dirent.h>
266 #include <sys/time.h>
267 #include <time.h>
268 #include <signal.h>
269 #include <assert.h>
270 #include <regex.h>
271 #include <utime.h>
272 #include <syslog.h>
273 #if !defined(NO_POLL_H)
274 #include <poll.h>
275 #elif !defined(NO_SYS_POLL_H)
276 #include <sys/poll.h>
277 #else
278 /* Pull the compat stuff */
279 #include <poll.h>
280 #endif
281 #ifdef HAVE_BSD_SYSCTL
282 #include <sys/sysctl.h>
283 #endif
285 /* Used by compat/win32/path-utils.h, and more */
286 static inline int is_xplatform_dir_sep(int c)
288 return c == '/' || c == '\\';
291 #if defined(__CYGWIN__)
292 #include "compat/win32/path-utils.h"
293 #endif
294 #if defined(__MINGW32__)
295 /* pull in Windows compatibility stuff */
296 #include "compat/win32/path-utils.h"
297 #include "compat/mingw.h"
298 #elif defined(_MSC_VER)
299 #include "compat/win32/path-utils.h"
300 #include "compat/msvc.h"
301 #else
302 #include <sys/utsname.h>
303 #include <sys/wait.h>
304 #include <sys/resource.h>
305 #include <sys/socket.h>
306 #include <sys/ioctl.h>
307 #include <sys/statvfs.h>
308 #include <termios.h>
309 #ifndef NO_SYS_SELECT_H
310 #include <sys/select.h>
311 #endif
312 #include <netinet/in.h>
313 #include <netinet/tcp.h>
314 #include <arpa/inet.h>
315 #include <netdb.h>
316 #include <pwd.h>
317 #include <sys/un.h>
318 #ifndef NO_INTTYPES_H
319 #include <inttypes.h>
320 #else
321 #include <stdint.h>
322 #endif
323 #ifdef HAVE_ARC4RANDOM_LIBBSD
324 #include <bsd/stdlib.h>
325 #endif
326 #ifdef HAVE_GETRANDOM
327 #include <sys/random.h>
328 #endif
329 #ifdef NO_INTPTR_T
331 * On I16LP32, ILP32 and LP64 "long" is the safe bet, however
332 * on LLP86, IL33LLP64 and P64 it needs to be "long long",
333 * while on IP16 and IP16L32 it is "int" (resp. "short")
334 * Size needs to match (or exceed) 'sizeof(void *)'.
335 * We can't take "long long" here as not everybody has it.
337 typedef long intptr_t;
338 typedef unsigned long uintptr_t;
339 #endif
340 #undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
341 #include <grp.h>
342 #define _ALL_SOURCE 1
343 #endif
345 /* used on Mac OS X */
346 #ifdef PRECOMPOSE_UNICODE
347 #include "compat/precompose_utf8.h"
348 #else
349 static inline const char *precompose_argv_prefix(int argc UNUSED,
350 const char **argv UNUSED,
351 const char *prefix)
353 return prefix;
355 static inline const char *precompose_string_if_needed(const char *in)
357 return in;
360 #define probe_utf8_pathname_composition()
361 #endif
363 #ifdef MKDIR_WO_TRAILING_SLASH
364 #define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
365 int compat_mkdir_wo_trailing_slash(const char*, mode_t);
366 #endif
368 #ifdef time
369 #undef time
370 #endif
371 static inline time_t git_time(time_t *tloc)
373 struct timeval tv;
376 * Avoid time(NULL), which can disagree with gettimeofday(2)
377 * and filesystem timestamps.
379 gettimeofday(&tv, NULL);
381 if (tloc)
382 *tloc = tv.tv_sec;
383 return tv.tv_sec;
385 #define time git_time
387 #ifdef NO_STRUCT_ITIMERVAL
388 struct itimerval {
389 struct timeval it_interval;
390 struct timeval it_value;
392 #endif
394 #ifdef NO_SETITIMER
395 static inline int git_setitimer(int which UNUSED,
396 const struct itimerval *value UNUSED,
397 struct itimerval *newvalue UNUSED) {
398 return 0; /* pretend success */
400 #undef setitimer
401 #define setitimer(which,value,ovalue) git_setitimer(which,value,ovalue)
402 #endif
404 #ifndef NO_LIBGEN_H
405 #include <libgen.h>
406 #else
407 #define basename gitbasename
408 char *gitbasename(char *);
409 #define dirname gitdirname
410 char *gitdirname(char *);
411 #endif
413 #ifndef NO_ICONV
414 #include <iconv.h>
415 #endif
417 #ifndef NO_OPENSSL
418 #ifdef __APPLE__
419 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
420 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
421 #include <AvailabilityMacros.h>
422 #undef DEPRECATED_ATTRIBUTE
423 #define DEPRECATED_ATTRIBUTE
424 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
425 #endif
426 #include <openssl/ssl.h>
427 #include <openssl/err.h>
428 #endif
430 #ifdef HAVE_SYSINFO
431 # include <sys/sysinfo.h>
432 #endif
434 /* On most systems <netdb.h> would have given us this, but
435 * not on some systems (e.g. z/OS).
437 #ifndef NI_MAXHOST
438 #define NI_MAXHOST 1025
439 #endif
441 #ifndef NI_MAXSERV
442 #define NI_MAXSERV 32
443 #endif
445 /* On most systems <limits.h> would have given us this, but
446 * not on some systems (e.g. GNU/Hurd).
448 #ifndef PATH_MAX
449 #define PATH_MAX 4096
450 #endif
452 #ifndef NAME_MAX
453 #define NAME_MAX 255
454 #endif
456 typedef uintmax_t timestamp_t;
457 #define PRItime PRIuMAX
458 #define parse_timestamp strtoumax
459 #define TIME_MAX UINTMAX_MAX
460 #define TIME_MIN 0
462 #ifndef PATH_SEP
463 #define PATH_SEP ':'
464 #endif
466 #ifdef HAVE_PATHS_H
467 #include <paths.h>
468 #endif
469 #ifndef _PATH_DEFPATH
470 #define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
471 #endif
473 #ifndef platform_core_config
474 struct config_context;
475 static inline int noop_core_config(const char *var UNUSED,
476 const char *value UNUSED,
477 const struct config_context *ctx UNUSED,
478 void *cb UNUSED)
480 return 0;
482 #define platform_core_config noop_core_config
483 #endif
485 int lstat_cache_aware_rmdir(const char *path);
486 #if !defined(__MINGW32__) && !defined(_MSC_VER)
487 #define rmdir lstat_cache_aware_rmdir
488 #endif
490 #ifndef has_dos_drive_prefix
491 static inline int git_has_dos_drive_prefix(const char *path UNUSED)
493 return 0;
495 #define has_dos_drive_prefix git_has_dos_drive_prefix
496 #endif
498 #ifndef skip_dos_drive_prefix
499 static inline int git_skip_dos_drive_prefix(char **path UNUSED)
501 return 0;
503 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
504 #endif
506 static inline int git_is_dir_sep(int c)
508 return c == '/';
510 #ifndef is_dir_sep
511 #define is_dir_sep git_is_dir_sep
512 #endif
514 #ifndef offset_1st_component
515 static inline int git_offset_1st_component(const char *path)
517 return is_dir_sep(path[0]);
519 #define offset_1st_component git_offset_1st_component
520 #endif
522 #ifndef fspathcmp
523 #define fspathcmp git_fspathcmp
524 #endif
526 #ifndef fspathncmp
527 #define fspathncmp git_fspathncmp
528 #endif
530 #ifndef is_valid_path
531 #define is_valid_path(path) 1
532 #endif
534 #ifndef is_path_owned_by_current_user
536 #ifdef __TANDEM
537 #define ROOT_UID 65535
538 #else
539 #define ROOT_UID 0
540 #endif
543 * Do not use this function when
544 * (1) geteuid() did not say we are running as 'root', or
545 * (2) using this function will compromise the system.
547 * PORTABILITY WARNING:
548 * This code assumes uid_t is unsigned because that is what sudo does.
549 * If your uid_t type is signed and all your ids are positive then it
550 * should all work fine.
551 * If your version of sudo uses negative values for uid_t or it is
552 * buggy and return an overflowed value in SUDO_UID, then git might
553 * fail to grant access to your repository properly or even mistakenly
554 * grant access to someone else.
555 * In the unlikely scenario this happened to you, and that is how you
556 * got to this message, we would like to know about it; so sent us an
557 * email to git@vger.kernel.org indicating which platform you are
558 * using and which version of sudo, so we can improve this logic and
559 * maybe provide you with a patch that would prevent this issue again
560 * in the future.
562 static inline void extract_id_from_env(const char *env, uid_t *id)
564 const char *real_uid = getenv(env);
566 /* discard anything empty to avoid a more complex check below */
567 if (real_uid && *real_uid) {
568 char *endptr = NULL;
569 unsigned long env_id;
571 errno = 0;
572 /* silent overflow errors could trigger a bug here */
573 env_id = strtoul(real_uid, &endptr, 10);
574 if (!*endptr && !errno)
575 *id = env_id;
579 static inline int is_path_owned_by_current_uid(const char *path,
580 struct strbuf *report UNUSED)
582 struct stat st;
583 uid_t euid;
585 if (lstat(path, &st))
586 return 0;
588 euid = geteuid();
589 if (euid == ROOT_UID)
591 if (st.st_uid == ROOT_UID)
592 return 1;
593 else
594 extract_id_from_env("SUDO_UID", &euid);
597 return st.st_uid == euid;
600 #define is_path_owned_by_current_user is_path_owned_by_current_uid
601 #endif
603 #ifndef find_last_dir_sep
604 static inline char *git_find_last_dir_sep(const char *path)
606 return strrchr(path, '/');
608 #define find_last_dir_sep git_find_last_dir_sep
609 #endif
611 #ifndef has_dir_sep
612 static inline int git_has_dir_sep(const char *path)
614 return !!strchr(path, '/');
616 #define has_dir_sep(path) git_has_dir_sep(path)
617 #endif
619 #ifndef query_user_email
620 #define query_user_email() NULL
621 #endif
623 #ifdef __TANDEM
624 #include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
625 #include <floss.h(floss_getpwuid)>
626 #ifndef NSIG
628 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
629 * known, by detective work using kill -l as a list is all signals
630 * instead of signal.h where it should be.
632 # define NSIG 100
633 #endif
634 #endif
636 #if defined(__HP_cc) && (__HP_cc >= 61000)
637 #define NORETURN __attribute__((noreturn))
638 #define NORETURN_PTR
639 #elif defined(__GNUC__) && !defined(NO_NORETURN)
640 #define NORETURN __attribute__((__noreturn__))
641 #define NORETURN_PTR __attribute__((__noreturn__))
642 #elif defined(_MSC_VER)
643 #define NORETURN __declspec(noreturn)
644 #define NORETURN_PTR
645 #else
646 #define NORETURN
647 #define NORETURN_PTR
648 #ifndef __GNUC__
649 #ifndef __attribute__
650 #define __attribute__(x)
651 #endif
652 #endif
653 #endif
655 /* The sentinel attribute is valid from gcc version 4.0 */
656 #if defined(__GNUC__) && (__GNUC__ >= 4)
657 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
658 /* warn_unused_result exists as of gcc 3.4.0, but be lazy and check 4.0 */
659 #define RESULT_MUST_BE_USED __attribute__ ((warn_unused_result))
660 #else
661 #define LAST_ARG_MUST_BE_NULL
662 #define RESULT_MUST_BE_USED
663 #endif
666 * MAYBE_UNUSED marks a function parameter that may be unused, but
667 * whose use is not an error. It also can be used to annotate a
668 * function, a variable, or a type that may be unused.
670 * Depending on a configuration, all uses of such a thing may become
671 * #ifdef'ed away. Marking it with UNUSED would give a warning in a
672 * compilation where it is indeed used, and not marking it at all
673 * would give a warning in a compilation where it is unused. In such
674 * a case, MAYBE_UNUSED is the appropriate annotation to use.
676 #define MAYBE_UNUSED __attribute__((__unused__))
678 #include "compat/bswap.h"
680 #include "wrapper.h"
682 /* General helper functions */
683 NORETURN void usage(const char *err);
684 NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
685 NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
686 NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
687 int die_message(const char *err, ...) __attribute__((format (printf, 1, 2)));
688 int die_message_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
689 int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
690 int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
691 void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
692 void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
694 #ifndef NO_OPENSSL
695 #ifdef APPLE_COMMON_CRYPTO
696 #include "compat/apple-common-crypto.h"
697 #else
698 #include <openssl/evp.h>
699 #include <openssl/hmac.h>
700 #endif /* APPLE_COMMON_CRYPTO */
701 #include <openssl/x509v3.h>
702 #endif /* NO_OPENSSL */
704 #ifdef HAVE_OPENSSL_CSPRNG
705 #include <openssl/rand.h>
706 #endif
709 * Let callers be aware of the constant return value; this can help
710 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
711 * because other compilers may be confused by this.
713 #if defined(__GNUC__)
714 static inline int const_error(void)
716 return -1;
718 #define error(...) (error(__VA_ARGS__), const_error())
719 #define error_errno(...) (error_errno(__VA_ARGS__), const_error())
720 #endif
722 typedef void (*report_fn)(const char *, va_list params);
724 void set_die_routine(NORETURN_PTR report_fn routine);
725 report_fn get_die_message_routine(void);
726 void set_error_routine(report_fn routine);
727 report_fn get_error_routine(void);
728 void set_warn_routine(report_fn routine);
729 report_fn get_warn_routine(void);
730 void set_die_is_recursing_routine(int (*routine)(void));
733 * If the string "str" begins with the string found in "prefix", return true.
734 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
735 * the string right after the prefix).
737 * Otherwise, return false and leave "out" untouched.
739 * Examples:
741 * [extract branch name, fail if not a branch]
742 * if (!skip_prefix(ref, "refs/heads/", &branch)
743 * return -1;
745 * [skip prefix if present, otherwise use whole string]
746 * skip_prefix(name, "refs/heads/", &name);
748 static inline bool skip_prefix(const char *str, const char *prefix,
749 const char **out)
751 do {
752 if (!*prefix) {
753 *out = str;
754 return true;
756 } while (*str++ == *prefix++);
757 return false;
761 * Like skip_prefix, but promises never to read past "len" bytes of the input
762 * buffer, and returns the remaining number of bytes in "out" via "outlen".
764 static inline bool skip_prefix_mem(const char *buf, size_t len,
765 const char *prefix,
766 const char **out, size_t *outlen)
768 size_t prefix_len = strlen(prefix);
769 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
770 *out = buf + prefix_len;
771 *outlen = len - prefix_len;
772 return true;
774 return false;
778 * If buf ends with suffix, return true and subtract the length of the suffix
779 * from *len. Otherwise, return false and leave *len untouched.
781 static inline bool strip_suffix_mem(const char *buf, size_t *len,
782 const char *suffix)
784 size_t suflen = strlen(suffix);
785 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
786 return false;
787 *len -= suflen;
788 return true;
792 * If str ends with suffix, return true and set *len to the size of the string
793 * without the suffix. Otherwise, return false and set *len to the size of the
794 * string.
796 * Note that we do _not_ NUL-terminate str to the new length.
798 static inline bool strip_suffix(const char *str, const char *suffix,
799 size_t *len)
801 *len = strlen(str);
802 return strip_suffix_mem(str, len, suffix);
805 #define SWAP(a, b) do { \
806 void *_swap_a_ptr = &(a); \
807 void *_swap_b_ptr = &(b); \
808 unsigned char _swap_buffer[sizeof(a)]; \
809 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
810 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
811 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
812 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
813 } while (0)
815 #if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
817 #ifndef PROT_READ
818 #define PROT_READ 1
819 #define PROT_WRITE 2
820 #define MAP_PRIVATE 1
821 #endif
823 #define mmap git_mmap
824 #define munmap git_munmap
825 void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
826 int git_munmap(void *start, size_t length);
828 #else /* NO_MMAP || USE_WIN32_MMAP */
830 #include <sys/mman.h>
832 #endif /* NO_MMAP || USE_WIN32_MMAP */
834 #ifdef NO_MMAP
836 /* This value must be multiple of (pagesize * 2) */
837 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
839 #else /* NO_MMAP */
841 /* This value must be multiple of (pagesize * 2) */
842 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
843 (sizeof(void*) >= 8 \
844 ? 1 * 1024 * 1024 * 1024 \
845 : 32 * 1024 * 1024)
847 #endif /* NO_MMAP */
849 #ifndef MAP_FAILED
850 #define MAP_FAILED ((void *)-1)
851 #endif
853 #ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
854 #define on_disk_bytes(st) ((st).st_size)
855 #else
856 #define on_disk_bytes(st) ((st).st_blocks * 512)
857 #endif
859 #ifdef NEEDS_MODE_TRANSLATION
860 #undef S_IFMT
861 #undef S_IFREG
862 #undef S_IFDIR
863 #undef S_IFLNK
864 #undef S_IFBLK
865 #undef S_IFCHR
866 #undef S_IFIFO
867 #undef S_IFSOCK
868 #define S_IFMT 0170000
869 #define S_IFREG 0100000
870 #define S_IFDIR 0040000
871 #define S_IFLNK 0120000
872 #define S_IFBLK 0060000
873 #define S_IFCHR 0020000
874 #define S_IFIFO 0010000
875 #define S_IFSOCK 0140000
876 #ifdef stat
877 #undef stat
878 #endif
879 #define stat(path, buf) git_stat(path, buf)
880 int git_stat(const char *, struct stat *);
881 #ifdef fstat
882 #undef fstat
883 #endif
884 #define fstat(fd, buf) git_fstat(fd, buf)
885 int git_fstat(int, struct stat *);
886 #ifdef lstat
887 #undef lstat
888 #endif
889 #define lstat(path, buf) git_lstat(path, buf)
890 int git_lstat(const char *, struct stat *);
891 #endif
893 #define DEFAULT_PACKED_GIT_LIMIT \
894 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
896 #ifdef NO_PREAD
897 #define pread git_pread
898 ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
899 #endif
901 #ifdef NO_SETENV
902 #define setenv gitsetenv
903 int gitsetenv(const char *, const char *, int);
904 #endif
906 #ifdef NO_MKDTEMP
907 #define mkdtemp gitmkdtemp
908 char *gitmkdtemp(char *);
909 #endif
911 #ifdef NO_UNSETENV
912 #define unsetenv gitunsetenv
913 int gitunsetenv(const char *);
914 #endif
916 #ifdef NO_STRCASESTR
917 #define strcasestr gitstrcasestr
918 char *gitstrcasestr(const char *haystack, const char *needle);
919 #endif
921 #ifdef NO_STRLCPY
922 #define strlcpy gitstrlcpy
923 size_t gitstrlcpy(char *, const char *, size_t);
924 #endif
926 #ifdef NO_STRTOUMAX
927 #define strtoumax gitstrtoumax
928 uintmax_t gitstrtoumax(const char *, char **, int);
929 #define strtoimax gitstrtoimax
930 intmax_t gitstrtoimax(const char *, char **, int);
931 #endif
933 #ifdef NO_HSTRERROR
934 #define hstrerror githstrerror
935 const char *githstrerror(int herror);
936 #endif
938 #ifdef NO_MEMMEM
939 #define memmem gitmemmem
940 void *gitmemmem(const void *haystack, size_t haystacklen,
941 const void *needle, size_t needlelen);
942 #endif
944 #ifdef OVERRIDE_STRDUP
945 #ifdef strdup
946 #undef strdup
947 #endif
948 #define strdup gitstrdup
949 char *gitstrdup(const char *s);
950 #endif
952 #ifdef NO_GETPAGESIZE
953 #define getpagesize() sysconf(_SC_PAGESIZE)
954 #endif
956 #ifndef O_CLOEXEC
957 #define O_CLOEXEC 0
958 #endif
960 #ifdef FREAD_READS_DIRECTORIES
961 # if !defined(SUPPRESS_FOPEN_REDEFINITION)
962 # ifdef fopen
963 # undef fopen
964 # endif
965 # define fopen(a,b) git_fopen(a,b)
966 # endif
967 FILE *git_fopen(const char*, const char*);
968 #endif
970 #ifdef SNPRINTF_RETURNS_BOGUS
971 #ifdef snprintf
972 #undef snprintf
973 #endif
974 #define snprintf git_snprintf
975 int git_snprintf(char *str, size_t maxsize,
976 const char *format, ...);
977 #ifdef vsnprintf
978 #undef vsnprintf
979 #endif
980 #define vsnprintf git_vsnprintf
981 int git_vsnprintf(char *str, size_t maxsize,
982 const char *format, va_list ap);
983 #endif
985 #ifdef OPEN_RETURNS_EINTR
986 #undef open
987 #define open git_open_with_retry
988 int git_open_with_retry(const char *path, int flag, ...);
989 #endif
991 #ifdef __GLIBC_PREREQ
992 #if __GLIBC_PREREQ(2, 1)
993 #define HAVE_STRCHRNUL
994 #endif
995 #endif
997 #ifndef HAVE_STRCHRNUL
998 #define strchrnul gitstrchrnul
999 static inline char *gitstrchrnul(const char *s, int c)
1001 while (*s && *s != c)
1002 s++;
1003 return (char *)s;
1005 #endif
1007 #ifdef NO_INET_PTON
1008 int inet_pton(int af, const char *src, void *dst);
1009 #endif
1011 #ifdef NO_INET_NTOP
1012 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
1013 #endif
1015 #ifdef NO_PTHREADS
1016 #define atexit git_atexit
1017 int git_atexit(void (*handler)(void));
1018 #endif
1020 static inline size_t st_add(size_t a, size_t b)
1022 if (unsigned_add_overflows(a, b))
1023 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
1024 (uintmax_t)a, (uintmax_t)b);
1025 return a + b;
1027 #define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
1028 #define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
1030 static inline size_t st_mult(size_t a, size_t b)
1032 if (unsigned_mult_overflows(a, b))
1033 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
1034 (uintmax_t)a, (uintmax_t)b);
1035 return a * b;
1038 static inline size_t st_sub(size_t a, size_t b)
1040 if (a < b)
1041 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
1042 (uintmax_t)a, (uintmax_t)b);
1043 return a - b;
1046 static inline size_t st_left_shift(size_t a, unsigned shift)
1048 if (unsigned_left_shift_overflows(a, shift))
1049 die("size_t overflow: %"PRIuMAX" << %u",
1050 (uintmax_t)a, shift);
1051 return a << shift;
1054 static inline unsigned long cast_size_t_to_ulong(size_t a)
1056 if (a != (unsigned long)a)
1057 die("object too large to read on this platform: %"
1058 PRIuMAX" is cut off to %lu",
1059 (uintmax_t)a, (unsigned long)a);
1060 return (unsigned long)a;
1063 static inline uint32_t cast_size_t_to_uint32_t(size_t a)
1065 if (a != (uint32_t)a)
1066 die("object too large to read on this platform: %"
1067 PRIuMAX" is cut off to %u",
1068 (uintmax_t)a, (uint32_t)a);
1069 return (uint32_t)a;
1072 static inline int cast_size_t_to_int(size_t a)
1074 if (a > INT_MAX)
1075 die("number too large to represent as int on this platform: %"PRIuMAX,
1076 (uintmax_t)a);
1077 return (int)a;
1081 * Limit size of IO chunks, because huge chunks only cause pain. OS X
1082 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
1083 * the absence of bugs, large chunks can result in bad latencies when
1084 * you decide to kill the process.
1086 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
1087 * that is smaller than that, clip it to SSIZE_MAX, as a call to
1088 * read(2) or write(2) larger than that is allowed to fail. As the last
1089 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
1090 * to override this, if the definition of SSIZE_MAX given by the platform
1091 * is broken.
1093 #ifndef MAX_IO_SIZE
1094 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
1095 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
1096 # define MAX_IO_SIZE SSIZE_MAX
1097 # else
1098 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
1099 # endif
1100 #endif
1102 #ifdef HAVE_ALLOCA_H
1103 # include <alloca.h>
1104 # define xalloca(size) (alloca(size))
1105 # define xalloca_free(p) do {} while (0)
1106 #else
1107 # define xalloca(size) (xmalloc(size))
1108 # define xalloca_free(p) (free(p))
1109 #endif
1112 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
1113 * that ptr is used twice, so don't pass e.g. ptr++.
1115 #define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
1117 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
1118 #define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
1119 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
1121 #define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
1122 BARF_UNLESS_COPYABLE((dst), (src)))
1123 static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
1125 if (n)
1126 memcpy(dst, src, st_mult(size, n));
1129 #define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
1130 BARF_UNLESS_COPYABLE((dst), (src)))
1131 static inline void move_array(void *dst, const void *src, size_t n, size_t size)
1133 if (n)
1134 memmove(dst, src, st_mult(size, n));
1137 #define DUP_ARRAY(dst, src, n) do { \
1138 size_t dup_array_n_ = (n); \
1139 COPY_ARRAY(ALLOC_ARRAY((dst), dup_array_n_), (src), dup_array_n_); \
1140 } while (0)
1143 * These functions help you allocate structs with flex arrays, and copy
1144 * the data directly into the array. For example, if you had:
1146 * struct foo {
1147 * int bar;
1148 * char name[FLEX_ARRAY];
1149 * };
1151 * you can do:
1153 * struct foo *f;
1154 * FLEX_ALLOC_MEM(f, name, src, len);
1156 * to allocate a "foo" with the contents of "src" in the "name" field.
1157 * The resulting struct is automatically zero'd, and the flex-array field
1158 * is NUL-terminated (whether the incoming src buffer was or not).
1160 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
1161 * but do want to store a pointer to some extra data in the same allocated
1162 * block. For example, if you have:
1164 * struct foo {
1165 * char *name;
1166 * int bar;
1167 * };
1169 * you can do:
1171 * struct foo *f;
1172 * FLEXPTR_ALLOC_STR(f, name, src);
1174 * and "name" will point to a block of memory after the struct, which will be
1175 * freed along with the struct (but the pointer can be repointed anywhere).
1177 * The *_STR variants accept a string parameter rather than a ptr/len
1178 * combination.
1180 * Note that these macros will evaluate the first parameter multiple
1181 * times, and it must be assignable as an lvalue.
1183 #define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
1184 size_t flex_array_len_ = (len); \
1185 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1186 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
1187 } while (0)
1188 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
1189 size_t flex_array_len_ = (len); \
1190 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1191 memcpy((x) + 1, (buf), flex_array_len_); \
1192 (x)->ptrname = (void *)((x)+1); \
1193 } while(0)
1194 #define FLEX_ALLOC_STR(x, flexname, str) \
1195 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
1196 #define FLEXPTR_ALLOC_STR(x, ptrname, str) \
1197 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
1199 #define alloc_nr(x) (((x)+16)*3/2)
1202 * Dynamically growing an array using realloc() is error prone and boring.
1204 * Define your array with:
1206 * - a pointer (`item`) that points at the array, initialized to `NULL`
1207 * (although please name the variable based on its contents, not on its
1208 * type);
1210 * - an integer variable (`alloc`) that keeps track of how big the current
1211 * allocation is, initialized to `0`;
1213 * - another integer variable (`nr`) to keep track of how many elements the
1214 * array currently has, initialized to `0`.
1216 * Then before adding `n`th element to the item, call `ALLOC_GROW(item, n,
1217 * alloc)`. This ensures that the array can hold at least `n` elements by
1218 * calling `realloc(3)` and adjusting `alloc` variable.
1220 * ------------
1221 * sometype *item;
1222 * size_t nr;
1223 * size_t alloc
1225 * for (i = 0; i < nr; i++)
1226 * if (we like item[i] already)
1227 * return;
1229 * // we did not like any existing one, so add one
1230 * ALLOC_GROW(item, nr + 1, alloc);
1231 * item[nr++] = value you like;
1232 * ------------
1234 * You are responsible for updating the `nr` variable.
1236 * If you need to specify the number of elements to allocate explicitly
1237 * then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`.
1239 * Consider using ALLOC_GROW_BY instead of ALLOC_GROW as it has some
1240 * added niceties.
1242 * DO NOT USE any expression with side-effect for 'x', 'nr', or 'alloc'.
1244 #define ALLOC_GROW(x, nr, alloc) \
1245 do { \
1246 if ((nr) > alloc) { \
1247 if (alloc_nr(alloc) < (nr)) \
1248 alloc = (nr); \
1249 else \
1250 alloc = alloc_nr(alloc); \
1251 REALLOC_ARRAY(x, alloc); \
1253 } while (0)
1256 * Similar to ALLOC_GROW but handles updating of the nr value and
1257 * zeroing the bytes of the newly-grown array elements.
1259 * DO NOT USE any expression with side-effect for any of the
1260 * arguments.
1262 #define ALLOC_GROW_BY(x, nr, increase, alloc) \
1263 do { \
1264 if (increase) { \
1265 size_t new_nr = nr + (increase); \
1266 if (new_nr < nr) \
1267 BUG("negative growth in ALLOC_GROW_BY"); \
1268 ALLOC_GROW(x, new_nr, alloc); \
1269 memset((x) + nr, 0, sizeof(*(x)) * (increase)); \
1270 nr = new_nr; \
1272 } while (0)
1274 static inline char *xstrdup_or_null(const char *str)
1276 return str ? xstrdup(str) : NULL;
1279 static inline size_t xsize_t(off_t len)
1281 if (len < 0 || (uintmax_t) len > SIZE_MAX)
1282 die("Cannot handle files this big");
1283 return (size_t) len;
1286 #ifndef HOST_NAME_MAX
1287 #define HOST_NAME_MAX 256
1288 #endif
1290 #include "sane-ctype.h"
1293 * Like skip_prefix, but compare case-insensitively. Note that the comparison
1294 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
1295 * locale-specific conversions).
1297 static inline int skip_iprefix(const char *str, const char *prefix,
1298 const char **out)
1300 do {
1301 if (!*prefix) {
1302 *out = str;
1303 return 1;
1305 } while (tolower(*str++) == tolower(*prefix++));
1306 return 0;
1310 * Like skip_prefix_mem, but compare case-insensitively. Note that the
1311 * comparison is done via tolower(), so it is strictly ASCII (no multi-byte
1312 * characters or locale-specific conversions).
1314 static inline int skip_iprefix_mem(const char *buf, size_t len,
1315 const char *prefix,
1316 const char **out, size_t *outlen)
1318 do {
1319 if (!*prefix) {
1320 *out = buf;
1321 *outlen = len;
1322 return 1;
1324 } while (len-- > 0 && tolower(*buf++) == tolower(*prefix++));
1325 return 0;
1328 static inline int strtoul_ui(char const *s, int base, unsigned int *result)
1330 unsigned long ul;
1331 char *p;
1333 errno = 0;
1334 /* negative values would be accepted by strtoul */
1335 if (strchr(s, '-'))
1336 return -1;
1337 ul = strtoul(s, &p, base);
1338 if (errno || *p || p == s || (unsigned int) ul != ul)
1339 return -1;
1340 *result = ul;
1341 return 0;
1344 static inline int strtol_i(char const *s, int base, int *result)
1346 long ul;
1347 char *p;
1349 errno = 0;
1350 ul = strtol(s, &p, base);
1351 if (errno || *p || p == s || (int) ul != ul)
1352 return -1;
1353 *result = ul;
1354 return 0;
1357 void git_stable_qsort(void *base, size_t nmemb, size_t size,
1358 int(*compar)(const void *, const void *));
1359 #ifdef INTERNAL_QSORT
1360 #define qsort git_stable_qsort
1361 #endif
1363 #define QSORT(base, n, compar) sane_qsort((base), (n), sizeof(*(base)), compar)
1364 static inline void sane_qsort(void *base, size_t nmemb, size_t size,
1365 int(*compar)(const void *, const void *))
1367 if (nmemb > 1)
1368 qsort(base, nmemb, size, compar);
1371 #define STABLE_QSORT(base, n, compar) \
1372 git_stable_qsort((base), (n), sizeof(*(base)), compar)
1374 #ifndef HAVE_ISO_QSORT_S
1375 int git_qsort_s(void *base, size_t nmemb, size_t size,
1376 int (*compar)(const void *, const void *, void *), void *ctx);
1377 #define qsort_s git_qsort_s
1378 #endif
1380 #define QSORT_S(base, n, compar, ctx) do { \
1381 if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
1382 BUG("qsort_s() failed"); \
1383 } while (0)
1385 #ifndef REG_STARTEND
1386 #error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
1387 #endif
1389 static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
1390 size_t nmatch, regmatch_t pmatch[], int eflags)
1392 assert(nmatch > 0 && pmatch);
1393 pmatch[0].rm_so = 0;
1394 pmatch[0].rm_eo = size;
1395 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
1398 #ifdef USE_ENHANCED_BASIC_REGULAR_EXPRESSIONS
1399 int git_regcomp(regex_t *preg, const char *pattern, int cflags);
1400 #define regcomp git_regcomp
1401 #endif
1403 #ifndef DIR_HAS_BSD_GROUP_SEMANTICS
1404 # define FORCE_DIR_SET_GID S_ISGID
1405 #else
1406 # define FORCE_DIR_SET_GID 0
1407 #endif
1409 #ifdef NO_NSEC
1410 #undef USE_NSEC
1411 #define ST_CTIME_NSEC(st) 0
1412 #define ST_MTIME_NSEC(st) 0
1413 #else
1414 #ifdef USE_ST_TIMESPEC
1415 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
1416 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
1417 #else
1418 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
1419 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
1420 #endif
1421 #endif
1423 #ifdef UNRELIABLE_FSTAT
1424 #define fstat_is_reliable() 0
1425 #else
1426 #define fstat_is_reliable() 1
1427 #endif
1429 #ifndef va_copy
1431 * Since an obvious implementation of va_list would be to make it a
1432 * pointer into the stack frame, a simple assignment will work on
1433 * many systems. But let's try to be more portable.
1435 #ifdef __va_copy
1436 #define va_copy(dst, src) __va_copy(dst, src)
1437 #else
1438 #define va_copy(dst, src) ((dst) = (src))
1439 #endif
1440 #endif
1442 /* usage.c: only to be used for testing BUG() implementation (see test-tool) */
1443 extern int BUG_exit_code;
1445 /* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
1446 extern int bug_called_must_BUG;
1448 __attribute__((format (printf, 3, 4))) NORETURN
1449 void BUG_fl(const char *file, int line, const char *fmt, ...);
1450 #define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
1451 __attribute__((format (printf, 3, 4)))
1452 void bug_fl(const char *file, int line, const char *fmt, ...);
1453 #define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1454 #define BUG_if_bug(...) do { \
1455 if (bug_called_must_BUG) \
1456 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1457 } while (0)
1459 #ifndef FSYNC_METHOD_DEFAULT
1460 #ifdef __APPLE__
1461 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1462 #else
1463 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1464 #endif
1465 #endif
1467 #ifndef SHELL_PATH
1468 # define SHELL_PATH "/bin/sh"
1469 #endif
1471 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
1472 static inline void git_flockfile(FILE *fh UNUSED)
1474 ; /* nothing */
1476 static inline void git_funlockfile(FILE *fh UNUSED)
1478 ; /* nothing */
1480 #undef flockfile
1481 #undef funlockfile
1482 #undef getc_unlocked
1483 #define flockfile(fh) git_flockfile(fh)
1484 #define funlockfile(fh) git_funlockfile(fh)
1485 #define getc_unlocked(fh) getc(fh)
1486 #endif
1488 #ifdef FILENO_IS_A_MACRO
1489 int git_fileno(FILE *stream);
1490 # ifndef COMPAT_CODE_FILENO
1491 # undef fileno
1492 # define fileno(p) git_fileno(p)
1493 # endif
1494 #endif
1496 #ifdef NEED_ACCESS_ROOT_HANDLER
1497 int git_access(const char *path, int mode);
1498 # ifndef COMPAT_CODE_ACCESS
1499 # ifdef access
1500 # undef access
1501 # endif
1502 # define access(path, mode) git_access(path, mode)
1503 # endif
1504 #endif
1507 * Our code often opens a path to an optional file, to work on its
1508 * contents when we can successfully open it. We can ignore a failure
1509 * to open if such an optional file does not exist, but we do want to
1510 * report a failure in opening for other reasons (e.g. we got an I/O
1511 * error, or the file is there, but we lack the permission to open).
1513 * Call this function after seeing an error from open() or fopen() to
1514 * see if the errno indicates a missing file that we can safely ignore.
1516 static inline int is_missing_file_error(int errno_)
1518 return (errno_ == ENOENT || errno_ == ENOTDIR);
1521 int cmd_main(int, const char **);
1524 * Intercept all calls to exit() and route them to trace2 to
1525 * optionally emit a message before calling the real exit().
1527 int common_exit(const char *file, int line, int code);
1528 #define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
1531 * You can mark a stack variable with UNLEAK(var) to avoid it being
1532 * reported as a leak by tools like LSAN or valgrind. The argument
1533 * should generally be the variable itself (not its address and not what
1534 * it points to). It's safe to use this on pointers which may already
1535 * have been freed, or on pointers which may still be in use.
1537 * Use this _only_ for a variable that leaks by going out of scope at
1538 * program exit (so only from cmd_* functions or their direct helpers).
1539 * Normal functions, especially those which may be called multiple
1540 * times, should actually free their memory. This is only meant as
1541 * an annotation, and does nothing in non-leak-checking builds.
1543 #ifdef SUPPRESS_ANNOTATED_LEAKS
1544 void unleak_memory(const void *ptr, size_t len);
1545 #define UNLEAK(var) unleak_memory(&(var), sizeof(var))
1546 #else
1547 #define UNLEAK(var) do {} while (0)
1548 #endif
1550 #define z_const
1551 #include <zlib.h>
1553 #if ZLIB_VERNUM < 0x1290
1555 * This is uncompress2, which is only available in zlib >= 1.2.9
1556 * (released as of early 2017). See compat/zlib-uncompress2.c.
1558 int uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
1559 uLong *sourceLen);
1560 #endif
1563 * This include must come after system headers, since it introduces macros that
1564 * replace system names.
1566 #include "banned.h"
1569 * container_of - Get the address of an object containing a field.
1571 * @ptr: pointer to the field.
1572 * @type: type of the object.
1573 * @member: name of the field within the object.
1575 #define container_of(ptr, type, member) \
1576 ((type *) ((char *)(ptr) - offsetof(type, member)))
1579 * helper function for `container_of_or_null' to avoid multiple
1580 * evaluation of @ptr
1582 static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1584 return ptr ? (char *)ptr - offset : NULL;
1588 * like `container_of', but allows returned value to be NULL
1590 #define container_of_or_null(ptr, type, member) \
1591 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1594 * like offsetof(), but takes a pointer to a variable of type which
1595 * contains @member, instead of a specified type.
1596 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1597 * everywhere.
1599 #if defined(__GNUC__) /* clang sets this, too */
1600 #define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1601 #else /* !__GNUC__ */
1602 #define OFFSETOF_VAR(ptr, member) \
1603 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1604 #endif /* !__GNUC__ */
1606 #endif