1 #ifndef GIT_COMPAT_UTIL_H
2 #define GIT_COMPAT_UTIL_H
4 #if __STDC_VERSION__ - 0 < 199901L
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."
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.
26 #include "compat/posix.h"
30 #if defined(__GNUC__) || defined(__clang__)
31 # define PRAGMA(pragma) _Pragma(#pragma)
32 # define DISABLE_WARNING(warning) PRAGMA(GCC diagnostic ignored #warning)
34 # define DISABLE_WARNING(warning)
37 #ifdef DISABLE_SIGN_COMPARE_WARNINGS
38 DISABLE_WARNING(-Wsign
-compare
)
43 * See if our compiler is known to support flexible array members.
47 * Check vendor specific quirks first, before checking the
48 * __STDC_VERSION__, as vendor compilers can lie and we need to be
49 * able to work them around. Note that by not defining FLEX_ARRAY
50 * here, we can fall back to use the "safer but a bit wasteful" one
53 #if defined(__SUNPRO_C) && (__SUNPRO_C <= 0x580)
54 #elif defined(__GNUC__)
56 # define FLEX_ARRAY /* empty */
58 # define FLEX_ARRAY 0 /* older GNU extension */
60 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
61 # define FLEX_ARRAY /* empty */
65 * Otherwise, default to safer but a bit wasteful traditional style
74 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
75 * @cond: the compile-time condition which must be true.
77 * Your compile will fail if the condition isn't true, or can't be evaluated
78 * by the compiler. This can be used in an expression: its value is "0".
81 * #define foo_to_char(foo) \
83 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
85 #define BUILD_ASSERT_OR_ZERO(cond) \
86 (sizeof(char [1 - 2*!(cond)]) - 1)
88 #if GIT_GNUC_PREREQ(3, 1)
89 /* &arr[0] degrades to a pointer: a different type from an array */
90 # define BARF_UNLESS_AN_ARRAY(arr) \
91 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
92 __typeof__(&(arr)[0])))
93 # define BARF_UNLESS_COPYABLE(dst, src) \
94 BUILD_ASSERT_OR_ZERO(__builtin_types_compatible_p(__typeof__(*(dst)), \
97 # define BARF_UNLESS_SIGNED(var) BUILD_ASSERT_OR_ZERO(((__typeof__(var)) -1) < 0)
98 # define BARF_UNLESS_UNSIGNED(var) BUILD_ASSERT_OR_ZERO(((__typeof__(var)) -1) > 0)
100 # define BARF_UNLESS_AN_ARRAY(arr) 0
101 # define BARF_UNLESS_COPYABLE(dst, src) \
102 BUILD_ASSERT_OR_ZERO(0 ? ((*(dst) = *(src)), 0) : \
103 sizeof(*(dst)) == sizeof(*(src)))
105 # define BARF_UNLESS_SIGNED(var) 0
106 # define BARF_UNLESS_UNSIGNED(var) 0
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))
156 #define TYPEOF(x) (__typeof__(x))
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 #if defined(NO_UNIX_SOCKETS) || !defined(GIT_WINDOWS_NATIVE)
170 static inline int _have_unix_sockets(void)
172 #if defined(NO_UNIX_SOCKETS)
178 #define have_unix_sockets _have_unix_sockets
181 /* Used by compat/win32/path-utils.h, and more */
182 static inline int is_xplatform_dir_sep(int c
)
184 return c
== '/' || c
== '\\';
187 #if defined(__CYGWIN__)
188 #include "compat/win32/path-utils.h"
190 #if defined(__MINGW32__)
191 /* pull in Windows compatibility stuff */
192 #include "compat/win32/path-utils.h"
193 #include "compat/mingw.h"
194 #elif defined(_MSC_VER)
195 #include "compat/win32/path-utils.h"
196 #include "compat/msvc.h"
199 /* used on Mac OS X */
200 #ifdef PRECOMPOSE_UNICODE
201 #include "compat/precompose_utf8.h"
203 static inline const char *precompose_argv_prefix(int argc UNUSED
,
204 const char **argv UNUSED
,
209 static inline const char *precompose_string_if_needed(const char *in
)
214 #define probe_utf8_pathname_composition()
219 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
220 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
221 #include <AvailabilityMacros.h>
222 #undef DEPRECATED_ATTRIBUTE
223 #define DEPRECATED_ATTRIBUTE
224 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
226 #include <openssl/ssl.h>
227 #include <openssl/err.h>
231 # include <sys/sysinfo.h>
241 #ifndef _PATH_DEFPATH
242 #define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
245 #ifndef platform_core_config
246 struct config_context
;
247 static inline int noop_core_config(const char *var UNUSED
,
248 const char *value UNUSED
,
249 const struct config_context
*ctx UNUSED
,
254 #define platform_core_config noop_core_config
257 #ifndef has_dos_drive_prefix
258 static inline int git_has_dos_drive_prefix(const char *path UNUSED
)
262 #define has_dos_drive_prefix git_has_dos_drive_prefix
265 #ifndef skip_dos_drive_prefix
266 static inline int git_skip_dos_drive_prefix(char **path UNUSED
)
270 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
273 static inline int git_is_dir_sep(int c
)
278 #define is_dir_sep git_is_dir_sep
281 #ifndef offset_1st_component
282 static inline int git_offset_1st_component(const char *path
)
284 return is_dir_sep(path
[0]);
286 #define offset_1st_component git_offset_1st_component
290 #define fspathcmp git_fspathcmp
294 #define fspathncmp git_fspathncmp
297 #ifndef is_valid_path
298 #define is_valid_path(path) 1
301 #ifndef is_path_owned_by_current_user
304 #define ROOT_UID 65535
310 * Do not use this function when
311 * (1) geteuid() did not say we are running as 'root', or
312 * (2) using this function will compromise the system.
314 * PORTABILITY WARNING:
315 * This code assumes uid_t is unsigned because that is what sudo does.
316 * If your uid_t type is signed and all your ids are positive then it
317 * should all work fine.
318 * If your version of sudo uses negative values for uid_t or it is
319 * buggy and return an overflowed value in SUDO_UID, then git might
320 * fail to grant access to your repository properly or even mistakenly
321 * grant access to someone else.
322 * In the unlikely scenario this happened to you, and that is how you
323 * got to this message, we would like to know about it; so sent us an
324 * email to git@vger.kernel.org indicating which platform you are
325 * using and which version of sudo, so we can improve this logic and
326 * maybe provide you with a patch that would prevent this issue again
329 static inline void extract_id_from_env(const char *env
, uid_t
*id
)
331 const char *real_uid
= getenv(env
);
333 /* discard anything empty to avoid a more complex check below */
334 if (real_uid
&& *real_uid
) {
336 unsigned long env_id
;
339 /* silent overflow errors could trigger a bug here */
340 env_id
= strtoul(real_uid
, &endptr
, 10);
341 if (!*endptr
&& !errno
)
346 static inline int is_path_owned_by_current_uid(const char *path
,
347 struct strbuf
*report UNUSED
)
352 if (lstat(path
, &st
))
356 if (euid
== ROOT_UID
)
358 if (st
.st_uid
== ROOT_UID
)
361 extract_id_from_env("SUDO_UID", &euid
);
364 return st
.st_uid
== euid
;
367 #define is_path_owned_by_current_user is_path_owned_by_current_uid
370 #ifndef find_last_dir_sep
371 static inline char *git_find_last_dir_sep(const char *path
)
373 return strrchr(path
, '/');
375 #define find_last_dir_sep git_find_last_dir_sep
379 static inline int git_has_dir_sep(const char *path
)
381 return !!strchr(path
, '/');
383 #define has_dir_sep(path) git_has_dir_sep(path)
386 #ifndef query_user_email
387 #define query_user_email() NULL
391 #include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
392 #include <floss.h(floss_getpwuid)>
395 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
396 * known, by detective work using kill -l as a list is all signals
397 * instead of signal.h where it should be.
403 #if defined(__HP_cc) && (__HP_cc >= 61000)
404 #define NORETURN __attribute__((noreturn))
406 #elif defined(__GNUC__) && !defined(NO_NORETURN)
407 #define NORETURN __attribute__((__noreturn__))
408 #define NORETURN_PTR __attribute__((__noreturn__))
409 #elif defined(_MSC_VER)
410 #define NORETURN __declspec(noreturn)
416 #ifndef __attribute__
417 #define __attribute__(x)
422 /* The sentinel attribute is valid from gcc version 4.0 */
423 #if defined(__GNUC__) && (__GNUC__ >= 4)
424 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
425 /* warn_unused_result exists as of gcc 3.4.0, but be lazy and check 4.0 */
426 #define RESULT_MUST_BE_USED __attribute__ ((warn_unused_result))
428 #define LAST_ARG_MUST_BE_NULL
429 #define RESULT_MUST_BE_USED
433 * MAYBE_UNUSED marks a function parameter that may be unused, but
434 * whose use is not an error. It also can be used to annotate a
435 * function, a variable, or a type that may be unused.
437 * Depending on a configuration, all uses of such a thing may become
438 * #ifdef'ed away. Marking it with UNUSED would give a warning in a
439 * compilation where it is indeed used, and not marking it at all
440 * would give a warning in a compilation where it is unused. In such
441 * a case, MAYBE_UNUSED is the appropriate annotation to use.
443 #define MAYBE_UNUSED __attribute__((__unused__))
445 #include "compat/bswap.h"
449 /* General helper functions */
450 NORETURN
void usage(const char *err
);
451 NORETURN
void usagef(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
452 NORETURN
void die(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
453 NORETURN
void die_errno(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
454 int die_message(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
455 int die_message_errno(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
456 int error(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
457 int error_errno(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
458 void warning(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
459 void warning_errno(const char *err
, ...) __attribute__((format (printf
, 1, 2)));
461 void show_usage_if_asked(int ac
, const char **av
, const char *err
);
463 NORETURN
void you_still_use_that(const char *command_name
);
466 #ifdef APPLE_COMMON_CRYPTO
467 #include "compat/apple-common-crypto.h"
469 #include <openssl/evp.h>
470 #include <openssl/hmac.h>
471 #endif /* APPLE_COMMON_CRYPTO */
472 #include <openssl/x509v3.h>
473 #endif /* NO_OPENSSL */
475 #ifdef HAVE_OPENSSL_CSPRNG
476 #include <openssl/rand.h>
480 * Let callers be aware of the constant return value; this can help
481 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
482 * because other compilers may be confused by this.
484 #if defined(__GNUC__)
485 static inline int const_error(void)
489 #define error(...) (error(__VA_ARGS__), const_error())
490 #define error_errno(...) (error_errno(__VA_ARGS__), const_error())
493 typedef void (*report_fn
)(const char *, va_list params
);
495 void set_die_routine(NORETURN_PTR report_fn routine
);
496 report_fn
get_die_message_routine(void);
497 void set_error_routine(report_fn routine
);
498 report_fn
get_error_routine(void);
499 void set_warn_routine(report_fn routine
);
500 report_fn
get_warn_routine(void);
501 void set_die_is_recursing_routine(int (*routine
)(void));
504 * If the string "str" begins with the string found in "prefix", return true.
505 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
506 * the string right after the prefix).
508 * Otherwise, return false and leave "out" untouched.
512 * [extract branch name, fail if not a branch]
513 * if (!skip_prefix(ref, "refs/heads/", &branch)
516 * [skip prefix if present, otherwise use whole string]
517 * skip_prefix(name, "refs/heads/", &name);
519 static inline bool skip_prefix(const char *str
, const char *prefix
,
527 } while (*str
++ == *prefix
++);
532 * Like skip_prefix, but promises never to read past "len" bytes of the input
533 * buffer, and returns the remaining number of bytes in "out" via "outlen".
535 static inline bool skip_prefix_mem(const char *buf
, size_t len
,
537 const char **out
, size_t *outlen
)
539 size_t prefix_len
= strlen(prefix
);
540 if (prefix_len
<= len
&& !memcmp(buf
, prefix
, prefix_len
)) {
541 *out
= buf
+ prefix_len
;
542 *outlen
= len
- prefix_len
;
549 * If buf ends with suffix, return true and subtract the length of the suffix
550 * from *len. Otherwise, return false and leave *len untouched.
552 static inline bool strip_suffix_mem(const char *buf
, size_t *len
,
555 size_t suflen
= strlen(suffix
);
556 if (*len
< suflen
|| memcmp(buf
+ (*len
- suflen
), suffix
, suflen
))
563 * If str ends with suffix, return true and set *len to the size of the string
564 * without the suffix. Otherwise, return false and set *len to the size of the
567 * Note that we do _not_ NUL-terminate str to the new length.
569 static inline bool strip_suffix(const char *str
, const char *suffix
,
573 return strip_suffix_mem(str
, len
, suffix
);
576 #define SWAP(a, b) do { \
577 void *_swap_a_ptr = &(a); \
578 void *_swap_b_ptr = &(b); \
579 unsigned char _swap_buffer[sizeof(a)]; \
580 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
581 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
582 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
583 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
588 /* This value must be multiple of (pagesize * 2) */
589 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
593 /* This value must be multiple of (pagesize * 2) */
594 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
595 (sizeof(void*) >= 8 \
596 ? 1 * 1024 * 1024 * 1024 \
601 #ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
602 #define on_disk_bytes(st) ((st).st_size)
604 #define on_disk_bytes(st) ((st).st_blocks * 512)
607 #define DEFAULT_PACKED_GIT_LIMIT \
608 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
610 int git_open_cloexec(const char *name
, int flags
);
611 #define git_open(name) git_open_cloexec(name, O_RDONLY)
613 static inline size_t st_add(size_t a
, size_t b
)
615 if (unsigned_add_overflows(a
, b
))
616 die("size_t overflow: %"PRIuMAX
" + %"PRIuMAX
,
617 (uintmax_t)a
, (uintmax_t)b
);
620 #define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
621 #define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
623 static inline size_t st_mult(size_t a
, size_t b
)
625 if (unsigned_mult_overflows(a
, b
))
626 die("size_t overflow: %"PRIuMAX
" * %"PRIuMAX
,
627 (uintmax_t)a
, (uintmax_t)b
);
631 static inline size_t st_sub(size_t a
, size_t b
)
634 die("size_t underflow: %"PRIuMAX
" - %"PRIuMAX
,
635 (uintmax_t)a
, (uintmax_t)b
);
639 static inline size_t st_left_shift(size_t a
, unsigned shift
)
641 if (unsigned_left_shift_overflows(a
, shift
))
642 die("size_t overflow: %"PRIuMAX
" << %u",
643 (uintmax_t)a
, shift
);
647 static inline unsigned long cast_size_t_to_ulong(size_t a
)
649 if (a
!= (unsigned long)a
)
650 die("object too large to read on this platform: %"
651 PRIuMAX
" is cut off to %lu",
652 (uintmax_t)a
, (unsigned long)a
);
653 return (unsigned long)a
;
656 static inline uint32_t cast_size_t_to_uint32_t(size_t a
)
658 if (a
!= (uint32_t)a
)
659 die("object too large to read on this platform: %"
660 PRIuMAX
" is cut off to %u",
661 (uintmax_t)a
, (uint32_t)a
);
665 static inline int cast_size_t_to_int(size_t a
)
668 die("number too large to represent as int on this platform: %"PRIuMAX
,
673 static inline uint64_t u64_mult(uint64_t a
, uint64_t b
)
675 if (unsigned_mult_overflows(a
, b
))
676 die("uint64_t overflow: %"PRIuMAX
" * %"PRIuMAX
,
677 (uintmax_t)a
, (uintmax_t)b
);
681 static inline uint64_t u64_add(uint64_t a
, uint64_t b
)
683 if (unsigned_add_overflows(a
, b
))
684 die("uint64_t overflow: %"PRIuMAX
" + %"PRIuMAX
,
685 (uintmax_t)a
, (uintmax_t)b
);
690 * Limit size of IO chunks, because huge chunks only cause pain. OS X
691 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
692 * the absence of bugs, large chunks can result in bad latencies when
693 * you decide to kill the process.
695 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
696 * that is smaller than that, clip it to SSIZE_MAX, as a call to
697 * read(2) or write(2) larger than that is allowed to fail. As the last
698 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
699 * to override this, if the definition of SSIZE_MAX given by the platform
703 # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
704 # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
705 # define MAX_IO_SIZE SSIZE_MAX
707 # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
713 # define xalloca(size) (alloca(size))
714 # define xalloca_free(p) do {} while (0)
716 # define xalloca(size) (xmalloc(size))
717 # define xalloca_free(p) (free(p))
721 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
722 * that ptr is used twice, so don't pass e.g. ptr++.
724 #define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
726 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
727 #define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
728 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
730 #define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
731 BARF_UNLESS_COPYABLE((dst), (src)))
732 static inline void copy_array(void *dst
, const void *src
, size_t n
, size_t size
)
735 memcpy(dst
, src
, st_mult(size
, n
));
738 #define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
739 BARF_UNLESS_COPYABLE((dst), (src)))
740 static inline void move_array(void *dst
, const void *src
, size_t n
, size_t size
)
743 memmove(dst
, src
, st_mult(size
, n
));
746 #define DUP_ARRAY(dst, src, n) do { \
747 size_t dup_array_n_ = (n); \
748 COPY_ARRAY(ALLOC_ARRAY((dst), dup_array_n_), (src), dup_array_n_); \
752 * These functions help you allocate structs with flex arrays, and copy
753 * the data directly into the array. For example, if you had:
757 * char name[FLEX_ARRAY];
763 * FLEX_ALLOC_MEM(f, name, src, len);
765 * to allocate a "foo" with the contents of "src" in the "name" field.
766 * The resulting struct is automatically zero'd, and the flex-array field
767 * is NUL-terminated (whether the incoming src buffer was or not).
769 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
770 * but do want to store a pointer to some extra data in the same allocated
771 * block. For example, if you have:
781 * FLEXPTR_ALLOC_STR(f, name, src);
783 * and "name" will point to a block of memory after the struct, which will be
784 * freed along with the struct (but the pointer can be repointed anywhere).
786 * The *_STR variants accept a string parameter rather than a ptr/len
789 * Note that these macros will evaluate the first parameter multiple
790 * times, and it must be assignable as an lvalue.
792 #define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
793 size_t flex_array_len_ = (len); \
794 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
795 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
797 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
798 size_t flex_array_len_ = (len); \
799 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
800 memcpy((x) + 1, (buf), flex_array_len_); \
801 (x)->ptrname = (void *)((x)+1); \
803 #define FLEX_ALLOC_STR(x, flexname, str) \
804 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
805 #define FLEXPTR_ALLOC_STR(x, ptrname, str) \
806 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
808 #define alloc_nr(x) (((x)+16)*3/2)
811 * Dynamically growing an array using realloc() is error prone and boring.
813 * Define your array with:
815 * - a pointer (`item`) that points at the array, initialized to `NULL`
816 * (although please name the variable based on its contents, not on its
819 * - an integer variable (`alloc`) that keeps track of how big the current
820 * allocation is, initialized to `0`;
822 * - another integer variable (`nr`) to keep track of how many elements the
823 * array currently has, initialized to `0`.
825 * Then before adding `n`th element to the item, call `ALLOC_GROW(item, n,
826 * alloc)`. This ensures that the array can hold at least `n` elements by
827 * calling `realloc(3)` and adjusting `alloc` variable.
834 * for (i = 0; i < nr; i++)
835 * if (we like item[i] already)
838 * // we did not like any existing one, so add one
839 * ALLOC_GROW(item, nr + 1, alloc);
840 * item[nr++] = value you like;
843 * You are responsible for updating the `nr` variable.
845 * If you need to specify the number of elements to allocate explicitly
846 * then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`.
848 * Consider using ALLOC_GROW_BY instead of ALLOC_GROW as it has some
851 * DO NOT USE any expression with side-effect for 'x', 'nr', or 'alloc'.
853 #define ALLOC_GROW(x, nr, alloc) \
855 if ((nr) > alloc) { \
856 if (alloc_nr(alloc) < (nr)) \
859 alloc = alloc_nr(alloc); \
860 REALLOC_ARRAY(x, alloc); \
865 * Similar to ALLOC_GROW but handles updating of the nr value and
866 * zeroing the bytes of the newly-grown array elements.
868 * DO NOT USE any expression with side-effect for any of the
871 #define ALLOC_GROW_BY(x, nr, increase, alloc) \
874 size_t new_nr = nr + (increase); \
876 BUG("negative growth in ALLOC_GROW_BY"); \
877 ALLOC_GROW(x, new_nr, alloc); \
878 memset((x) + nr, 0, sizeof(*(x)) * (increase)); \
883 static inline char *xstrdup_or_null(const char *str
)
885 return str
? xstrdup(str
) : NULL
;
888 static inline size_t xsize_t(off_t len
)
890 if (len
< 0 || (uintmax_t) len
> SIZE_MAX
)
891 die("Cannot handle files this big");
896 * Like skip_prefix, but compare case-insensitively. Note that the comparison
897 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
898 * locale-specific conversions).
900 static inline int skip_iprefix(const char *str
, const char *prefix
,
908 } while (tolower(*str
++) == tolower(*prefix
++));
913 * Like skip_prefix_mem, but compare case-insensitively. Note that the
914 * comparison is done via tolower(), so it is strictly ASCII (no multi-byte
915 * characters or locale-specific conversions).
917 static inline int skip_iprefix_mem(const char *buf
, size_t len
,
919 const char **out
, size_t *outlen
)
927 } while (len
-- > 0 && tolower(*buf
++) == tolower(*prefix
++));
931 static inline int strtoul_ui(char const *s
, int base
, unsigned int *result
)
937 /* negative values would be accepted by strtoul */
940 ul
= strtoul(s
, &p
, base
);
941 if (errno
|| *p
|| p
== s
|| (unsigned int) ul
!= ul
)
947 static inline int strtol_i(char const *s
, int base
, int *result
)
953 ul
= strtol(s
, &p
, base
);
954 if (errno
|| *p
|| p
== s
|| (int) ul
!= ul
)
961 #error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
964 static inline int regexec_buf(const regex_t
*preg
, const char *buf
, size_t size
,
965 size_t nmatch
, regmatch_t pmatch
[], int eflags
)
967 assert(nmatch
> 0 && pmatch
);
969 pmatch
[0].rm_eo
= size
;
970 return regexec(preg
, buf
, nmatch
, pmatch
, eflags
| REG_STARTEND
);
973 #ifdef USE_ENHANCED_BASIC_REGULAR_EXPRESSIONS
974 int git_regcomp(regex_t
*preg
, const char *pattern
, int cflags
);
975 #define regcomp git_regcomp
978 #ifndef DIR_HAS_BSD_GROUP_SEMANTICS
979 # define FORCE_DIR_SET_GID S_ISGID
981 # define FORCE_DIR_SET_GID 0
984 #ifdef UNRELIABLE_FSTAT
985 #define fstat_is_reliable() 0
987 #define fstat_is_reliable() 1
990 /* usage.c: only to be used for testing BUG() implementation (see test-tool) */
991 extern int BUG_exit_code
;
993 /* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
994 extern int bug_called_must_BUG
;
996 __attribute__((format (printf
, 3, 4))) NORETURN
997 void BUG_fl(const char *file
, int line
, const char *fmt
, ...);
998 #define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
999 /* ASSERT: like assert(), but won't be compiled out with NDEBUG */
1000 #define ASSERT(a) if (!(a)) BUG("Assertion `" #a "' failed.")
1001 __attribute__((format (printf
, 3, 4)))
1002 void bug_fl(const char *file
, int line
, const char *fmt
, ...);
1003 #define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1004 #define BUG_if_bug(...) do { \
1005 if (bug_called_must_BUG) \
1006 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1009 #ifndef FSYNC_METHOD_DEFAULT
1011 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1013 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1018 # define SHELL_PATH "/bin/sh"
1022 * Our code often opens a path to an optional file, to work on its
1023 * contents when we can successfully open it. We can ignore a failure
1024 * to open if such an optional file does not exist, but we do want to
1025 * report a failure in opening for other reasons (e.g. we got an I/O
1026 * error, or the file is there, but we lack the permission to open).
1028 * Call this function after seeing an error from open() or fopen() to
1029 * see if the errno indicates a missing file that we can safely ignore.
1031 static inline int is_missing_file_error(int errno_
)
1033 return (errno_
== ENOENT
|| errno_
== ENOTDIR
);
1036 int cmd_main(int, const char **);
1039 * Intercept all calls to exit() and route them to trace2 to
1040 * optionally emit a message before calling the real exit().
1042 int common_exit(const char *file
, int line
, int code
);
1043 #define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
1046 * This include must come after system headers, since it introduces macros that
1047 * replace system names.
1052 * container_of - Get the address of an object containing a field.
1054 * @ptr: pointer to the field.
1055 * @type: type of the object.
1056 * @member: name of the field within the object.
1058 #define container_of(ptr, type, member) \
1059 ((type *) ((char *)(ptr) - offsetof(type, member)))
1062 * helper function for `container_of_or_null' to avoid multiple
1063 * evaluation of @ptr
1065 static inline void *container_of_or_null_offset(void *ptr
, size_t offset
)
1067 return ptr
? (char *)ptr
- offset
: NULL
;
1071 * like `container_of', but allows returned value to be NULL
1073 #define container_of_or_null(ptr, type, member) \
1074 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1077 * like offsetof(), but takes a pointer to a variable of type which
1078 * contains @member, instead of a specified type.
1079 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1082 #if defined(__GNUC__) /* clang sets this, too */
1083 #define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1084 #else /* !__GNUC__ */
1085 #define OFFSETOF_VAR(ptr, member) \
1086 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1087 #endif /* !__GNUC__ */
1090 * Prevent an overly clever compiler from optimizing an expression
1091 * out, triggering a false positive when building with the
1092 * -Wunreachable-code option. false_but_the_compiler_does_not_know_it_
1093 * is defined in a compilation unit separate from where the macro is
1094 * used, initialized to 0, and never modified.
1096 #define NOT_CONSTANT(expr) ((expr) || false_but_the_compiler_does_not_know_it_)
1097 extern int false_but_the_compiler_does_not_know_it_
;
1099 #ifdef CHECK_ASSERTION_SIDE_EFFECTS
1101 extern int not_supposed_to_survive
;
1102 #define assert(expr) ((void)(not_supposed_to_survive || (expr)))
1103 #endif /* CHECK_ASSERTION_SIDE_EFFECTS */