blob: 79977caed6277a36471e57115aac928ac6c7bddc [file] [log] [blame]
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001#ifndef GIT_COMPAT_UTIL_H
2#define GIT_COMPAT_UTIL_H
3
brian m. carlson7bc341e2021-12-01 01:40:50 +00004#if __STDC_VERSION__ - 0 < 199901L
5/*
6 * Git is in a testing period for mandatory C99 support in the compiler. If
7 * your compiler is reasonably recent, you can try to enable C99 support (or,
8 * for MSVC, C11 support). If you encounter a problem and can't enable C99
9 * support with your compiler (such as with "-std=gnu99") and don't have access
10 * to one with this support, such as GCC or Clang, you can remove this #if
11 * directive, but please report the details of your system to
12 * git@vger.kernel.org.
13 */
14#error "Required C99 support is in a test phase. Please see git-compat-util.h for more details."
15#endif
16
Jeff Hostetler556702f2019-06-25 07:49:40 -070017#ifdef USE_MSVC_CRTDBG
18/*
19 * For these to work they must appear very early in each
20 * file -- before most of the standard header files.
21 */
22#include <stdlib.h>
23#include <crtdbg.h>
24#endif
25
Martin Waitzb97e9112007-02-17 10:13:10 +010026#define _FILE_OFFSET_BITS 64
27
Elia Pinto89c855e2015-04-30 14:44:14 +020028
29/* Derived from Linux "Features Test Macro" header
30 * Convenience macros to test the versions of gcc (or
31 * a compatible compiler).
32 * Use them like this:
33 * #if GIT_GNUC_PREREQ (2,8)
34 * ... code requiring gcc 2.8 or later ...
35 * #endif
36*/
37#if defined(__GNUC__) && defined(__GNUC_MINOR__)
38# define GIT_GNUC_PREREQ(maj, min) \
39 ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
40#else
41 #define GIT_GNUC_PREREQ(maj, min) 0
42#endif
43
44
Junio C Hamano8f1d2e62006-01-07 01:33:54 -080045#ifndef FLEX_ARRAY
Junio C Hamano8e973992007-11-20 12:08:06 -080046/*
47 * See if our compiler is known to support flexible array members.
48 */
Junio C Hamanodeefc2d2021-12-08 17:39:39 -080049
50/*
51 * Check vendor specific quirks first, before checking the
52 * __STDC_VERSION__, as vendor compilers can lie and we need to be
53 * able to work them around. Note that by not defining FLEX_ARRAY
54 * here, we can fall back to use the "safer but a bit wasteful" one
55 * later.
56 */
57#if defined(__SUNPRO_C) && (__SUNPRO_C <= 0x580)
Junio C Hamano8e973992007-11-20 12:08:06 -080058#elif defined(__GNUC__)
59# if (__GNUC__ >= 3)
60# define FLEX_ARRAY /* empty */
61# else
62# define FLEX_ARRAY 0 /* older GNU extension */
63# endif
Junio C Hamanodeefc2d2021-12-08 17:39:39 -080064#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
65# define FLEX_ARRAY /* empty */
Junio C Hamano8e973992007-11-20 12:08:06 -080066#endif
67
68/*
69 * Otherwise, default to safer but a bit wasteful traditional style
70 */
71#ifndef FLEX_ARRAY
72# define FLEX_ARRAY 1
Junio C Hamano8f1d2e62006-01-07 01:33:54 -080073#endif
74#endif
75
Elia Pinto89c855e2015-04-30 14:44:14 +020076
77/*
78 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
79 * @cond: the compile-time condition which must be true.
80 *
81 * Your compile will fail if the condition isn't true, or can't be evaluated
82 * by the compiler. This can be used in an expression: its value is "0".
83 *
84 * Example:
85 * #define foo_to_char(foo) \
86 * ((char *)(foo) \
87 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
88 */
89#define BUILD_ASSERT_OR_ZERO(cond) \
90 (sizeof(char [1 - 2*!(cond)]) - 1)
91
Charles Baileye2c6f7c2015-06-24 23:12:07 +010092#if GIT_GNUC_PREREQ(3, 1)
Elia Pinto89c855e2015-04-30 14:44:14 +020093 /* &arr[0] degrades to a pointer: a different type from an array */
94# define BARF_UNLESS_AN_ARRAY(arr) \
95 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
96 __typeof__(&(arr)[0])))
Charles Baileye2c6f7c2015-06-24 23:12:07 +010097#else
98# define BARF_UNLESS_AN_ARRAY(arr) 0
Elia Pinto89c855e2015-04-30 14:44:14 +020099#endif
100/*
101 * ARRAY_SIZE - get the number of elements in a visible array
Beat Bolli68b69212019-10-11 20:24:54 +0200102 * @x: the array whose size you want.
Elia Pinto89c855e2015-04-30 14:44:14 +0200103 *
104 * This does not work on pointers, or arrays declared as [], or
105 * function parameters. With correct compiler support, such usage
106 * will cause a build error (see the build_assert_or_zero macro).
107 */
108#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
109
Pierre Habouzitf630cfd2009-07-22 23:34:34 +0200110#define bitsizeof(x) (CHAR_BIT * sizeof(x))
Junio C Hamanob4f2a6a2006-03-09 11:58:05 -0800111
Erik Faye-Lundc03c8312010-10-05 09:24:10 +0200112#define maximum_signed_value_of_type(a) \
113 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
114
Jonathan Nieder1368f652010-10-10 21:59:26 -0500115#define maximum_unsigned_value_of_type(a) \
116 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
117
Erik Faye-Lundc03c8312010-10-05 09:24:10 +0200118/*
119 * Signed integer overflow is undefined in C, so here's a helper macro
120 * to detect if the sum of two integers will overflow.
121 *
122 * Requires: a >= 0, typeof(a) equals typeof(b)
123 */
124#define signed_add_overflows(a, b) \
125 ((b) > maximum_signed_value_of_type(a) - (a))
126
Jonathan Nieder1368f652010-10-10 21:59:26 -0500127#define unsigned_add_overflows(a, b) \
128 ((b) > maximum_unsigned_value_of_type(a) - (a))
129
Jeff King320d0b42016-02-19 06:21:19 -0500130/*
131 * Returns true if the multiplication of "a" and "b" will
132 * overflow. The types of "a" and "b" must match and must be unsigned.
133 * Note that this macro evaluates "a" twice!
134 */
135#define unsigned_mult_overflows(a, b) \
136 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
137
Johannes Schindeline2ffeae2021-11-02 15:46:09 +0000138/*
139 * Returns true if the left shift of "a" by "shift" bits will
140 * overflow. The type of "a" must be unsigned.
141 */
142#define unsigned_left_shift_overflows(a, shift) \
143 ((shift) < bitsizeof(a) && \
144 (a) > maximum_unsigned_value_of_type(a) >> (shift))
145
Nicolas Pitre8723f212007-04-09 01:06:29 -0400146#ifdef __GNUC__
147#define TYPEOF(x) (__typeof__(x))
148#else
149#define TYPEOF(x)
150#endif
151
Pierre Habouzitf630cfd2009-07-22 23:34:34 +0200152#define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
Pierre Habouzitdb7244b2007-11-07 11:20:27 +0100153#define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
Nicolas Pitre8723f212007-04-09 01:06:29 -0400154
Pierre Habouzit98cb6f32009-07-22 23:34:35 +0200155#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
156
Andy Whitcroftcf606e32007-05-15 17:33:25 +0100157/* Approximation of the length of the decimal representation of this type. */
158#define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
159
Carlo Marcelo Arenas Belón9e124002021-11-27 10:15:32 +0000160#ifdef __MINGW64__
161#define _POSIX_C_SOURCE 1
162#elif defined(__sun__)
Brandon Casey4cb18a42009-06-05 18:36:13 -0500163 /*
164 * On Solaris, when _XOPEN_EXTENDED is set, its header file
165 * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
166 * setting to say we are XPG5 or XPG6. Also on Solaris,
167 * XPG6 programs must be compiled with a c99 compiler, while
168 * non XPG6 programs must be compiled with a pre-c99 compiler.
169 */
170# if __STDC_VERSION__ - 0 >= 199901L
171# define _XOPEN_SOURCE 600
172# else
173# define _XOPEN_SOURCE 500
174# endif
YONETANI Tomokazu6555b192010-04-02 16:52:09 +0900175#elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
Joachim Schmitz6c109902012-09-19 12:03:30 +0200176 !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
Ramsay Jones3a0a3a82014-11-23 17:14:55 +0000177 !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
178 !defined(__CYGWIN__)
Junio C Hamano85023572006-12-19 14:34:12 -0800179#define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
180#define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
Terje Sten Bjerksethc902c9a2006-12-20 17:32:21 -0800181#endif
Jason Riedyfb952202007-01-15 17:34:49 -0800182#define _ALL_SOURCE 1
183#define _GNU_SOURCE 1
184#define _BSD_SOURCE 1
Sergey Senozhatskyf978a992014-09-14 14:33:35 +0900185#define _DEFAULT_SOURCE 1
Patrick Welche9a695fb2009-04-26 14:49:00 +0100186#define _NETBSD_SOURCE 1
Brandon Casey9398b852009-07-10 12:10:44 -0500187#define _SGI_SOURCE 1
Junio C Hamano85023572006-12-19 14:34:12 -0800188
Jonathan Nieder380395d2013-05-02 20:26:08 +0100189#if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
Johannes Schindelin3571e782018-10-03 12:43:43 -0700190# if !defined(_WIN32_WINNT)
Johannes Schindelin2939a1f2018-10-03 12:43:44 -0700191# define _WIN32_WINNT 0x0600
Ramsay Jones41f29992013-01-31 18:28:35 +0000192# endif
Marius Storm-Olsen435bdf82009-09-16 10:20:26 +0200193#define WIN32_LEAN_AND_MEAN /* stops windows.h including winsock.h */
194#include <winsock2.h>
Carlo Marcelo Arenas Belónbb390b12021-09-14 00:26:00 -0700195#ifndef NO_UNIX_SOCKETS
196#include <afunix.h>
197#endif
Marius Storm-Olsen435bdf82009-09-16 10:20:26 +0200198#include <windows.h>
Jonathan Nieder380395d2013-05-02 20:26:08 +0100199#define GIT_WINDOWS_NATIVE
Marius Storm-Olsen435bdf82009-09-16 10:20:26 +0200200#endif
201
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800202#include <unistd.h>
203#include <stdio.h>
204#include <sys/stat.h>
205#include <fcntl.h>
206#include <stddef.h>
207#include <stdlib.h>
208#include <stdarg.h>
209#include <string.h>
David Michaelb3e103d2012-12-14 14:57:01 -0500210#ifdef HAVE_STRINGS_H
Joachim Schmitz6c109902012-09-19 12:03:30 +0200211#include <strings.h> /* for strcasecmp() */
212#endif
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800213#include <errno.h>
214#include <limits.h>
Junio C Hamanob2d05e02012-12-18 09:35:33 -0800215#ifdef NEEDS_SYS_PARAM_H
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800216#include <sys/param.h>
David Michael6ede7202012-12-14 14:56:58 -0500217#endif
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800218#include <sys/types.h>
219#include <dirent.h>
Junio C Hamano85023572006-12-19 14:34:12 -0800220#include <sys/time.h>
221#include <time.h>
222#include <signal.h>
Johannes Sixtf4626df2007-12-01 21:24:59 +0100223#include <assert.h>
224#include <regex.h>
225#include <utime.h>
Mike Pape088d8802010-11-04 02:35:10 +0100226#include <syslog.h>
Đoàn Trần Công Danh2648ccc2018-11-14 08:10:43 +0700227#if !defined(NO_POLL_H)
228#include <poll.h>
229#elif !defined(NO_SYS_POLL_H)
Erik Faye-Lundfdc12112010-11-04 02:35:21 +0100230#include <sys/poll.h>
Markus Duft28449232010-10-27 10:39:52 +0200231#else
Đoàn Trần Công Danh2648ccc2018-11-14 08:10:43 +0700232/* Pull the compat stuff */
Markus Duft28449232010-10-27 10:39:52 +0200233#include <poll.h>
234#endif
Kyle J. McKay95290802015-03-07 23:14:36 -0800235#ifdef HAVE_BSD_SYSCTL
236#include <sys/sysctl.h>
237#endif
Ramsay Jones2f0aaaf2013-05-30 00:53:28 +0100238
Ævar Arnfjörð Bjarmason9fd512c2022-05-16 20:10:59 +0000239/* Used by compat/win32/path-utils.h, and more */
240static inline int is_xplatform_dir_sep(int c)
241{
242 return c == '/' || c == '\\';
243}
244
Torsten Bögershausen496f2562017-07-03 16:41:37 +0200245#if defined(__CYGWIN__)
Torsten Bögershausen1cadad62018-12-15 05:33:30 +0100246#include "compat/win32/path-utils.h"
Torsten Bögershausen496f2562017-07-03 16:41:37 +0200247#endif
Vincent van Ravesteijncfc755d2011-10-31 20:12:42 +0100248#if defined(__MINGW32__)
249/* pull in Windows compatibility stuff */
Torsten Bögershausen1cadad62018-12-15 05:33:30 +0100250#include "compat/win32/path-utils.h"
Vincent van Ravesteijncfc755d2011-10-31 20:12:42 +0100251#include "compat/mingw.h"
252#elif defined(_MSC_VER)
Sven Strickroth22c36342019-04-08 13:26:16 +0200253#include "compat/win32/path-utils.h"
Vincent van Ravesteijncfc755d2011-10-31 20:12:42 +0100254#include "compat/msvc.h"
255#else
Nguyễn Thái Ngọc Duy1e8fef62015-03-08 17:12:46 +0700256#include <sys/utsname.h>
Johannes Sixtf4626df2007-12-01 21:24:59 +0100257#include <sys/wait.h>
Jonathan Niederebae9ff2011-03-18 15:23:52 -0500258#include <sys/resource.h>
Junio C Hamano85023572006-12-19 14:34:12 -0800259#include <sys/socket.h>
Johannes Sixt80bbe722007-11-13 21:05:01 +0100260#include <sys/ioctl.h>
Nguyễn Thái Ngọc Duyeb800422010-01-11 17:41:01 +0700261#include <termios.h>
Robert Schiele26009732008-01-24 19:34:46 +0100262#ifndef NO_SYS_SELECT_H
Johannes Sixt80bbe722007-11-13 21:05:01 +0100263#include <sys/select.h>
Robert Schiele26009732008-01-24 19:34:46 +0100264#endif
Junio C Hamano85023572006-12-19 14:34:12 -0800265#include <netinet/in.h>
266#include <netinet/tcp.h>
267#include <arpa/inet.h>
268#include <netdb.h>
269#include <pwd.h>
Jeff Kinge2770972011-12-10 05:34:14 -0500270#include <sys/un.h>
Markus Duft28449232010-10-27 10:39:52 +0200271#ifndef NO_INTTYPES_H
Jason Riedy007e2ba2007-01-25 13:11:40 -0800272#include <inttypes.h>
Markus Duft28449232010-10-27 10:39:52 +0200273#else
274#include <stdint.h>
275#endif
brian m. carlson05cd9882022-01-17 21:56:16 +0000276#ifdef HAVE_ARC4RANDOM_LIBBSD
277#include <bsd/stdlib.h>
278#endif
279#ifdef HAVE_GETRANDOM
280#include <sys/random.h>
281#endif
Joachim Schmitz6c109902012-09-19 12:03:30 +0200282#ifdef NO_INTPTR_T
283/*
Johannes Schindelinc70e1b02018-08-08 04:49:58 -0700284 * On I16LP32, ILP32 and LP64 "long" is the safe bet, however
Joachim Schmitz6c109902012-09-19 12:03:30 +0200285 * on LLP86, IL33LLP64 and P64 it needs to be "long long",
286 * while on IP16 and IP16L32 it is "int" (resp. "short")
287 * Size needs to match (or exceed) 'sizeof(void *)'.
288 * We can't take "long long" here as not everybody has it.
289 */
290typedef long intptr_t;
291typedef unsigned long uintptr_t;
292#endif
Jason Riedyfb952202007-01-15 17:34:49 -0800293#undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
Junio C Hamano85023572006-12-19 14:34:12 -0800294#include <grp.h>
Jason Riedyfb952202007-01-15 17:34:49 -0800295#define _ALL_SOURCE 1
Ramsay Jones41b20012007-03-03 18:28:52 +0000296#endif
Junio C Hamano85023572006-12-19 14:34:12 -0800297
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200298/* used on Mac OS X */
299#ifdef PRECOMPOSE_UNICODE
300#include "compat/precompose_utf8.h"
301#else
Torsten Bögershausen5c327502021-02-03 17:28:23 +0100302static inline const char *precompose_argv_prefix(int argc, const char **argv, const char *prefix)
Junio C Hamano15b52a42020-08-06 17:25:37 -0700303{
Torsten Bögershausen5c327502021-02-03 17:28:23 +0100304 return prefix;
Junio C Hamano15b52a42020-08-06 17:25:37 -0700305}
Torsten Bögershausen50207742021-04-04 08:17:45 +0200306static inline const char *precompose_string_if_needed(const char *in)
307{
308 return in;
309}
310
Jeff Kingfdf72962015-10-04 23:45:26 -0400311#define probe_utf8_pathname_composition()
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200312#endif
313
Joachim Schmitz0539ecf2012-08-24 12:31:03 +0200314#ifdef MKDIR_WO_TRAILING_SLASH
315#define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
Denton Liu55454422019-04-29 04:28:14 -0400316int compat_mkdir_wo_trailing_slash(const char*, mode_t);
Joachim Schmitz0539ecf2012-08-24 12:31:03 +0200317#endif
318
Joachim Schmitz7f9e8482012-09-08 18:54:34 +0200319#ifdef NO_STRUCT_ITIMERVAL
320struct itimerval {
321 struct timeval it_interval;
322 struct timeval it_value;
Jonas 'Sortie' Termansen981ff522014-08-29 09:42:33 -0700323};
Joachim Schmitz7f9e8482012-09-08 18:54:34 +0200324#endif
325
326#ifdef NO_SETITIMER
Junio C Hamano15b52a42020-08-06 17:25:37 -0700327static inline int setitimer(int which, const struct itimerval *value, struct itimerval *newvalue) {
Junio C Hamano14639a42020-12-15 13:26:17 -0800328 return 0; /* pretend success */
Junio C Hamano15b52a42020-08-06 17:25:37 -0700329}
Joachim Schmitz7f9e8482012-09-08 18:54:34 +0200330#endif
331
David Aguilare1c06882009-05-31 01:35:51 -0700332#ifndef NO_LIBGEN_H
333#include <libgen.h>
334#else
335#define basename gitbasename
Denton Liu55454422019-04-29 04:28:14 -0400336char *gitbasename(char *);
Johannes Schindelin824682a2016-01-12 08:57:36 +0100337#define dirname gitdirname
Denton Liu55454422019-04-29 04:28:14 -0400338char *gitdirname(char *);
David Aguilare1c06882009-05-31 01:35:51 -0700339#endif
340
Junio C Hamano85023572006-12-19 14:34:12 -0800341#ifndef NO_ICONV
342#include <iconv.h>
343#endif
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800344
Robert Shearman684ec6c2008-07-09 22:29:00 +0100345#ifndef NO_OPENSSL
Kyle J. McKay88c03eb2015-02-06 01:35:31 -0800346#ifdef __APPLE__
Eric Sunshineb195aa02014-12-16 18:19:36 -0500347#define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
Kyle J. McKay88c03eb2015-02-06 01:35:31 -0800348#include <AvailabilityMacros.h>
349#undef DEPRECATED_ATTRIBUTE
350#define DEPRECATED_ATTRIBUTE
351#undef __AVAILABILITY_MACROS_USES_AVAILABILITY
352#endif
Robert Shearman684ec6c2008-07-09 22:29:00 +0100353#include <openssl/ssl.h>
354#include <openssl/err.h>
355#endif
356
Nguyễn Thái Ngọc Duy9806f5a2018-04-15 17:36:17 +0200357#ifdef HAVE_SYSINFO
358# include <sys/sysinfo.h>
359#endif
360
David Michael3b130ade2013-02-25 14:30:19 -0500361/* On most systems <netdb.h> would have given us this, but
362 * not on some systems (e.g. z/OS).
363 */
364#ifndef NI_MAXHOST
365#define NI_MAXHOST 1025
366#endif
367
368#ifndef NI_MAXSERV
369#define NI_MAXSERV 32
370#endif
371
Junio C Hamanod0c24492006-09-15 22:47:21 -0700372/* On most systems <limits.h> would have given us this, but
373 * not on some systems (e.g. GNU/Hurd).
374 */
375#ifndef PATH_MAX
376#define PATH_MAX 4096
377#endif
378
Johannes Schindelin28f4aee2017-04-26 21:29:42 +0200379typedef uintmax_t timestamp_t;
380#define PRItime PRIuMAX
381#define parse_timestamp strtoumax
382#define TIME_MAX UINTMAX_MAX
SZEDER Gábor2e09c012019-09-24 09:32:13 +0200383#define TIME_MIN 0
Johannes Schindelin1aeb7e72017-04-21 12:45:44 +0200384
Johannes Sixt80ba0742007-12-03 21:55:57 +0100385#ifndef PATH_SEP
386#define PATH_SEP ':'
387#endif
388
Chris Webbcb6a22c2010-04-13 10:07:13 +0100389#ifdef HAVE_PATHS_H
390#include <paths.h>
391#endif
392#ifndef _PATH_DEFPATH
393#define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
394#endif
395
Johannes Schindelin70fc5792018-10-30 11:40:04 -0700396#ifndef platform_core_config
397static inline int noop_core_config(const char *var, const char *value, void *cb)
398{
399 return 0;
400}
401#define platform_core_config noop_core_config
402#endif
403
Matheus Tavares684dd4c2020-12-10 10:27:55 -0300404int lstat_cache_aware_rmdir(const char *path);
405#if !defined(__MINGW32__) && !defined(_MSC_VER)
406#define rmdir lstat_cache_aware_rmdir
407#endif
408
Johannes Sixt25fe2172008-03-05 21:51:27 +0100409#ifndef has_dos_drive_prefix
René Scharfebf728342014-08-16 23:48:33 +0200410static inline int git_has_dos_drive_prefix(const char *path)
411{
412 return 0;
413}
414#define has_dos_drive_prefix git_has_dos_drive_prefix
Cezary Zawadkac2369bd2010-07-13 16:17:43 +0200415#endif
416
Johannes Schindelin2f36eed2016-01-12 08:57:22 +0100417#ifndef skip_dos_drive_prefix
418static inline int git_skip_dos_drive_prefix(char **path)
419{
420 return 0;
421}
422#define skip_dos_drive_prefix git_skip_dos_drive_prefix
423#endif
424
René Scharfebf728342014-08-16 23:48:33 +0200425static inline int git_is_dir_sep(int c)
426{
427 return c == '/';
428}
Ævar Arnfjörð Bjarmason9fd512c2022-05-16 20:10:59 +0000429#ifndef is_dir_sep
René Scharfebf728342014-08-16 23:48:33 +0200430#define is_dir_sep git_is_dir_sep
431#endif
432
433#ifndef offset_1st_component
434static inline int git_offset_1st_component(const char *path)
435{
436 return is_dir_sep(path[0]);
437}
438#define offset_1st_component git_offset_1st_component
Johannes Sixt25fe2172008-03-05 21:51:27 +0100439#endif
440
Johannes Schindelind2c84da2019-09-05 13:27:53 +0200441#ifndef is_valid_path
442#define is_valid_path(path) 1
443#endif
444
Johannes Schindelinbdc77d12022-03-02 11:06:24 +0100445#ifndef is_path_owned_by_current_user
Carlo Marcelo Arenas Belónae9abbb2022-05-12 18:00:18 -0700446
447#ifdef __TANDEM
448#define ROOT_UID 65535
449#else
450#define ROOT_UID 0
451#endif
452
453/*
454 * Do not use this function when
455 * (1) geteuid() did not say we are running as 'root', or
456 * (2) using this function will compromise the system.
457 *
458 * PORTABILITY WARNING:
459 * This code assumes uid_t is unsigned because that is what sudo does.
460 * If your uid_t type is signed and all your ids are positive then it
461 * should all work fine.
462 * If your version of sudo uses negative values for uid_t or it is
463 * buggy and return an overflowed value in SUDO_UID, then git might
464 * fail to grant access to your repository properly or even mistakenly
465 * grant access to someone else.
466 * In the unlikely scenario this happened to you, and that is how you
467 * got to this message, we would like to know about it; so sent us an
468 * email to git@vger.kernel.org indicating which platform you are
469 * using and which version of sudo, so we can improve this logic and
470 * maybe provide you with a patch that would prevent this issue again
471 * in the future.
472 */
473static inline void extract_id_from_env(const char *env, uid_t *id)
474{
475 const char *real_uid = getenv(env);
476
477 /* discard anything empty to avoid a more complex check below */
478 if (real_uid && *real_uid) {
479 char *endptr = NULL;
480 unsigned long env_id;
481
482 errno = 0;
483 /* silent overflow errors could trigger a bug here */
484 env_id = strtoul(real_uid, &endptr, 10);
485 if (!*endptr && !errno)
486 *id = env_id;
487 }
488}
489
Johannes Schindelinbdc77d12022-03-02 11:06:24 +0100490static inline int is_path_owned_by_current_uid(const char *path)
491{
492 struct stat st;
Carlo Marcelo Arenas Belónae9abbb2022-05-12 18:00:18 -0700493 uid_t euid;
494
Johannes Schindelinbdc77d12022-03-02 11:06:24 +0100495 if (lstat(path, &st))
496 return 0;
Carlo Marcelo Arenas Belónae9abbb2022-05-12 18:00:18 -0700497
498 euid = geteuid();
499 if (euid == ROOT_UID)
Carlo Marcelo Arenas Belón6b11e3d2022-06-17 13:23:38 -0700500 {
501 if (st.st_uid == ROOT_UID)
502 return 1;
503 else
504 extract_id_from_env("SUDO_UID", &euid);
505 }
Carlo Marcelo Arenas Belónae9abbb2022-05-12 18:00:18 -0700506
507 return st.st_uid == euid;
Johannes Schindelinbdc77d12022-03-02 11:06:24 +0100508}
509
510#define is_path_owned_by_current_user is_path_owned_by_current_uid
511#endif
512
Theo Niessinkd1c69252011-05-27 18:00:39 +0200513#ifndef find_last_dir_sep
René Scharfebf728342014-08-16 23:48:33 +0200514static inline char *git_find_last_dir_sep(const char *path)
515{
516 return strrchr(path, '/');
517}
518#define find_last_dir_sep git_find_last_dir_sep
Theo Niessinkd1c69252011-05-27 18:00:39 +0200519#endif
520
Andras Kucsma05ac8582020-03-27 00:36:43 +0000521#ifndef has_dir_sep
522static inline int git_has_dir_sep(const char *path)
523{
524 return !!strchr(path, '/');
525}
526#define has_dir_sep(path) git_has_dir_sep(path)
527#endif
528
Johannes Schindelin501afcb2018-10-15 02:47:08 -0700529#ifndef query_user_email
530#define query_user_email() NULL
531#endif
532
Randall S. Becker1305ef32019-01-03 16:03:50 -0500533#ifdef __TANDEM
534#include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
535#include <floss.h(floss_getpwuid)>
536#ifndef NSIG
537/*
538 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
539 * known, by detective work using kill -l as a list is all signals
540 * instead of signal.h where it should be.
541 */
542# define NSIG 100
543#endif
544#endif
545
Ramkumar Ramachandrae4ac9532011-11-15 23:01:09 +0530546#if defined(__HP_cc) && (__HP_cc >= 61000)
Michal Rokosb6ab3492011-03-07 13:13:15 +0100547#define NORETURN __attribute__((noreturn))
548#define NORETURN_PTR
Junio C Hamano6520c842011-06-18 18:07:03 -0700549#elif defined(__GNUC__) && !defined(NO_NORETURN)
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800550#define NORETURN __attribute__((__noreturn__))
Erik Faye-Lund18660bc2009-09-30 18:05:50 +0000551#define NORETURN_PTR __attribute__((__noreturn__))
Ramsay Jonesaba7dea2010-01-20 19:45:12 +0000552#elif defined(_MSC_VER)
553#define NORETURN __declspec(noreturn)
554#define NORETURN_PTR
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800555#else
556#define NORETURN
Erik Faye-Lund18660bc2009-09-30 18:05:50 +0000557#define NORETURN_PTR
Andi Kleen8cd7ebc2014-07-04 16:43:49 -0700558#ifndef __GNUC__
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800559#ifndef __attribute__
560#define __attribute__(x)
561#endif
562#endif
Andi Kleen8cd7ebc2014-07-04 16:43:49 -0700563#endif
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800564
Ramsay Jones9fe3edc2013-07-18 21:02:12 +0100565/* The sentinel attribute is valid from gcc version 4.0 */
566#if defined(__GNUC__) && (__GNUC__ >= 4)
567#define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
568#else
569#define LAST_ARG_MUST_BE_NULL
570#endif
571
Carlo Marcelo Arenas Belónbbd8eb32018-10-23 14:50:19 -0700572#define MAYBE_UNUSED __attribute__((__unused__))
573
Nicolas Pitre51ea5512009-08-18 15:26:55 -0400574#include "compat/bswap.h"
575
Nguyễn Thái Ngọc Duycebcab12013-01-01 09:44:11 +0700576#include "wildmatch.h"
Nguyễn Thái Ngọc Duycebcab12013-01-01 09:44:11 +0700577
Ronnie Sahlberg9ccc0c02014-07-16 11:20:36 -0700578struct strbuf;
579
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800580/* General helper functions */
Denton Liu55454422019-04-29 04:28:14 -0400581NORETURN void usage(const char *err);
Denton Liub199d712019-04-29 04:28:20 -0400582NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
583NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
584NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
Ævar Arnfjörð Bjarmason18568ee2021-12-07 19:26:29 +0100585int die_message(const char *err, ...) __attribute__((format (printf, 1, 2)));
Ævar Arnfjörð Bjarmason24f6e6d2021-12-07 19:26:33 +0100586int die_message_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
Denton Liub199d712019-04-29 04:28:20 -0400587int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
588int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
589void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
590void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800591
Brian Gernhardtf2be0342013-08-05 11:59:23 -0400592#ifndef NO_OPENSSL
593#ifdef APPLE_COMMON_CRYPTO
594#include "compat/apple-common-crypto.h"
595#else
596#include <openssl/evp.h>
597#include <openssl/hmac.h>
598#endif /* APPLE_COMMON_CRYPTO */
599#include <openssl/x509v3.h>
600#endif /* NO_OPENSSL */
601
Carlo Marcelo Arenas Belón5b52d9f2022-04-04 21:28:26 -0700602#ifdef HAVE_OPENSSL_CSPRNG
603#include <openssl/rand.h>
604#endif
605
Jeff Kinge208f9c2012-12-15 12:37:36 -0500606/*
607 * Let callers be aware of the constant return value; this can help
Matt Kraai9798f7e2013-02-08 07:09:28 -0800608 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
Ævar Arnfjörð Bjarmasonb7ba8582022-02-21 17:05:26 +0100609 * because other compilers may be confused by this.
Jeff Kinge208f9c2012-12-15 12:37:36 -0500610 */
Jeff Kingff0a80a2014-05-06 11:17:50 -0400611#if defined(__GNUC__)
Jeff King87fe5df2014-05-06 11:14:42 -0400612static inline int const_error(void)
613{
614 return -1;
615}
616#define error(...) (error(__VA_ARGS__), const_error())
Jeff King4df5e912016-08-30 23:41:22 -0400617#define error_errno(...) (error_errno(__VA_ARGS__), const_error())
Jeff Kinge208f9c2012-12-15 12:37:36 -0500618#endif
619
Jeff King5710dcc2020-10-15 15:30:04 -0400620typedef void (*report_fn)(const char *, va_list params);
621
622void set_die_routine(NORETURN_PTR report_fn routine);
Ævar Arnfjörð Bjarmason18568ee2021-12-07 19:26:29 +0100623report_fn get_die_message_routine(void);
Jeff King5710dcc2020-10-15 15:30:04 -0400624void set_error_routine(report_fn routine);
625report_fn get_error_routine(void);
626void set_warn_routine(report_fn routine);
627report_fn get_warn_routine(void);
Denton Liu55454422019-04-29 04:28:14 -0400628void set_die_is_recursing_routine(int (*routine)(void));
Petr Baudis39a3f5e2006-06-24 04:34:38 +0200629
Denton Liu55454422019-04-29 04:28:14 -0400630int starts_with(const char *str, const char *prefix);
631int istarts_with(const char *str, const char *prefix);
Junio C Hamano698a68b2008-01-03 01:23:12 -0800632
Jeff Kingcf4fff52014-06-18 15:44:19 -0400633/*
634 * If the string "str" begins with the string found in "prefix", return 1.
635 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
636 * the string right after the prefix).
637 *
638 * Otherwise, return 0 and leave "out" untouched.
639 *
640 * Examples:
641 *
642 * [extract branch name, fail if not a branch]
643 * if (!skip_prefix(ref, "refs/heads/", &branch)
644 * return -1;
645 *
646 * [skip prefix if present, otherwise use whole string]
647 * skip_prefix(name, "refs/heads/", &name);
648 */
649static inline int skip_prefix(const char *str, const char *prefix,
650 const char **out)
Miklos Vajnafbca5832008-06-27 18:21:56 +0200651{
David Kastrupba399c42014-03-04 00:22:15 +0100652 do {
Jeff Kingcf4fff52014-06-18 15:44:19 -0400653 if (!*prefix) {
654 *out = str;
655 return 1;
656 }
David Kastrupba399c42014-03-04 00:22:15 +0100657 } while (*str++ == *prefix++);
Jeff Kingcf4fff52014-06-18 15:44:19 -0400658 return 0;
Miklos Vajnafbca5832008-06-27 18:21:56 +0200659}
660
Jeff King35480f02014-06-30 12:57:51 -0400661/*
Christian Couderafaef552017-12-09 21:40:07 +0100662 * If the string "str" is the same as the string in "prefix", then the "arg"
663 * parameter is set to the "def" parameter and 1 is returned.
664 * If the string "str" begins with the string found in "prefix" and then a
665 * "=" sign, then the "arg" parameter is set to "str + strlen(prefix) + 1"
666 * (i.e., to the point in the string right after the prefix and the "=" sign),
667 * and 1 is returned.
668 *
669 * Otherwise, return 0 and leave "arg" untouched.
670 *
671 * When we accept both a "--key" and a "--key=<val>" option, this function
672 * can be used instead of !strcmp(arg, "--key") and then
673 * skip_prefix(arg, "--key=", &arg) to parse such an option.
674 */
675int skip_to_optional_arg_default(const char *str, const char *prefix,
676 const char **arg, const char *def);
677
678static inline int skip_to_optional_arg(const char *str, const char *prefix,
679 const char **arg)
680{
681 return skip_to_optional_arg_default(str, prefix, arg, "");
682}
683
684/*
Jeff Kingae989a62016-06-23 13:33:57 -0400685 * Like skip_prefix, but promises never to read past "len" bytes of the input
686 * buffer, and returns the remaining number of bytes in "out" via "outlen".
687 */
688static inline int skip_prefix_mem(const char *buf, size_t len,
689 const char *prefix,
690 const char **out, size_t *outlen)
691{
692 size_t prefix_len = strlen(prefix);
693 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
694 *out = buf + prefix_len;
695 *outlen = len - prefix_len;
696 return 1;
697 }
698 return 0;
699}
700
701/*
Jeff King35480f02014-06-30 12:57:51 -0400702 * If buf ends with suffix, return 1 and subtract the length of the suffix
703 * from *len. Otherwise, return 0 and leave *len untouched.
704 */
705static inline int strip_suffix_mem(const char *buf, size_t *len,
706 const char *suffix)
707{
708 size_t suflen = strlen(suffix);
709 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
710 return 0;
711 *len -= suflen;
712 return 1;
713}
714
715/*
716 * If str ends with suffix, return 1 and set *len to the size of the string
717 * without the suffix. Otherwise, return 0 and set *len to the size of the
718 * string.
719 *
720 * Note that we do _not_ NUL-terminate str to the new length.
721 */
722static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
723{
724 *len = strlen(str);
725 return strip_suffix_mem(str, len, suffix);
726}
727
Jeff Kingf52a35f2014-06-30 12:58:08 -0400728static inline int ends_with(const char *str, const char *suffix)
729{
730 size_t len;
731 return strip_suffix(str, suffix, &len);
732}
733
René Scharfe568edcb2017-01-28 22:38:21 +0100734#define SWAP(a, b) do { \
735 void *_swap_a_ptr = &(a); \
736 void *_swap_b_ptr = &(b); \
737 unsigned char _swap_buffer[sizeof(a)]; \
738 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
739 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
740 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
741 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
742} while (0)
743
Janos Laubeb130a722009-03-13 16:50:45 +0100744#if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800745
746#ifndef PROT_READ
747#define PROT_READ 1
748#define PROT_WRITE 2
749#define MAP_PRIVATE 1
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800750#endif
751
Shawn O. Pearced6779122006-12-24 00:45:37 -0500752#define mmap git_mmap
753#define munmap git_munmap
Denton Liu55454422019-04-29 04:28:14 -0400754void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
755int git_munmap(void *start, size_t length);
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800756
Janos Laubeb130a722009-03-13 16:50:45 +0100757#else /* NO_MMAP || USE_WIN32_MMAP */
758
759#include <sys/mman.h>
760
761#endif /* NO_MMAP || USE_WIN32_MMAP */
762
763#ifdef NO_MMAP
764
Junio C Hamano5faaf242007-02-14 13:20:41 -0800765/* This value must be multiple of (pagesize * 2) */
Shawn O. Pearce8c825342006-12-24 00:46:13 -0500766#define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
767
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800768#else /* NO_MMAP */
769
Junio C Hamano5faaf242007-02-14 13:20:41 -0800770/* This value must be multiple of (pagesize * 2) */
Shawn O. Pearce22bac0e2007-01-04 22:28:08 -0500771#define DEFAULT_PACKED_GIT_WINDOW_SIZE \
772 (sizeof(void*) >= 8 \
773 ? 1 * 1024 * 1024 * 1024 \
774 : 32 * 1024 * 1024)
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800775
776#endif /* NO_MMAP */
777
Gary V. Vaughanfcf3a212010-05-14 09:31:39 +0000778#ifndef MAP_FAILED
779#define MAP_FAILED ((void *)-1)
780#endif
781
Junio C Hamanofdb2a2a2008-08-18 21:57:16 +0200782#ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
783#define on_disk_bytes(st) ((st).st_size)
784#else
785#define on_disk_bytes(st) ((st).st_blocks * 512)
786#endif
787
David Michaeld543d9c2014-12-03 21:24:17 -0500788#ifdef NEEDS_MODE_TRANSLATION
789#undef S_IFMT
790#undef S_IFREG
791#undef S_IFDIR
792#undef S_IFLNK
793#undef S_IFBLK
794#undef S_IFCHR
795#undef S_IFIFO
796#undef S_IFSOCK
797#define S_IFMT 0170000
798#define S_IFREG 0100000
799#define S_IFDIR 0040000
800#define S_IFLNK 0120000
801#define S_IFBLK 0060000
802#define S_IFCHR 0020000
803#define S_IFIFO 0010000
804#define S_IFSOCK 0140000
805#ifdef stat
806#undef stat
807#endif
808#define stat(path, buf) git_stat(path, buf)
Denton Liu55454422019-04-29 04:28:14 -0400809int git_stat(const char *, struct stat *);
David Michaeld543d9c2014-12-03 21:24:17 -0500810#ifdef fstat
811#undef fstat
812#endif
813#define fstat(fd, buf) git_fstat(fd, buf)
Denton Liu55454422019-04-29 04:28:14 -0400814int git_fstat(int, struct stat *);
David Michaeld543d9c2014-12-03 21:24:17 -0500815#ifdef lstat
816#undef lstat
817#endif
818#define lstat(path, buf) git_lstat(path, buf)
Denton Liu55454422019-04-29 04:28:14 -0400819int git_lstat(const char *, struct stat *);
David Michaeld543d9c2014-12-03 21:24:17 -0500820#endif
821
Shawn O. Pearce22bac0e2007-01-04 22:28:08 -0500822#define DEFAULT_PACKED_GIT_LIMIT \
David Turnerbe4ca292017-04-20 16:41:18 -0400823 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
Shawn O. Pearce8c825342006-12-24 00:46:13 -0500824
Stefan-W. Hahn69006792007-01-09 22:04:12 +0100825#ifdef NO_PREAD
826#define pread git_pread
Denton Liu55454422019-04-29 04:28:14 -0400827ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
Stefan-W. Hahn69006792007-01-09 22:04:12 +0100828#endif
Steffen Prohaska14086b02007-11-17 20:48:14 +0100829/*
830 * Forward decl that will remind us if its twin in cache.h changes.
831 * This function is used in compat/pread.c. But we can't include
832 * cache.h there.
833 */
Denton Liu55454422019-04-29 04:28:14 -0400834ssize_t read_in_full(int fd, void *buf, size_t count);
Stefan-W. Hahn69006792007-01-09 22:04:12 +0100835
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800836#ifdef NO_SETENV
837#define setenv gitsetenv
Denton Liu55454422019-04-29 04:28:14 -0400838int gitsetenv(const char *, const char *, int);
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800839#endif
840
Shawn O. Pearceca5bb5d2007-10-20 16:03:49 -0400841#ifdef NO_MKDTEMP
842#define mkdtemp gitmkdtemp
Denton Liu55454422019-04-29 04:28:14 -0400843char *gitmkdtemp(char *);
Shawn O. Pearceca5bb5d2007-10-20 16:03:49 -0400844#endif
845
Jason Riedy731043f2006-01-25 12:38:36 -0800846#ifdef NO_UNSETENV
847#define unsetenv gitunsetenv
Junio C Hamanoa38989b2021-10-29 14:42:12 -0700848int gitunsetenv(const char *);
Jason Riedy731043f2006-01-25 12:38:36 -0800849#endif
850
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800851#ifdef NO_STRCASESTR
852#define strcasestr gitstrcasestr
Denton Liu55454422019-04-29 04:28:14 -0400853char *gitstrcasestr(const char *haystack, const char *needle);
Junio C Hamano4050c0d2005-12-05 11:54:29 -0800854#endif
855
Peter Eriksen817151e2006-06-24 16:01:25 +0200856#ifdef NO_STRLCPY
857#define strlcpy gitstrlcpy
Denton Liu55454422019-04-29 04:28:14 -0400858size_t gitstrlcpy(char *, const char *, size_t);
Peter Eriksen817151e2006-06-24 16:01:25 +0200859#endif
860
Jason Riedybc6b4f52007-02-19 16:22:56 -0800861#ifdef NO_STRTOUMAX
862#define strtoumax gitstrtoumax
Denton Liu55454422019-04-29 04:28:14 -0400863uintmax_t gitstrtoumax(const char *, char **, int);
Johannes Sixt97000ba2011-11-05 16:37:34 +0100864#define strtoimax gitstrtoimax
Denton Liu55454422019-04-29 04:28:14 -0400865intmax_t gitstrtoimax(const char *, char **, int);
Jason Riedybc6b4f52007-02-19 16:22:56 -0800866#endif
867
Alex Riesenfa0c87c2007-06-13 20:54:32 +0200868#ifdef NO_HSTRERROR
869#define hstrerror githstrerror
Denton Liu55454422019-04-29 04:28:14 -0400870const char *githstrerror(int herror);
Alex Riesenfa0c87c2007-06-13 20:54:32 +0200871#endif
872
René Scharfeb21b9f12007-09-07 00:32:54 +0200873#ifdef NO_MEMMEM
874#define memmem gitmemmem
875void *gitmemmem(const void *haystack, size_t haystacklen,
Nguyễn Thái Ngọc Duyec36c422018-12-06 16:42:06 +0100876 const void *needle, size_t needlelen);
René Scharfeb21b9f12007-09-07 00:32:54 +0200877#endif
878
René Scharfeca2baa32016-09-03 17:59:15 +0200879#ifdef OVERRIDE_STRDUP
880#ifdef strdup
881#undef strdup
882#endif
883#define strdup gitstrdup
884char *gitstrdup(const char *s);
885#endif
886
Matt Kraai40036be2012-12-18 14:03:55 -0800887#ifdef NO_GETPAGESIZE
888#define getpagesize() sysconf(_SC_PAGESIZE)
889#endif
890
Ben Wijen05d1ed62016-08-22 14:47:55 +0200891#ifndef O_CLOEXEC
892#define O_CLOEXEC 0
893#endif
894
Brandon Caseycba22522008-02-08 20:32:47 -0600895#ifdef FREAD_READS_DIRECTORIES
Ramsay Jonesb0a642a2017-05-08 21:45:56 +0100896# if !defined(SUPPRESS_FOPEN_REDEFINITION)
897# ifdef fopen
898# undef fopen
899# endif
900# define fopen(a,b) git_fopen(a,b)
901# endif
Denton Liu55454422019-04-29 04:28:14 -0400902FILE *git_fopen(const char*, const char*);
Brandon Caseycba22522008-02-08 20:32:47 -0600903#endif
904
Michal Rokosc4582f92008-03-05 16:46:13 +0100905#ifdef SNPRINTF_RETURNS_BOGUS
Benoit Sigoureab038032014-01-30 22:25:12 -0800906#ifdef snprintf
907#undef snprintf
908#endif
Michal Rokosc4582f92008-03-05 16:46:13 +0100909#define snprintf git_snprintf
Denton Liub199d712019-04-29 04:28:20 -0400910int git_snprintf(char *str, size_t maxsize,
Denton Liuad6dad02019-04-29 04:28:23 -0400911 const char *format, ...);
Benoit Sigoureab038032014-01-30 22:25:12 -0800912#ifdef vsnprintf
913#undef vsnprintf
914#endif
Michal Rokosc4582f92008-03-05 16:46:13 +0100915#define vsnprintf git_vsnprintf
Denton Liu55454422019-04-29 04:28:14 -0400916int git_vsnprintf(char *str, size_t maxsize,
Denton Liuad6dad02019-04-29 04:28:23 -0400917 const char *format, va_list ap);
Michal Rokosc4582f92008-03-05 16:46:13 +0100918#endif
919
Jeff King2b081012021-02-26 01:14:35 -0500920#ifdef OPEN_RETURNS_EINTR
921#undef open
922#define open git_open_with_retry
923int git_open_with_retry(const char *path, int flag, ...);
924#endif
925
Johannes Sixt726c8ef2007-11-12 11:09:05 +0100926#ifdef __GLIBC_PREREQ
927#if __GLIBC_PREREQ(2, 1)
928#define HAVE_STRCHRNUL
929#endif
930#endif
931
932#ifndef HAVE_STRCHRNUL
René Scharfe659c69c2007-11-09 01:49:36 +0100933#define strchrnul gitstrchrnul
Andreas Ericsson9e79f002007-11-10 12:55:48 +0100934static inline char *gitstrchrnul(const char *s, int c)
935{
936 while (*s && *s != c)
937 s++;
938 return (char *)s;
939}
René Scharfe659c69c2007-11-09 01:49:36 +0100940#endif
941
Mike Papeda523cc2010-11-04 02:35:11 +0100942#ifdef NO_INET_PTON
943int inet_pton(int af, const char *src, void *dst);
944#endif
945
946#ifdef NO_INET_NTOP
947const char *inet_ntop(int af, const void *src, char *dst, size_t size);
948#endif
949
Etienne Buira0f4b6db2014-10-18 14:31:15 +0200950#ifdef NO_PTHREADS
951#define atexit git_atexit
Denton Liu55454422019-04-29 04:28:14 -0400952int git_atexit(void (*handler)(void));
Etienne Buira0f4b6db2014-10-18 14:31:15 +0200953#endif
954
Jeff King320d0b42016-02-19 06:21:19 -0500955static inline size_t st_add(size_t a, size_t b)
956{
957 if (unsigned_add_overflows(a, b))
958 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
959 (uintmax_t)a, (uintmax_t)b);
960 return a + b;
961}
Eric Sunshined616fbf2016-03-21 00:35:57 -0400962#define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
963#define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
Jeff King320d0b42016-02-19 06:21:19 -0500964
965static inline size_t st_mult(size_t a, size_t b)
966{
967 if (unsigned_mult_overflows(a, b))
968 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
969 (uintmax_t)a, (uintmax_t)b);
970 return a * b;
971}
972
973static inline size_t st_sub(size_t a, size_t b)
974{
975 if (a < b)
976 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
977 (uintmax_t)a, (uintmax_t)b);
978 return a - b;
979}
980
Johannes Schindeline2ffeae2021-11-02 15:46:09 +0000981static inline size_t st_left_shift(size_t a, unsigned shift)
982{
983 if (unsigned_left_shift_overflows(a, shift))
984 die("size_t overflow: %"PRIuMAX" << %u",
985 (uintmax_t)a, shift);
986 return a << shift;
987}
988
989static inline unsigned long cast_size_t_to_ulong(size_t a)
990{
991 if (a != (unsigned long)a)
992 die("object too large to read on this platform: %"
993 PRIuMAX" is cut off to %lu",
994 (uintmax_t)a, (unsigned long)a);
995 return (unsigned long)a;
996}
997
Jeff Kingec4f39b2022-08-17 02:06:58 -0400998/*
999 * Limit size of IO chunks, because huge chunks only cause pain. OS X
1000 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
1001 * the absence of bugs, large chunks can result in bad latencies when
1002 * you decide to kill the process.
1003 *
1004 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
1005 * that is smaller than that, clip it to SSIZE_MAX, as a call to
1006 * read(2) or write(2) larger than that is allowed to fail. As the last
1007 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
1008 * to override this, if the definition of SSIZE_MAX given by the platform
1009 * is broken.
1010 */
1011#ifndef MAX_IO_SIZE
1012# define MAX_IO_SIZE_DEFAULT (8*1024*1024)
1013# if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
1014# define MAX_IO_SIZE SSIZE_MAX
1015# else
1016# define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
1017# endif
1018#endif
1019
Kirill Smelkov61f76a32014-03-27 18:22:50 +04001020#ifdef HAVE_ALLOCA_H
1021# include <alloca.h>
1022# define xalloca(size) (alloca(size))
1023# define xalloca_free(p) do {} while (0)
1024#else
1025# define xalloca(size) (xmalloc(size))
1026# define xalloca_free(p) (free(p))
1027#endif
Denton Liu55454422019-04-29 04:28:14 -04001028char *xstrdup(const char *str);
1029void *xmalloc(size_t size);
1030void *xmallocz(size_t size);
1031void *xmallocz_gently(size_t size);
1032void *xmemdupz(const void *data, size_t len);
1033char *xstrndup(const char *str, size_t len);
1034void *xrealloc(void *ptr, size_t size);
1035void *xcalloc(size_t nmemb, size_t size);
Ævar Arnfjörð Bjarmason3540c712021-09-21 15:12:59 +02001036void xsetenv(const char *name, const char *value, int overwrite);
Denton Liu55454422019-04-29 04:28:14 -04001037void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
Eric Wongdc059292021-06-30 00:01:32 +00001038const char *mmap_os_err(void);
Denton Liu55454422019-04-29 04:28:14 -04001039void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
Denton Liub199d712019-04-29 04:28:20 -04001040int xopen(const char *path, int flags, ...);
Denton Liu55454422019-04-29 04:28:14 -04001041ssize_t xread(int fd, void *buf, size_t len);
1042ssize_t xwrite(int fd, const void *buf, size_t len);
1043ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
1044int xdup(int fd);
1045FILE *xfopen(const char *path, const char *mode);
1046FILE *xfdopen(int fd, const char *mode);
1047int xmkstemp(char *temp_filename);
1048int xmkstemp_mode(char *temp_filename, int mode);
1049char *xgetcwd(void);
1050FILE *fopen_for_writing(const char *path);
1051FILE *fopen_or_warn(const char *path, const char *mode);
Luiz Fernando N. Capitulinof21a47b2007-08-14 16:44:53 -03001052
Ævar Arnfjörð Bjarmason481df652017-06-15 21:06:59 +00001053/*
brian m. carlson14570dc2020-05-25 19:58:50 +00001054 * Like strncmp, but only return zero if s is NUL-terminated and exactly len
1055 * characters long. If it is not, consider it greater than t.
1056 */
1057int xstrncmpz(const char *s, const char *t, size_t len);
1058
1059/*
Ævar Arnfjörð Bjarmason481df652017-06-15 21:06:59 +00001060 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
1061 * that ptr is used twice, so don't pass e.g. ptr++.
1062 */
1063#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
1064
Jeff Kinge7792a72016-02-22 17:43:18 -05001065#define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
René Scharfef1121492021-03-13 17:10:47 +01001066#define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
Jeff Kinge7792a72016-02-22 17:43:18 -05001067#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
René Scharfe3ac22f82014-09-16 20:56:48 +02001068
René Scharfe60566cb2016-09-25 09:15:42 +02001069#define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
1070 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
1071static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
1072{
1073 if (n)
1074 memcpy(dst, src, st_mult(size, n));
1075}
1076
René Scharfe57839802017-07-15 21:36:20 +02001077#define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
1078 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
1079static inline void move_array(void *dst, const void *src, size_t n, size_t size)
1080{
1081 if (n)
1082 memmove(dst, src, st_mult(size, n));
1083}
1084
Jeff King36895392016-02-22 17:43:25 -05001085/*
1086 * These functions help you allocate structs with flex arrays, and copy
1087 * the data directly into the array. For example, if you had:
1088 *
1089 * struct foo {
1090 * int bar;
1091 * char name[FLEX_ARRAY];
1092 * };
1093 *
1094 * you can do:
1095 *
1096 * struct foo *f;
1097 * FLEX_ALLOC_MEM(f, name, src, len);
1098 *
1099 * to allocate a "foo" with the contents of "src" in the "name" field.
1100 * The resulting struct is automatically zero'd, and the flex-array field
1101 * is NUL-terminated (whether the incoming src buffer was or not).
1102 *
1103 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
1104 * but do want to store a pointer to some extra data in the same allocated
1105 * block. For example, if you have:
1106 *
1107 * struct foo {
1108 * char *name;
1109 * int bar;
1110 * };
1111 *
1112 * you can do:
1113 *
1114 * struct foo *f;
René Scharfe0bb15192016-08-13 11:01:21 +02001115 * FLEXPTR_ALLOC_STR(f, name, src);
Jeff King36895392016-02-22 17:43:25 -05001116 *
1117 * and "name" will point to a block of memory after the struct, which will be
1118 * freed along with the struct (but the pointer can be repointed anywhere).
1119 *
1120 * The *_STR variants accept a string parameter rather than a ptr/len
1121 * combination.
1122 *
1123 * Note that these macros will evaluate the first parameter multiple
1124 * times, and it must be assignable as an lvalue.
1125 */
1126#define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
René Scharfee9451782016-10-15 18:23:11 +02001127 size_t flex_array_len_ = (len); \
1128 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1129 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
Jeff King36895392016-02-22 17:43:25 -05001130} while (0)
1131#define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
René Scharfe0ac52a32016-10-16 12:06:02 +02001132 size_t flex_array_len_ = (len); \
1133 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1134 memcpy((x) + 1, (buf), flex_array_len_); \
Jeff King36895392016-02-22 17:43:25 -05001135 (x)->ptrname = (void *)((x)+1); \
1136} while(0)
1137#define FLEX_ALLOC_STR(x, flexname, str) \
1138 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
1139#define FLEXPTR_ALLOC_STR(x, ptrname, str) \
1140 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
1141
Jeff Kingd64ea0f2015-01-12 20:57:37 -05001142static inline char *xstrdup_or_null(const char *str)
1143{
1144 return str ? xstrdup(str) : NULL;
1145}
1146
Shawn O. Pearcedc49cd72007-03-06 20:44:37 -05001147static inline size_t xsize_t(off_t len)
1148{
Jonathan Niederaafa5df2021-05-18 18:52:56 -07001149 if (len < 0 || (uintmax_t) len > SIZE_MAX)
Thomas Rast46be82d2010-07-28 18:36:31 +02001150 die("Cannot handle files this big");
Jonathan Niederaafa5df2021-05-18 18:52:56 -07001151 return (size_t) len;
Shawn O. Pearcedc49cd72007-03-06 20:44:37 -05001152}
1153
Jeff King7b03c892015-09-24 17:05:37 -04001154__attribute__((format (printf, 3, 4)))
Denton Liub199d712019-04-29 04:28:20 -04001155int xsnprintf(char *dst, size_t max, const char *fmt, ...);
Jeff King7b03c892015-09-24 17:05:37 -04001156
René Scharfeda25bdb2017-04-18 17:57:42 -04001157#ifndef HOST_NAME_MAX
1158#define HOST_NAME_MAX 256
1159#endif
1160
Denton Liu55454422019-04-29 04:28:14 -04001161int xgethostname(char *buf, size_t len);
David Turner5781a9a2017-04-18 17:57:43 -04001162
Ramsay Jonesf1589d12012-03-04 19:10:57 +00001163/* in ctype.c, for kwset users */
Ben Walton189c8602015-03-02 19:22:31 +00001164extern const unsigned char tolower_trans_tbl[256];
Ramsay Jonesf1589d12012-03-04 19:10:57 +00001165
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001166/* Sane ctype - no locale, and works with signed chars */
René Scharfec2e93642009-03-07 14:06:49 +01001167#undef isascii
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001168#undef isspace
1169#undef isdigit
1170#undef isalpha
1171#undef isalnum
Jan H. Schönherr0fcec2c2012-10-18 16:43:32 +02001172#undef isprint
Namhyung Kim43ccdf52012-02-10 11:13:31 +09001173#undef islower
1174#undef isupper
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001175#undef tolower
1176#undef toupper
Nguyễn Thái Ngọc Duy1c149ab2012-10-15 13:25:51 +07001177#undef iscntrl
1178#undef ispunct
1179#undef isxdigit
Junio C Hamano2adf7242013-01-10 13:47:15 -08001180
Nguyễn Thái Ngọc Duyca5ab7d2012-10-15 13:25:50 +07001181extern const unsigned char sane_ctype[256];
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001182#define GIT_SPACE 0x01
1183#define GIT_DIGIT 0x02
1184#define GIT_ALPHA 0x04
René Scharfe8cc32992009-01-17 16:50:34 +01001185#define GIT_GLOB_SPECIAL 0x08
René Scharfef9b7cce2009-01-17 16:50:37 +01001186#define GIT_REGEX_SPECIAL 0x10
Junio C Hamano2f6c9762011-04-08 16:18:46 -07001187#define GIT_PATHSPEC_MAGIC 0x20
Nguyễn Thái Ngọc Duy1c149ab2012-10-15 13:25:51 +07001188#define GIT_CNTRL 0x40
1189#define GIT_PUNCT 0x80
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001190#define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
René Scharfec2e93642009-03-07 14:06:49 +01001191#define isascii(x) (((x) & ~0x7f) == 0)
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001192#define isspace(x) sane_istest(x,GIT_SPACE)
1193#define isdigit(x) sane_istest(x,GIT_DIGIT)
1194#define isalpha(x) sane_istest(x,GIT_ALPHA)
1195#define isalnum(x) sane_istest(x,GIT_ALPHA | GIT_DIGIT)
Jan H. Schönherr0fcec2c2012-10-18 16:43:32 +02001196#define isprint(x) ((x) >= 0x20 && (x) <= 0x7e)
Namhyung Kim43ccdf52012-02-10 11:13:31 +09001197#define islower(x) sane_iscase(x, 1)
1198#define isupper(x) sane_iscase(x, 0)
René Scharfe8cc32992009-01-17 16:50:34 +01001199#define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
René Scharfef9b7cce2009-01-17 16:50:37 +01001200#define is_regex_special(x) sane_istest(x,GIT_GLOB_SPECIAL | GIT_REGEX_SPECIAL)
Nguyễn Thái Ngọc Duy1c149ab2012-10-15 13:25:51 +07001201#define iscntrl(x) (sane_istest(x,GIT_CNTRL))
1202#define ispunct(x) sane_istest(x, GIT_PUNCT | GIT_REGEX_SPECIAL | \
1203 GIT_GLOB_SPECIAL | GIT_PATHSPEC_MAGIC)
Jeff King50a71772014-10-15 18:34:05 -04001204#define isxdigit(x) (hexval_table[(unsigned char)(x)] != -1)
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001205#define tolower(x) sane_case((unsigned char)(x), 0x20)
1206#define toupper(x) sane_case((unsigned char)(x), 0)
Junio C Hamano2f6c9762011-04-08 16:18:46 -07001207#define is_pathspec_magic(x) sane_istest(x,GIT_PATHSPEC_MAGIC)
Junio C Hamano4050c0d2005-12-05 11:54:29 -08001208
1209static inline int sane_case(int x, int high)
1210{
1211 if (sane_istest(x, GIT_ALPHA))
1212 x = (x & ~0x20) | high;
1213 return x;
1214}
1215
Namhyung Kim43ccdf52012-02-10 11:13:31 +09001216static inline int sane_iscase(int x, int is_lower)
1217{
1218 if (!sane_istest(x, GIT_ALPHA))
1219 return 0;
1220
1221 if (is_lower)
1222 return (x & 0x20) != 0;
1223 else
1224 return (x & 0x20) == 0;
1225}
1226
Jeff King41a80922018-05-13 12:57:14 -04001227/*
1228 * Like skip_prefix, but compare case-insensitively. Note that the comparison
1229 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
1230 * locale-specific conversions).
1231 */
1232static inline int skip_iprefix(const char *str, const char *prefix,
1233 const char **out)
1234{
1235 do {
1236 if (!*prefix) {
1237 *out = str;
1238 return 1;
1239 }
1240 } while (tolower(*str++) == tolower(*prefix++));
1241 return 0;
1242}
1243
Jim Meyering6aead432007-04-10 01:01:44 +02001244static inline int strtoul_ui(char const *s, int base, unsigned int *result)
1245{
1246 unsigned long ul;
1247 char *p;
1248
1249 errno = 0;
Matthieu Moye6f25992015-09-17 18:28:33 +02001250 /* negative values would be accepted by strtoul */
1251 if (strchr(s, '-'))
1252 return -1;
Jim Meyering6aead432007-04-10 01:01:44 +02001253 ul = strtoul(s, &p, base);
1254 if (errno || *p || p == s || (unsigned int) ul != ul)
1255 return -1;
1256 *result = ul;
1257 return 0;
1258}
1259
Junio C Hamano7791ecb2007-10-23 13:33:26 -07001260static inline int strtol_i(char const *s, int base, int *result)
1261{
1262 long ul;
1263 char *p;
1264
1265 errno = 0;
1266 ul = strtol(s, &p, base);
1267 if (errno || *p || p == s || (int) ul != ul)
1268 return -1;
1269 *result = ul;
1270 return 0;
1271}
1272
Johannes Schindelin97fff612019-09-30 10:21:54 -07001273void git_stable_qsort(void *base, size_t nmemb, size_t size,
1274 int(*compar)(const void *, const void *));
Brian Downing43fe9012008-02-05 15:10:44 -06001275#ifdef INTERNAL_QSORT
Johannes Schindelin97fff612019-09-30 10:21:54 -07001276#define qsort git_stable_qsort
Brian Downing43fe9012008-02-05 15:10:44 -06001277#endif
1278
René Scharfedbc540c2016-09-29 17:23:43 +02001279#define QSORT(base, n, compar) sane_qsort((base), (n), sizeof(*(base)), compar)
1280static inline void sane_qsort(void *base, size_t nmemb, size_t size,
1281 int(*compar)(const void *, const void *))
1282{
1283 if (nmemb > 1)
1284 qsort(base, nmemb, size, compar);
1285}
1286
Johannes Schindelin97fff612019-09-30 10:21:54 -07001287#define STABLE_QSORT(base, n, compar) \
1288 git_stable_qsort((base), (n), sizeof(*(base)), compar)
1289
René Scharfe04ee8b82017-01-22 18:51:11 +01001290#ifndef HAVE_ISO_QSORT_S
1291int git_qsort_s(void *base, size_t nmemb, size_t size,
1292 int (*compar)(const void *, const void *, void *), void *ctx);
1293#define qsort_s git_qsort_s
1294#endif
1295
René Scharfe3ca86992017-01-22 18:52:13 +01001296#define QSORT_S(base, n, compar, ctx) do { \
1297 if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
Johannes Schindelinc3c34862018-05-02 11:38:41 +02001298 BUG("qsort_s() failed"); \
René Scharfe3ca86992017-01-22 18:52:13 +01001299} while (0)
1300
Johannes Schindelin2f895222016-09-21 20:24:04 +02001301#ifndef REG_STARTEND
1302#error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
1303#endif
1304
1305static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
1306 size_t nmatch, regmatch_t pmatch[], int eflags)
1307{
1308 assert(nmatch > 0 && pmatch);
1309 pmatch[0].rm_so = 0;
1310 pmatch[0].rm_eo = size;
1311 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
1312}
1313
Alex Riesen81a24b52008-03-05 00:15:39 +01001314#ifndef DIR_HAS_BSD_GROUP_SEMANTICS
1315# define FORCE_DIR_SET_GID S_ISGID
1316#else
1317# define FORCE_DIR_SET_GID 0
1318#endif
1319
Kjetil Barvikc06ff492009-03-04 18:47:40 +01001320#ifdef NO_NSEC
1321#undef USE_NSEC
1322#define ST_CTIME_NSEC(st) 0
1323#define ST_MTIME_NSEC(st) 0
1324#else
Brian Gernhardtc5673832009-03-08 16:04:28 -04001325#ifdef USE_ST_TIMESPEC
1326#define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
1327#define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
1328#else
Kjetil Barvikc06ff492009-03-04 18:47:40 +01001329#define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
1330#define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
1331#endif
Brian Gernhardtc5673832009-03-08 16:04:28 -04001332#endif
Kjetil Barvikc06ff492009-03-04 18:47:40 +01001333
Johannes Sixt34779c52009-04-20 10:17:00 +02001334#ifdef UNRELIABLE_FSTAT
1335#define fstat_is_reliable() 0
1336#else
1337#define fstat_is_reliable() 1
1338#endif
1339
Jeff Kingab8632a2011-02-25 23:08:25 -06001340#ifndef va_copy
Jonathan Nieder26db0f22011-03-08 02:33:44 -06001341/*
1342 * Since an obvious implementation of va_list would be to make it a
1343 * pointer into the stack frame, a simple assignment will work on
1344 * many systems. But let's try to be more portable.
1345 */
1346#ifdef __va_copy
1347#define va_copy(dst, src) __va_copy(dst, src)
1348#else
1349#define va_copy(dst, src) ((dst) = (src))
1350#endif
Jeff Kingab8632a2011-02-25 23:08:25 -06001351#endif
1352
Ramsay Jones746ea4a2018-05-09 18:04:06 +01001353/* usage.c: only to be used for testing BUG() implementation (see test-tool) */
1354extern int BUG_exit_code;
1355
Ævar Arnfjörð Bjarmason0cc05b02022-06-02 14:25:33 +02001356/* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
1357extern int bug_called_must_BUG;
1358
Jeff Kingd8193742017-05-12 23:28:50 -04001359__attribute__((format (printf, 3, 4))) NORETURN
1360void BUG_fl(const char *file, int line, const char *fmt, ...);
1361#define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
Ævar Arnfjörð Bjarmason0cc05b02022-06-02 14:25:33 +02001362__attribute__((format (printf, 3, 4)))
1363void bug_fl(const char *file, int line, const char *fmt, ...);
1364#define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1365#define BUG_if_bug(...) do { \
1366 if (bug_called_must_BUG) \
1367 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1368} while (0)
Jeff Kingd8193742017-05-12 23:28:50 -04001369
Neeraj Singh8a94d832022-04-04 22:20:14 -07001370#ifndef FSYNC_METHOD_DEFAULT
Neeraj Singhabf38ab2022-03-10 22:43:20 +00001371#ifdef __APPLE__
1372#define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1373#else
1374#define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1375#endif
Neeraj Singh8a94d832022-04-04 22:20:14 -07001376#endif
Neeraj Singhabf38ab2022-03-10 22:43:20 +00001377
1378enum fsync_action {
1379 FSYNC_WRITEOUT_ONLY,
1380 FSYNC_HARDWARE_FLUSH
1381};
1382
1383/*
1384 * Issues an fsync against the specified file according to the specified mode.
1385 *
1386 * FSYNC_WRITEOUT_ONLY attempts to use interfaces available on some operating
1387 * systems to flush the OS cache without issuing a flush command to the storage
1388 * controller. If those interfaces are unavailable, the function fails with
1389 * ENOSYS.
1390 *
1391 * FSYNC_HARDWARE_FLUSH does an OS writeout and hardware flush to ensure that
1392 * changes are durable. It is not expected to fail.
1393 */
1394int git_fsync(int fd, enum fsync_action action);
1395
Alex Riesenfc71db32009-04-29 23:21:46 +02001396/*
Neeraj Singh9a498762022-03-30 05:06:40 +00001397 * Writes out trace statistics for fsync using the trace2 API.
1398 */
1399void trace_git_fsync_stats(void);
1400
1401/*
Alex Riesenfc71db32009-04-29 23:21:46 +02001402 * Preserves errno, prints a message, but gives no warning for ENOENT.
Ronnie Sahlberg1054af72014-07-16 11:01:18 -07001403 * Returns 0 on success, which includes trying to unlink an object that does
1404 * not exist.
Alex Riesenfc71db32009-04-29 23:21:46 +02001405 */
1406int unlink_or_warn(const char *path);
Ronnie Sahlberg9ccc0c02014-07-16 11:20:36 -07001407 /*
1408 * Tries to unlink file. Returns 0 if unlink succeeded
1409 * or the file already didn't exist. Returns -1 and
1410 * appends a message to err suitable for
1411 * 'error("%s", err->buf)' on error.
1412 */
1413int unlink_or_msg(const char *file, struct strbuf *err);
Peter Collingbourned1723292010-03-26 15:25:33 +00001414/*
Ronnie Sahlberg1054af72014-07-16 11:01:18 -07001415 * Preserves errno, prints a message, but gives no warning for ENOENT.
1416 * Returns 0 on success, which includes trying to remove a directory that does
1417 * not exist.
Peter Collingbourned1723292010-03-26 15:25:33 +00001418 */
1419int rmdir_or_warn(const char *path);
Peter Collingbourne80d706a2010-03-26 15:25:34 +00001420/*
1421 * Calls the correct function out of {unlink,rmdir}_or_warn based on
1422 * the supplied file mode.
1423 */
1424int remove_or_warn(unsigned int mode, const char *path);
Alex Riesenfc71db32009-04-29 23:21:46 +02001425
Jonathan Niedere5c52c92012-10-13 17:03:07 -07001426/*
1427 * Call access(2), but warn for any error except "missing file"
1428 * (ENOENT or ENOTDIR).
1429 */
Jonathan Nieder4698c8f2013-04-12 14:03:18 -07001430#define ACCESS_EACCES_OK (1U << 0)
1431int access_or_warn(const char *path, int mode, unsigned flag);
1432int access_or_die(const char *path, int mode, unsigned flag);
Jeff Kingba8bd832012-08-21 02:10:59 -04001433
Nguyễn Thái Ngọc Duy11dc1fc2017-05-03 17:16:49 +07001434/* Warn on an inaccessible file if errno indicates this is an error */
1435int warn_on_fopen_errors(const char *path);
Junio C Hamano55b38a42012-08-21 14:52:07 -07001436
Jeff King00611d82021-02-16 09:44:22 -05001437/*
1438 * Open with O_NOFOLLOW, or equivalent. Note that the fallback equivalent
1439 * may be racy. Do not use this as protection against an attacker who can
1440 * simultaneously create paths.
1441 */
1442int open_nofollow(const char *path, int flags);
1443
Kyle J. McKay1b56cdf2015-03-07 21:07:59 -08001444#ifndef SHELL_PATH
1445# define SHELL_PATH "/bin/sh"
1446#endif
1447
Jeff Kingf43cce22015-04-16 04:48:45 -04001448#ifndef _POSIX_THREAD_SAFE_FUNCTIONS
Junio C Hamano15b52a42020-08-06 17:25:37 -07001449static inline void flockfile(FILE *fh)
1450{
1451 ; /* nothing */
1452}
1453static inline void funlockfile(FILE *fh)
1454{
1455 ; /* nothing */
1456}
Jeff Kingf43cce22015-04-16 04:48:45 -04001457#define getc_unlocked(fh) getc(fh)
1458#endif
1459
Duy Nguyen18a4f6b2019-02-12 21:14:41 +07001460#ifdef FILENO_IS_A_MACRO
1461int git_fileno(FILE *stream);
Clément Chigot400caaf2019-04-25 07:01:56 +00001462# ifndef COMPAT_CODE_FILENO
Duy Nguyen18a4f6b2019-02-12 21:14:41 +07001463# undef fileno
1464# define fileno(p) git_fileno(p)
1465# endif
1466#endif
1467
Clément Chigot400caaf2019-04-25 07:01:56 +00001468#ifdef NEED_ACCESS_ROOT_HANDLER
1469int git_access(const char *path, int mode);
1470# ifndef COMPAT_CODE_ACCESS
1471# ifdef access
1472# undef access
1473# endif
1474# define access(path, mode) git_access(path, mode)
1475# endif
1476#endif
1477
Junio C Hamanodc5a18b2017-05-26 12:09:01 +09001478/*
1479 * Our code often opens a path to an optional file, to work on its
1480 * contents when we can successfully open it. We can ignore a failure
1481 * to open if such an optional file does not exist, but we do want to
1482 * report a failure in opening for other reasons (e.g. we got an I/O
1483 * error, or the file is there, but we lack the permission to open).
1484 *
1485 * Call this function after seeing an error from open() or fopen() to
1486 * see if the errno indicates a missing file that we can safely ignore.
1487 */
1488static inline int is_missing_file_error(int errno_)
1489{
1490 return (errno_ == ENOENT || errno_ == ENOTDIR);
1491}
1492
Denton Liu55454422019-04-29 04:28:14 -04001493int cmd_main(int, const char **);
Jeff King5c238e22016-10-27 13:30:30 -04001494
Jeff King0e5bba52017-09-08 02:38:41 -04001495/*
Jeff Hostetleree4512e2019-02-22 14:25:01 -08001496 * Intercept all calls to exit() and route them to trace2 to
1497 * optionally emit a message before calling the real exit().
1498 */
Ævar Arnfjörð Bjarmason19d75942022-06-02 14:25:32 +02001499int common_exit(const char *file, int line, int code);
1500#define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
Jeff Hostetleree4512e2019-02-22 14:25:01 -08001501
1502/*
Jeff King0e5bba52017-09-08 02:38:41 -04001503 * You can mark a stack variable with UNLEAK(var) to avoid it being
1504 * reported as a leak by tools like LSAN or valgrind. The argument
1505 * should generally be the variable itself (not its address and not what
1506 * it points to). It's safe to use this on pointers which may already
1507 * have been freed, or on pointers which may still be in use.
1508 *
1509 * Use this _only_ for a variable that leaks by going out of scope at
1510 * program exit (so only from cmd_* functions or their direct helpers).
1511 * Normal functions, especially those which may be called multiple
1512 * times, should actually free their memory. This is only meant as
1513 * an annotation, and does nothing in non-leak-checking builds.
1514 */
1515#ifdef SUPPRESS_ANNOTATED_LEAKS
Denton Liu55454422019-04-29 04:28:14 -04001516void unleak_memory(const void *ptr, size_t len);
Jonathan Tan5de3de32017-09-19 15:10:04 -07001517#define UNLEAK(var) unleak_memory(&(var), sizeof(var))
Jeff King0e5bba52017-09-08 02:38:41 -04001518#else
Jonathan Tan5de3de32017-09-19 15:10:04 -07001519#define UNLEAK(var) do {} while (0)
Jeff King0e5bba52017-09-08 02:38:41 -04001520#endif
1521
Ævar Arnfjörð Bjarmason07564772022-01-24 10:27:59 -08001522#define z_const
1523#include <zlib.h>
1524
1525#if ZLIB_VERNUM < 0x1290
1526/*
1527 * This is uncompress2, which is only available in zlib >= 1.2.9
1528 * (released as of early 2017). See compat/zlib-uncompress2.c.
1529 */
1530int uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
1531 uLong *sourceLen);
1532#endif
1533
Jeff Kingc8af66a2018-07-26 03:21:05 -04001534/*
1535 * This include must come after system headers, since it introduces macros that
1536 * replace system names.
1537 */
1538#include "banned.h"
1539
Eric Wong973d5ee2019-10-06 23:30:33 +00001540/*
1541 * container_of - Get the address of an object containing a field.
1542 *
1543 * @ptr: pointer to the field.
1544 * @type: type of the object.
1545 * @member: name of the field within the object.
1546 */
1547#define container_of(ptr, type, member) \
1548 ((type *) ((char *)(ptr) - offsetof(type, member)))
1549
Eric Wongf0e63c42019-10-06 23:30:35 +00001550/*
1551 * helper function for `container_of_or_null' to avoid multiple
1552 * evaluation of @ptr
1553 */
1554static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1555{
1556 return ptr ? (char *)ptr - offset : NULL;
1557}
1558
1559/*
1560 * like `container_of', but allows returned value to be NULL
1561 */
1562#define container_of_or_null(ptr, type, member) \
1563 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1564
Eric Wong23dee692019-10-06 23:30:41 +00001565/*
Andrei Rybakabcb66c2021-06-11 13:18:50 +02001566 * like offsetof(), but takes a pointer to a variable of type which
Eric Wong23dee692019-10-06 23:30:41 +00001567 * contains @member, instead of a specified type.
1568 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1569 * everywhere.
1570 */
1571#if defined(__GNUC__) /* clang sets this, too */
1572#define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1573#else /* !__GNUC__ */
1574#define OFFSETOF_VAR(ptr, member) \
1575 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1576#endif /* !__GNUC__ */
1577
Han-Wen Nienhuysa76b1382020-11-24 19:10:11 +00001578void sleep_millisec(int millisec);
1579
brian m. carlson05cd9882022-01-17 21:56:16 +00001580/*
1581 * Generate len bytes from the system cryptographically secure PRNG.
1582 * Returns 0 on success and -1 on error, setting errno. The inability to
1583 * satisfy the full request is an error.
1584 */
1585int csprng_bytes(void *buf, size_t len);
1586
Jeff King5c238e22016-10-27 13:30:30 -04001587#endif