git-compat-util.h: use "deprecated" for UNUSED variables
[git.git] / git-compat-util.h
blob71a004be40966ea8e152f4cff6b774efd86583f7
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 #else
101 # define BARF_UNLESS_AN_ARRAY(arr) 0
102 #endif
104 * ARRAY_SIZE - get the number of elements in a visible array
105 * @x: the array whose size you want.
107 * This does not work on pointers, or arrays declared as [], or
108 * function parameters. With correct compiler support, such usage
109 * will cause a build error (see the build_assert_or_zero macro).
111 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
113 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
115 #define maximum_signed_value_of_type(a) \
116 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
118 #define maximum_unsigned_value_of_type(a) \
119 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
122 * Signed integer overflow is undefined in C, so here's a helper macro
123 * to detect if the sum of two integers will overflow.
125 * Requires: a >= 0, typeof(a) equals typeof(b)
127 #define signed_add_overflows(a, b) \
128 ((b) > maximum_signed_value_of_type(a) - (a))
130 #define unsigned_add_overflows(a, b) \
131 ((b) > maximum_unsigned_value_of_type(a) - (a))
134 * Returns true if the multiplication of "a" and "b" will
135 * overflow. The types of "a" and "b" must match and must be unsigned.
136 * Note that this macro evaluates "a" twice!
138 #define unsigned_mult_overflows(a, b) \
139 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
142 * Returns true if the left shift of "a" by "shift" bits will
143 * overflow. The type of "a" must be unsigned.
145 #define unsigned_left_shift_overflows(a, shift) \
146 ((shift) < bitsizeof(a) && \
147 (a) > maximum_unsigned_value_of_type(a) >> (shift))
149 #ifdef __GNUC__
150 #define TYPEOF(x) (__typeof__(x))
151 #else
152 #define TYPEOF(x)
153 #endif
155 #define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
156 #define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
158 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
160 /* Approximation of the length of the decimal representation of this type. */
161 #define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
163 #ifdef __MINGW64__
164 #define _POSIX_C_SOURCE 1
165 #elif defined(__sun__)
167 * On Solaris, when _XOPEN_EXTENDED is set, its header file
168 * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
169 * setting to say we are XPG5 or XPG6. Also on Solaris,
170 * XPG6 programs must be compiled with a c99 compiler, while
171 * non XPG6 programs must be compiled with a pre-c99 compiler.
173 # if __STDC_VERSION__ - 0 >= 199901L
174 # define _XOPEN_SOURCE 600
175 # else
176 # define _XOPEN_SOURCE 500
177 # endif
178 #elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
179 !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
180 !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
181 !defined(__CYGWIN__)
182 #define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
183 #define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
184 #endif
185 #define _ALL_SOURCE 1
186 #define _GNU_SOURCE 1
187 #define _BSD_SOURCE 1
188 #define _DEFAULT_SOURCE 1
189 #define _NETBSD_SOURCE 1
190 #define _SGI_SOURCE 1
192 #if defined(__GNUC__)
193 #define UNUSED __attribute__((unused)) \
194 __attribute__((deprecated ("parameter declared as UNUSED")))
195 #else
196 #define UNUSED
197 #endif
199 #if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
200 # if !defined(_WIN32_WINNT)
201 # define _WIN32_WINNT 0x0600
202 # endif
203 #define WIN32_LEAN_AND_MEAN /* stops windows.h including winsock.h */
204 #include <winsock2.h>
205 #ifndef NO_UNIX_SOCKETS
206 #include <afunix.h>
207 #endif
208 #include <windows.h>
209 #define GIT_WINDOWS_NATIVE
210 #endif
212 #include <unistd.h>
213 #include <stdio.h>
214 #include <sys/stat.h>
215 #include <fcntl.h>
216 #include <stddef.h>
217 #include <stdlib.h>
218 #include <stdarg.h>
219 #include <string.h>
220 #ifdef HAVE_STRINGS_H
221 #include <strings.h> /* for strcasecmp() */
222 #endif
223 #include <errno.h>
224 #include <limits.h>
225 #ifdef NEEDS_SYS_PARAM_H
226 #include <sys/param.h>
227 #endif
228 #include <sys/types.h>
229 #include <dirent.h>
230 #include <sys/time.h>
231 #include <time.h>
232 #include <signal.h>
233 #include <assert.h>
234 #include <regex.h>
235 #include <utime.h>
236 #include <syslog.h>
237 #if !defined(NO_POLL_H)
238 #include <poll.h>
239 #elif !defined(NO_SYS_POLL_H)
240 #include <sys/poll.h>
241 #else
242 /* Pull the compat stuff */
243 #include <poll.h>
244 #endif
245 #ifdef HAVE_BSD_SYSCTL
246 #include <sys/sysctl.h>
247 #endif
249 /* Used by compat/win32/path-utils.h, and more */
250 static inline int is_xplatform_dir_sep(int c)
252 return c == '/' || c == '\\';
255 #if defined(__CYGWIN__)
256 #include "compat/win32/path-utils.h"
257 #endif
258 #if defined(__MINGW32__)
259 /* pull in Windows compatibility stuff */
260 #include "compat/win32/path-utils.h"
261 #include "compat/mingw.h"
262 #elif defined(_MSC_VER)
263 #include "compat/win32/path-utils.h"
264 #include "compat/msvc.h"
265 #else
266 #include <sys/utsname.h>
267 #include <sys/wait.h>
268 #include <sys/resource.h>
269 #include <sys/socket.h>
270 #include <sys/ioctl.h>
271 #include <termios.h>
272 #ifndef NO_SYS_SELECT_H
273 #include <sys/select.h>
274 #endif
275 #include <netinet/in.h>
276 #include <netinet/tcp.h>
277 #include <arpa/inet.h>
278 #include <netdb.h>
279 #include <pwd.h>
280 #include <sys/un.h>
281 #ifndef NO_INTTYPES_H
282 #include <inttypes.h>
283 #else
284 #include <stdint.h>
285 #endif
286 #ifdef HAVE_ARC4RANDOM_LIBBSD
287 #include <bsd/stdlib.h>
288 #endif
289 #ifdef HAVE_GETRANDOM
290 #include <sys/random.h>
291 #endif
292 #ifdef NO_INTPTR_T
294 * On I16LP32, ILP32 and LP64 "long" is the safe bet, however
295 * on LLP86, IL33LLP64 and P64 it needs to be "long long",
296 * while on IP16 and IP16L32 it is "int" (resp. "short")
297 * Size needs to match (or exceed) 'sizeof(void *)'.
298 * We can't take "long long" here as not everybody has it.
300 typedef long intptr_t;
301 typedef unsigned long uintptr_t;
302 #endif
303 #undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
304 #include <grp.h>
305 #define _ALL_SOURCE 1
306 #endif
308 /* used on Mac OS X */
309 #ifdef PRECOMPOSE_UNICODE
310 #include "compat/precompose_utf8.h"
311 #else
312 static inline const char *precompose_argv_prefix(int argc, const char **argv, const char *prefix)
314 return prefix;
316 static inline const char *precompose_string_if_needed(const char *in)
318 return in;
321 #define probe_utf8_pathname_composition()
322 #endif
324 #ifdef MKDIR_WO_TRAILING_SLASH
325 #define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
326 int compat_mkdir_wo_trailing_slash(const char*, mode_t);
327 #endif
329 #ifdef NO_STRUCT_ITIMERVAL
330 struct itimerval {
331 struct timeval it_interval;
332 struct timeval it_value;
334 #endif
336 #ifdef NO_SETITIMER
337 static inline int setitimer(int which, const struct itimerval *value, struct itimerval *newvalue) {
338 return 0; /* pretend success */
340 #endif
342 #ifndef NO_LIBGEN_H
343 #include <libgen.h>
344 #else
345 #define basename gitbasename
346 char *gitbasename(char *);
347 #define dirname gitdirname
348 char *gitdirname(char *);
349 #endif
351 #ifndef NO_ICONV
352 #include <iconv.h>
353 #endif
355 #ifndef NO_OPENSSL
356 #ifdef __APPLE__
357 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
358 #include <AvailabilityMacros.h>
359 #undef DEPRECATED_ATTRIBUTE
360 #define DEPRECATED_ATTRIBUTE
361 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
362 #endif
363 #include <openssl/ssl.h>
364 #include <openssl/err.h>
365 #endif
367 #ifdef HAVE_SYSINFO
368 # include <sys/sysinfo.h>
369 #endif
371 /* On most systems <netdb.h> would have given us this, but
372 * not on some systems (e.g. z/OS).
374 #ifndef NI_MAXHOST
375 #define NI_MAXHOST 1025
376 #endif
378 #ifndef NI_MAXSERV
379 #define NI_MAXSERV 32
380 #endif
382 /* On most systems <limits.h> would have given us this, but
383 * not on some systems (e.g. GNU/Hurd).
385 #ifndef PATH_MAX
386 #define PATH_MAX 4096
387 #endif
389 typedef uintmax_t timestamp_t;
390 #define PRItime PRIuMAX
391 #define parse_timestamp strtoumax
392 #define TIME_MAX UINTMAX_MAX
393 #define TIME_MIN 0
395 #ifndef PATH_SEP
396 #define PATH_SEP ':'
397 #endif
399 #ifdef HAVE_PATHS_H
400 #include <paths.h>
401 #endif
402 #ifndef _PATH_DEFPATH
403 #define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
404 #endif
406 #ifndef platform_core_config
407 static inline int noop_core_config(const char *var UNUSED,
408 const char *value UNUSED,
409 void *cb UNUSED)
411 return 0;
413 #define platform_core_config noop_core_config
414 #endif
416 int lstat_cache_aware_rmdir(const char *path);
417 #if !defined(__MINGW32__) && !defined(_MSC_VER)
418 #define rmdir lstat_cache_aware_rmdir
419 #endif
421 #ifndef has_dos_drive_prefix
422 static inline int git_has_dos_drive_prefix(const char *path)
424 return 0;
426 #define has_dos_drive_prefix git_has_dos_drive_prefix
427 #endif
429 #ifndef skip_dos_drive_prefix
430 static inline int git_skip_dos_drive_prefix(char **path)
432 return 0;
434 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
435 #endif
437 static inline int git_is_dir_sep(int c)
439 return c == '/';
441 #ifndef is_dir_sep
442 #define is_dir_sep git_is_dir_sep
443 #endif
445 #ifndef offset_1st_component
446 static inline int git_offset_1st_component(const char *path)
448 return is_dir_sep(path[0]);
450 #define offset_1st_component git_offset_1st_component
451 #endif
453 #ifndef is_valid_path
454 #define is_valid_path(path) 1
455 #endif
457 #ifndef is_path_owned_by_current_user
459 #ifdef __TANDEM
460 #define ROOT_UID 65535
461 #else
462 #define ROOT_UID 0
463 #endif
466 * Do not use this function when
467 * (1) geteuid() did not say we are running as 'root', or
468 * (2) using this function will compromise the system.
470 * PORTABILITY WARNING:
471 * This code assumes uid_t is unsigned because that is what sudo does.
472 * If your uid_t type is signed and all your ids are positive then it
473 * should all work fine.
474 * If your version of sudo uses negative values for uid_t or it is
475 * buggy and return an overflowed value in SUDO_UID, then git might
476 * fail to grant access to your repository properly or even mistakenly
477 * grant access to someone else.
478 * In the unlikely scenario this happened to you, and that is how you
479 * got to this message, we would like to know about it; so sent us an
480 * email to git@vger.kernel.org indicating which platform you are
481 * using and which version of sudo, so we can improve this logic and
482 * maybe provide you with a patch that would prevent this issue again
483 * in the future.
485 static inline void extract_id_from_env(const char *env, uid_t *id)
487 const char *real_uid = getenv(env);
489 /* discard anything empty to avoid a more complex check below */
490 if (real_uid && *real_uid) {
491 char *endptr = NULL;
492 unsigned long env_id;
494 errno = 0;
495 /* silent overflow errors could trigger a bug here */
496 env_id = strtoul(real_uid, &endptr, 10);
497 if (!*endptr && !errno)
498 *id = env_id;
502 static inline int is_path_owned_by_current_uid(const char *path,
503 struct strbuf *report UNUSED)
505 struct stat st;
506 uid_t euid;
508 if (lstat(path, &st))
509 return 0;
511 euid = geteuid();
512 if (euid == ROOT_UID)
514 if (st.st_uid == ROOT_UID)
515 return 1;
516 else
517 extract_id_from_env("SUDO_UID", &euid);
520 return st.st_uid == euid;
523 #define is_path_owned_by_current_user is_path_owned_by_current_uid
524 #endif
526 #ifndef find_last_dir_sep
527 static inline char *git_find_last_dir_sep(const char *path)
529 return strrchr(path, '/');
531 #define find_last_dir_sep git_find_last_dir_sep
532 #endif
534 #ifndef has_dir_sep
535 static inline int git_has_dir_sep(const char *path)
537 return !!strchr(path, '/');
539 #define has_dir_sep(path) git_has_dir_sep(path)
540 #endif
542 #ifndef query_user_email
543 #define query_user_email() NULL
544 #endif
546 #ifdef __TANDEM
547 #include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
548 #include <floss.h(floss_getpwuid)>
549 #ifndef NSIG
551 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
552 * known, by detective work using kill -l as a list is all signals
553 * instead of signal.h where it should be.
555 # define NSIG 100
556 #endif
557 #endif
559 #if defined(__HP_cc) && (__HP_cc >= 61000)
560 #define NORETURN __attribute__((noreturn))
561 #define NORETURN_PTR
562 #elif defined(__GNUC__) && !defined(NO_NORETURN)
563 #define NORETURN __attribute__((__noreturn__))
564 #define NORETURN_PTR __attribute__((__noreturn__))
565 #elif defined(_MSC_VER)
566 #define NORETURN __declspec(noreturn)
567 #define NORETURN_PTR
568 #else
569 #define NORETURN
570 #define NORETURN_PTR
571 #ifndef __GNUC__
572 #ifndef __attribute__
573 #define __attribute__(x)
574 #endif
575 #endif
576 #endif
578 /* The sentinel attribute is valid from gcc version 4.0 */
579 #if defined(__GNUC__) && (__GNUC__ >= 4)
580 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
581 #else
582 #define LAST_ARG_MUST_BE_NULL
583 #endif
585 #define MAYBE_UNUSED __attribute__((__unused__))
587 #include "compat/bswap.h"
589 #include "wildmatch.h"
591 struct strbuf;
593 /* General helper functions */
594 NORETURN void usage(const char *err);
595 NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
596 NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
597 NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
598 int die_message(const char *err, ...) __attribute__((format (printf, 1, 2)));
599 int die_message_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
600 int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
601 int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
602 void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
603 void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
605 #ifndef NO_OPENSSL
606 #ifdef APPLE_COMMON_CRYPTO
607 #include "compat/apple-common-crypto.h"
608 #else
609 #include <openssl/evp.h>
610 #include <openssl/hmac.h>
611 #endif /* APPLE_COMMON_CRYPTO */
612 #include <openssl/x509v3.h>
613 #endif /* NO_OPENSSL */
615 #ifdef HAVE_OPENSSL_CSPRNG
616 #include <openssl/rand.h>
617 #endif
620 * Let callers be aware of the constant return value; this can help
621 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
622 * because other compilers may be confused by this.
624 #if defined(__GNUC__)
625 static inline int const_error(void)
627 return -1;
629 #define error(...) (error(__VA_ARGS__), const_error())
630 #define error_errno(...) (error_errno(__VA_ARGS__), const_error())
631 #endif
633 typedef void (*report_fn)(const char *, va_list params);
635 void set_die_routine(NORETURN_PTR report_fn routine);
636 report_fn get_die_message_routine(void);
637 void set_error_routine(report_fn routine);
638 report_fn get_error_routine(void);
639 void set_warn_routine(report_fn routine);
640 report_fn get_warn_routine(void);
641 void set_die_is_recursing_routine(int (*routine)(void));
643 int starts_with(const char *str, const char *prefix);
644 int istarts_with(const char *str, const char *prefix);
647 * If the string "str" begins with the string found in "prefix", return 1.
648 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
649 * the string right after the prefix).
651 * Otherwise, return 0 and leave "out" untouched.
653 * Examples:
655 * [extract branch name, fail if not a branch]
656 * if (!skip_prefix(ref, "refs/heads/", &branch)
657 * return -1;
659 * [skip prefix if present, otherwise use whole string]
660 * skip_prefix(name, "refs/heads/", &name);
662 static inline int skip_prefix(const char *str, const char *prefix,
663 const char **out)
665 do {
666 if (!*prefix) {
667 *out = str;
668 return 1;
670 } while (*str++ == *prefix++);
671 return 0;
675 * If the string "str" is the same as the string in "prefix", then the "arg"
676 * parameter is set to the "def" parameter and 1 is returned.
677 * If the string "str" begins with the string found in "prefix" and then a
678 * "=" sign, then the "arg" parameter is set to "str + strlen(prefix) + 1"
679 * (i.e., to the point in the string right after the prefix and the "=" sign),
680 * and 1 is returned.
682 * Otherwise, return 0 and leave "arg" untouched.
684 * When we accept both a "--key" and a "--key=<val>" option, this function
685 * can be used instead of !strcmp(arg, "--key") and then
686 * skip_prefix(arg, "--key=", &arg) to parse such an option.
688 int skip_to_optional_arg_default(const char *str, const char *prefix,
689 const char **arg, const char *def);
691 static inline int skip_to_optional_arg(const char *str, const char *prefix,
692 const char **arg)
694 return skip_to_optional_arg_default(str, prefix, arg, "");
698 * Like skip_prefix, but promises never to read past "len" bytes of the input
699 * buffer, and returns the remaining number of bytes in "out" via "outlen".
701 static inline int skip_prefix_mem(const char *buf, size_t len,
702 const char *prefix,
703 const char **out, size_t *outlen)
705 size_t prefix_len = strlen(prefix);
706 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
707 *out = buf + prefix_len;
708 *outlen = len - prefix_len;
709 return 1;
711 return 0;
715 * If buf ends with suffix, return 1 and subtract the length of the suffix
716 * from *len. Otherwise, return 0 and leave *len untouched.
718 static inline int strip_suffix_mem(const char *buf, size_t *len,
719 const char *suffix)
721 size_t suflen = strlen(suffix);
722 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
723 return 0;
724 *len -= suflen;
725 return 1;
729 * If str ends with suffix, return 1 and set *len to the size of the string
730 * without the suffix. Otherwise, return 0 and set *len to the size of the
731 * string.
733 * Note that we do _not_ NUL-terminate str to the new length.
735 static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
737 *len = strlen(str);
738 return strip_suffix_mem(str, len, suffix);
741 static inline int ends_with(const char *str, const char *suffix)
743 size_t len;
744 return strip_suffix(str, suffix, &len);
747 #define SWAP(a, b) do { \
748 void *_swap_a_ptr = &(a); \
749 void *_swap_b_ptr = &(b); \
750 unsigned char _swap_buffer[sizeof(a)]; \
751 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
752 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
753 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
754 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
755 } while (0)
757 #if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
759 #ifndef PROT_READ
760 #define PROT_READ 1
761 #define PROT_WRITE 2
762 #define MAP_PRIVATE 1
763 #endif
765 #define mmap git_mmap
766 #define munmap git_munmap
767 void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
768 int git_munmap(void *start, size_t length);
770 #else /* NO_MMAP || USE_WIN32_MMAP */
772 #include <sys/mman.h>
774 #endif /* NO_MMAP || USE_WIN32_MMAP */
776 #ifdef NO_MMAP
778 /* This value must be multiple of (pagesize * 2) */
779 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
781 #else /* NO_MMAP */
783 /* This value must be multiple of (pagesize * 2) */
784 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
785 (sizeof(void*) >= 8 \
786 ? 1 * 1024 * 1024 * 1024 \
787 : 32 * 1024 * 1024)
789 #endif /* NO_MMAP */
791 #ifndef MAP_FAILED
792 #define MAP_FAILED ((void *)-1)
793 #endif
795 #ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
796 #define on_disk_bytes(st) ((st).st_size)
797 #else
798 #define on_disk_bytes(st) ((st).st_blocks * 512)
799 #endif
801 #ifdef NEEDS_MODE_TRANSLATION
802 #undef S_IFMT
803 #undef S_IFREG
804 #undef S_IFDIR
805 #undef S_IFLNK
806 #undef S_IFBLK
807 #undef S_IFCHR
808 #undef S_IFIFO
809 #undef S_IFSOCK
810 #define S_IFMT 0170000
811 #define S_IFREG 0100000
812 #define S_IFDIR 0040000
813 #define S_IFLNK 0120000
814 #define S_IFBLK 0060000
815 #define S_IFCHR 0020000
816 #define S_IFIFO 0010000
817 #define S_IFSOCK 0140000
818 #ifdef stat
819 #undef stat
820 #endif
821 #define stat(path, buf) git_stat(path, buf)
822 int git_stat(const char *, struct stat *);
823 #ifdef fstat
824 #undef fstat
825 #endif
826 #define fstat(fd, buf) git_fstat(fd, buf)
827 int git_fstat(int, struct stat *);
828 #ifdef lstat
829 #undef lstat
830 #endif
831 #define lstat(path, buf) git_lstat(path, buf)
832 int git_lstat(const char *, struct stat *);
833 #endif
835 #define DEFAULT_PACKED_GIT_LIMIT \
836 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
838 #ifdef NO_PREAD
839 #define pread git_pread
840 ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
841 #endif
843 * Forward decl that will remind us if its twin in cache.h changes.
844 * This function is used in compat/pread.c. But we can't include
845 * cache.h there.
847 ssize_t read_in_full(int fd, void *buf, size_t count);
849 #ifdef NO_SETENV
850 #define setenv gitsetenv
851 int gitsetenv(const char *, const char *, int);
852 #endif
854 #ifdef NO_MKDTEMP
855 #define mkdtemp gitmkdtemp
856 char *gitmkdtemp(char *);
857 #endif
859 #ifdef NO_UNSETENV
860 #define unsetenv gitunsetenv
861 int gitunsetenv(const char *);
862 #endif
864 #ifdef NO_STRCASESTR
865 #define strcasestr gitstrcasestr
866 char *gitstrcasestr(const char *haystack, const char *needle);
867 #endif
869 #ifdef NO_STRLCPY
870 #define strlcpy gitstrlcpy
871 size_t gitstrlcpy(char *, const char *, size_t);
872 #endif
874 #ifdef NO_STRTOUMAX
875 #define strtoumax gitstrtoumax
876 uintmax_t gitstrtoumax(const char *, char **, int);
877 #define strtoimax gitstrtoimax
878 intmax_t gitstrtoimax(const char *, char **, int);
879 #endif
881 #ifdef NO_HSTRERROR
882 #define hstrerror githstrerror
883 const char *githstrerror(int herror);
884 #endif
886 #ifdef NO_MEMMEM
887 #define memmem gitmemmem
888 void *gitmemmem(const void *haystack, size_t haystacklen,
889 const void *needle, size_t needlelen);
890 #endif
892 #ifdef OVERRIDE_STRDUP
893 #ifdef strdup
894 #undef strdup
895 #endif
896 #define strdup gitstrdup
897 char *gitstrdup(const char *s);
898 #endif
900 #ifdef NO_GETPAGESIZE
901 #define getpagesize() sysconf(_SC_PAGESIZE)
902 #endif
904 #ifndef O_CLOEXEC
905 #define O_CLOEXEC 0
906 #endif
908 #ifdef FREAD_READS_DIRECTORIES
909 # if !defined(SUPPRESS_FOPEN_REDEFINITION)
910 # ifdef fopen
911 # undef fopen
912 # endif
913 # define fopen(a,b) git_fopen(a,b)
914 # endif
915 FILE *git_fopen(const char*, const char*);
916 #endif
918 #ifdef SNPRINTF_RETURNS_BOGUS
919 #ifdef snprintf
920 #undef snprintf
921 #endif
922 #define snprintf git_snprintf
923 int git_snprintf(char *str, size_t maxsize,
924 const char *format, ...);
925 #ifdef vsnprintf
926 #undef vsnprintf
927 #endif
928 #define vsnprintf git_vsnprintf
929 int git_vsnprintf(char *str, size_t maxsize,
930 const char *format, va_list ap);
931 #endif
933 #ifdef OPEN_RETURNS_EINTR
934 #undef open
935 #define open git_open_with_retry
936 int git_open_with_retry(const char *path, int flag, ...);
937 #endif
939 #ifdef __GLIBC_PREREQ
940 #if __GLIBC_PREREQ(2, 1)
941 #define HAVE_STRCHRNUL
942 #endif
943 #endif
945 #ifndef HAVE_STRCHRNUL
946 #define strchrnul gitstrchrnul
947 static inline char *gitstrchrnul(const char *s, int c)
949 while (*s && *s != c)
950 s++;
951 return (char *)s;
953 #endif
955 #ifdef NO_INET_PTON
956 int inet_pton(int af, const char *src, void *dst);
957 #endif
959 #ifdef NO_INET_NTOP
960 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
961 #endif
963 #ifdef NO_PTHREADS
964 #define atexit git_atexit
965 int git_atexit(void (*handler)(void));
966 #endif
968 static inline size_t st_add(size_t a, size_t b)
970 if (unsigned_add_overflows(a, b))
971 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
972 (uintmax_t)a, (uintmax_t)b);
973 return a + b;
975 #define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
976 #define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
978 static inline size_t st_mult(size_t a, size_t b)
980 if (unsigned_mult_overflows(a, b))
981 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
982 (uintmax_t)a, (uintmax_t)b);
983 return a * b;
986 static inline size_t st_sub(size_t a, size_t b)
988 if (a < b)
989 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
990 (uintmax_t)a, (uintmax_t)b);
991 return a - b;
994 static inline size_t st_left_shift(size_t a, unsigned shift)
996 if (unsigned_left_shift_overflows(a, shift))
997 die("size_t overflow: %"PRIuMAX" << %u",
998 (uintmax_t)a, shift);
999 return a << shift;
1002 static inline unsigned long cast_size_t_to_ulong(size_t a)
1004 if (a != (unsigned long)a)
1005 die("object too large to read on this platform: %"
1006 PRIuMAX" is cut off to %lu",
1007 (uintmax_t)a, (unsigned long)a);
1008 return (unsigned long)a;
1011 #ifdef HAVE_ALLOCA_H
1012 # include <alloca.h>
1013 # define xalloca(size) (alloca(size))
1014 # define xalloca_free(p) do {} while (0)
1015 #else
1016 # define xalloca(size) (xmalloc(size))
1017 # define xalloca_free(p) (free(p))
1018 #endif
1019 char *xstrdup(const char *str);
1020 void *xmalloc(size_t size);
1021 void *xmallocz(size_t size);
1022 void *xmallocz_gently(size_t size);
1023 void *xmemdupz(const void *data, size_t len);
1024 char *xstrndup(const char *str, size_t len);
1025 void *xrealloc(void *ptr, size_t size);
1026 void *xcalloc(size_t nmemb, size_t size);
1027 void xsetenv(const char *name, const char *value, int overwrite);
1028 void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
1029 const char *mmap_os_err(void);
1030 void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
1031 int xopen(const char *path, int flags, ...);
1032 ssize_t xread(int fd, void *buf, size_t len);
1033 ssize_t xwrite(int fd, const void *buf, size_t len);
1034 ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
1035 int xdup(int fd);
1036 FILE *xfopen(const char *path, const char *mode);
1037 FILE *xfdopen(int fd, const char *mode);
1038 int xmkstemp(char *temp_filename);
1039 int xmkstemp_mode(char *temp_filename, int mode);
1040 char *xgetcwd(void);
1041 FILE *fopen_for_writing(const char *path);
1042 FILE *fopen_or_warn(const char *path, const char *mode);
1045 * Like strncmp, but only return zero if s is NUL-terminated and exactly len
1046 * characters long. If it is not, consider it greater than t.
1048 int xstrncmpz(const char *s, const char *t, size_t len);
1051 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
1052 * that ptr is used twice, so don't pass e.g. ptr++.
1054 #define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
1056 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
1057 #define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
1058 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
1060 #define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
1061 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
1062 static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
1064 if (n)
1065 memcpy(dst, src, st_mult(size, n));
1068 #define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
1069 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
1070 static inline void move_array(void *dst, const void *src, size_t n, size_t size)
1072 if (n)
1073 memmove(dst, src, st_mult(size, n));
1077 * These functions help you allocate structs with flex arrays, and copy
1078 * the data directly into the array. For example, if you had:
1080 * struct foo {
1081 * int bar;
1082 * char name[FLEX_ARRAY];
1083 * };
1085 * you can do:
1087 * struct foo *f;
1088 * FLEX_ALLOC_MEM(f, name, src, len);
1090 * to allocate a "foo" with the contents of "src" in the "name" field.
1091 * The resulting struct is automatically zero'd, and the flex-array field
1092 * is NUL-terminated (whether the incoming src buffer was or not).
1094 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
1095 * but do want to store a pointer to some extra data in the same allocated
1096 * block. For example, if you have:
1098 * struct foo {
1099 * char *name;
1100 * int bar;
1101 * };
1103 * you can do:
1105 * struct foo *f;
1106 * FLEXPTR_ALLOC_STR(f, name, src);
1108 * and "name" will point to a block of memory after the struct, which will be
1109 * freed along with the struct (but the pointer can be repointed anywhere).
1111 * The *_STR variants accept a string parameter rather than a ptr/len
1112 * combination.
1114 * Note that these macros will evaluate the first parameter multiple
1115 * times, and it must be assignable as an lvalue.
1117 #define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
1118 size_t flex_array_len_ = (len); \
1119 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1120 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
1121 } while (0)
1122 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
1123 size_t flex_array_len_ = (len); \
1124 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1125 memcpy((x) + 1, (buf), flex_array_len_); \
1126 (x)->ptrname = (void *)((x)+1); \
1127 } while(0)
1128 #define FLEX_ALLOC_STR(x, flexname, str) \
1129 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
1130 #define FLEXPTR_ALLOC_STR(x, ptrname, str) \
1131 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
1133 static inline char *xstrdup_or_null(const char *str)
1135 return str ? xstrdup(str) : NULL;
1138 static inline size_t xsize_t(off_t len)
1140 if (len < 0 || (uintmax_t) len > SIZE_MAX)
1141 die("Cannot handle files this big");
1142 return (size_t) len;
1145 __attribute__((format (printf, 3, 4)))
1146 int xsnprintf(char *dst, size_t max, const char *fmt, ...);
1148 #ifndef HOST_NAME_MAX
1149 #define HOST_NAME_MAX 256
1150 #endif
1152 int xgethostname(char *buf, size_t len);
1154 /* in ctype.c, for kwset users */
1155 extern const unsigned char tolower_trans_tbl[256];
1157 /* Sane ctype - no locale, and works with signed chars */
1158 #undef isascii
1159 #undef isspace
1160 #undef isdigit
1161 #undef isalpha
1162 #undef isalnum
1163 #undef isprint
1164 #undef islower
1165 #undef isupper
1166 #undef tolower
1167 #undef toupper
1168 #undef iscntrl
1169 #undef ispunct
1170 #undef isxdigit
1172 extern const unsigned char sane_ctype[256];
1173 #define GIT_SPACE 0x01
1174 #define GIT_DIGIT 0x02
1175 #define GIT_ALPHA 0x04
1176 #define GIT_GLOB_SPECIAL 0x08
1177 #define GIT_REGEX_SPECIAL 0x10
1178 #define GIT_PATHSPEC_MAGIC 0x20
1179 #define GIT_CNTRL 0x40
1180 #define GIT_PUNCT 0x80
1181 #define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
1182 #define isascii(x) (((x) & ~0x7f) == 0)
1183 #define isspace(x) sane_istest(x,GIT_SPACE)
1184 #define isdigit(x) sane_istest(x,GIT_DIGIT)
1185 #define isalpha(x) sane_istest(x,GIT_ALPHA)
1186 #define isalnum(x) sane_istest(x,GIT_ALPHA | GIT_DIGIT)
1187 #define isprint(x) ((x) >= 0x20 && (x) <= 0x7e)
1188 #define islower(x) sane_iscase(x, 1)
1189 #define isupper(x) sane_iscase(x, 0)
1190 #define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
1191 #define is_regex_special(x) sane_istest(x,GIT_GLOB_SPECIAL | GIT_REGEX_SPECIAL)
1192 #define iscntrl(x) (sane_istest(x,GIT_CNTRL))
1193 #define ispunct(x) sane_istest(x, GIT_PUNCT | GIT_REGEX_SPECIAL | \
1194 GIT_GLOB_SPECIAL | GIT_PATHSPEC_MAGIC)
1195 #define isxdigit(x) (hexval_table[(unsigned char)(x)] != -1)
1196 #define tolower(x) sane_case((unsigned char)(x), 0x20)
1197 #define toupper(x) sane_case((unsigned char)(x), 0)
1198 #define is_pathspec_magic(x) sane_istest(x,GIT_PATHSPEC_MAGIC)
1200 static inline int sane_case(int x, int high)
1202 if (sane_istest(x, GIT_ALPHA))
1203 x = (x & ~0x20) | high;
1204 return x;
1207 static inline int sane_iscase(int x, int is_lower)
1209 if (!sane_istest(x, GIT_ALPHA))
1210 return 0;
1212 if (is_lower)
1213 return (x & 0x20) != 0;
1214 else
1215 return (x & 0x20) == 0;
1219 * Like skip_prefix, but compare case-insensitively. Note that the comparison
1220 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
1221 * locale-specific conversions).
1223 static inline int skip_iprefix(const char *str, const char *prefix,
1224 const char **out)
1226 do {
1227 if (!*prefix) {
1228 *out = str;
1229 return 1;
1231 } while (tolower(*str++) == tolower(*prefix++));
1232 return 0;
1235 static inline int strtoul_ui(char const *s, int base, unsigned int *result)
1237 unsigned long ul;
1238 char *p;
1240 errno = 0;
1241 /* negative values would be accepted by strtoul */
1242 if (strchr(s, '-'))
1243 return -1;
1244 ul = strtoul(s, &p, base);
1245 if (errno || *p || p == s || (unsigned int) ul != ul)
1246 return -1;
1247 *result = ul;
1248 return 0;
1251 static inline int strtol_i(char const *s, int base, int *result)
1253 long ul;
1254 char *p;
1256 errno = 0;
1257 ul = strtol(s, &p, base);
1258 if (errno || *p || p == s || (int) ul != ul)
1259 return -1;
1260 *result = ul;
1261 return 0;
1264 void git_stable_qsort(void *base, size_t nmemb, size_t size,
1265 int(*compar)(const void *, const void *));
1266 #ifdef INTERNAL_QSORT
1267 #define qsort git_stable_qsort
1268 #endif
1270 #define QSORT(base, n, compar) sane_qsort((base), (n), sizeof(*(base)), compar)
1271 static inline void sane_qsort(void *base, size_t nmemb, size_t size,
1272 int(*compar)(const void *, const void *))
1274 if (nmemb > 1)
1275 qsort(base, nmemb, size, compar);
1278 #define STABLE_QSORT(base, n, compar) \
1279 git_stable_qsort((base), (n), sizeof(*(base)), compar)
1281 #ifndef HAVE_ISO_QSORT_S
1282 int git_qsort_s(void *base, size_t nmemb, size_t size,
1283 int (*compar)(const void *, const void *, void *), void *ctx);
1284 #define qsort_s git_qsort_s
1285 #endif
1287 #define QSORT_S(base, n, compar, ctx) do { \
1288 if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
1289 BUG("qsort_s() failed"); \
1290 } while (0)
1292 #ifndef REG_STARTEND
1293 #error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
1294 #endif
1296 static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
1297 size_t nmatch, regmatch_t pmatch[], int eflags)
1299 assert(nmatch > 0 && pmatch);
1300 pmatch[0].rm_so = 0;
1301 pmatch[0].rm_eo = size;
1302 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
1305 #ifndef DIR_HAS_BSD_GROUP_SEMANTICS
1306 # define FORCE_DIR_SET_GID S_ISGID
1307 #else
1308 # define FORCE_DIR_SET_GID 0
1309 #endif
1311 #ifdef NO_NSEC
1312 #undef USE_NSEC
1313 #define ST_CTIME_NSEC(st) 0
1314 #define ST_MTIME_NSEC(st) 0
1315 #else
1316 #ifdef USE_ST_TIMESPEC
1317 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
1318 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
1319 #else
1320 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
1321 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
1322 #endif
1323 #endif
1325 #ifdef UNRELIABLE_FSTAT
1326 #define fstat_is_reliable() 0
1327 #else
1328 #define fstat_is_reliable() 1
1329 #endif
1331 #ifndef va_copy
1333 * Since an obvious implementation of va_list would be to make it a
1334 * pointer into the stack frame, a simple assignment will work on
1335 * many systems. But let's try to be more portable.
1337 #ifdef __va_copy
1338 #define va_copy(dst, src) __va_copy(dst, src)
1339 #else
1340 #define va_copy(dst, src) ((dst) = (src))
1341 #endif
1342 #endif
1344 /* usage.c: only to be used for testing BUG() implementation (see test-tool) */
1345 extern int BUG_exit_code;
1347 /* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
1348 extern int bug_called_must_BUG;
1350 __attribute__((format (printf, 3, 4))) NORETURN
1351 void BUG_fl(const char *file, int line, const char *fmt, ...);
1352 #define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
1353 __attribute__((format (printf, 3, 4)))
1354 void bug_fl(const char *file, int line, const char *fmt, ...);
1355 #define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1356 #define BUG_if_bug(...) do { \
1357 if (bug_called_must_BUG) \
1358 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1359 } while (0)
1361 #ifndef FSYNC_METHOD_DEFAULT
1362 #ifdef __APPLE__
1363 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1364 #else
1365 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1366 #endif
1367 #endif
1369 enum fsync_action {
1370 FSYNC_WRITEOUT_ONLY,
1371 FSYNC_HARDWARE_FLUSH
1375 * Issues an fsync against the specified file according to the specified mode.
1377 * FSYNC_WRITEOUT_ONLY attempts to use interfaces available on some operating
1378 * systems to flush the OS cache without issuing a flush command to the storage
1379 * controller. If those interfaces are unavailable, the function fails with
1380 * ENOSYS.
1382 * FSYNC_HARDWARE_FLUSH does an OS writeout and hardware flush to ensure that
1383 * changes are durable. It is not expected to fail.
1385 int git_fsync(int fd, enum fsync_action action);
1388 * Writes out trace statistics for fsync using the trace2 API.
1390 void trace_git_fsync_stats(void);
1393 * Preserves errno, prints a message, but gives no warning for ENOENT.
1394 * Returns 0 on success, which includes trying to unlink an object that does
1395 * not exist.
1397 int unlink_or_warn(const char *path);
1399 * Tries to unlink file. Returns 0 if unlink succeeded
1400 * or the file already didn't exist. Returns -1 and
1401 * appends a message to err suitable for
1402 * 'error("%s", err->buf)' on error.
1404 int unlink_or_msg(const char *file, struct strbuf *err);
1406 * Preserves errno, prints a message, but gives no warning for ENOENT.
1407 * Returns 0 on success, which includes trying to remove a directory that does
1408 * not exist.
1410 int rmdir_or_warn(const char *path);
1412 * Calls the correct function out of {unlink,rmdir}_or_warn based on
1413 * the supplied file mode.
1415 int remove_or_warn(unsigned int mode, const char *path);
1418 * Call access(2), but warn for any error except "missing file"
1419 * (ENOENT or ENOTDIR).
1421 #define ACCESS_EACCES_OK (1U << 0)
1422 int access_or_warn(const char *path, int mode, unsigned flag);
1423 int access_or_die(const char *path, int mode, unsigned flag);
1425 /* Warn on an inaccessible file if errno indicates this is an error */
1426 int warn_on_fopen_errors(const char *path);
1429 * Open with O_NOFOLLOW, or equivalent. Note that the fallback equivalent
1430 * may be racy. Do not use this as protection against an attacker who can
1431 * simultaneously create paths.
1433 int open_nofollow(const char *path, int flags);
1435 #ifndef SHELL_PATH
1436 # define SHELL_PATH "/bin/sh"
1437 #endif
1439 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
1440 static inline void flockfile(FILE *fh)
1442 ; /* nothing */
1444 static inline void funlockfile(FILE *fh)
1446 ; /* nothing */
1448 #define getc_unlocked(fh) getc(fh)
1449 #endif
1451 #ifdef FILENO_IS_A_MACRO
1452 int git_fileno(FILE *stream);
1453 # ifndef COMPAT_CODE_FILENO
1454 # undef fileno
1455 # define fileno(p) git_fileno(p)
1456 # endif
1457 #endif
1459 #ifdef NEED_ACCESS_ROOT_HANDLER
1460 int git_access(const char *path, int mode);
1461 # ifndef COMPAT_CODE_ACCESS
1462 # ifdef access
1463 # undef access
1464 # endif
1465 # define access(path, mode) git_access(path, mode)
1466 # endif
1467 #endif
1470 * Our code often opens a path to an optional file, to work on its
1471 * contents when we can successfully open it. We can ignore a failure
1472 * to open if such an optional file does not exist, but we do want to
1473 * report a failure in opening for other reasons (e.g. we got an I/O
1474 * error, or the file is there, but we lack the permission to open).
1476 * Call this function after seeing an error from open() or fopen() to
1477 * see if the errno indicates a missing file that we can safely ignore.
1479 static inline int is_missing_file_error(int errno_)
1481 return (errno_ == ENOENT || errno_ == ENOTDIR);
1484 int cmd_main(int, const char **);
1487 * Intercept all calls to exit() and route them to trace2 to
1488 * optionally emit a message before calling the real exit().
1490 int common_exit(const char *file, int line, int code);
1491 #define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
1494 * You can mark a stack variable with UNLEAK(var) to avoid it being
1495 * reported as a leak by tools like LSAN or valgrind. The argument
1496 * should generally be the variable itself (not its address and not what
1497 * it points to). It's safe to use this on pointers which may already
1498 * have been freed, or on pointers which may still be in use.
1500 * Use this _only_ for a variable that leaks by going out of scope at
1501 * program exit (so only from cmd_* functions or their direct helpers).
1502 * Normal functions, especially those which may be called multiple
1503 * times, should actually free their memory. This is only meant as
1504 * an annotation, and does nothing in non-leak-checking builds.
1506 #ifdef SUPPRESS_ANNOTATED_LEAKS
1507 void unleak_memory(const void *ptr, size_t len);
1508 #define UNLEAK(var) unleak_memory(&(var), sizeof(var))
1509 #else
1510 #define UNLEAK(var) do {} while (0)
1511 #endif
1513 #define z_const
1514 #include <zlib.h>
1516 #if ZLIB_VERNUM < 0x1290
1518 * This is uncompress2, which is only available in zlib >= 1.2.9
1519 * (released as of early 2017). See compat/zlib-uncompress2.c.
1521 int uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
1522 uLong *sourceLen);
1523 #endif
1526 * This include must come after system headers, since it introduces macros that
1527 * replace system names.
1529 #include "banned.h"
1532 * container_of - Get the address of an object containing a field.
1534 * @ptr: pointer to the field.
1535 * @type: type of the object.
1536 * @member: name of the field within the object.
1538 #define container_of(ptr, type, member) \
1539 ((type *) ((char *)(ptr) - offsetof(type, member)))
1542 * helper function for `container_of_or_null' to avoid multiple
1543 * evaluation of @ptr
1545 static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1547 return ptr ? (char *)ptr - offset : NULL;
1551 * like `container_of', but allows returned value to be NULL
1553 #define container_of_or_null(ptr, type, member) \
1554 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1557 * like offsetof(), but takes a pointer to a variable of type which
1558 * contains @member, instead of a specified type.
1559 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1560 * everywhere.
1562 #if defined(__GNUC__) /* clang sets this, too */
1563 #define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1564 #else /* !__GNUC__ */
1565 #define OFFSETOF_VAR(ptr, member) \
1566 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1567 #endif /* !__GNUC__ */
1569 void sleep_millisec(int millisec);
1572 * Generate len bytes from the system cryptographically secure PRNG.
1573 * Returns 0 on success and -1 on error, setting errno. The inability to
1574 * satisfy the full request is an error.
1576 int csprng_bytes(void *buf, size_t len);
1578 #endif