]> git.ipfire.org Git - thirdparty/git.git/blame - git-compat-util.h
The sixth batch
[thirdparty/git.git] / git-compat-util.h
CommitLineData
4050c0df
JH
1#ifndef GIT_COMPAT_UTIL_H
2#define GIT_COMPAT_UTIL_H
3
7bc341e2 4#if __STDC_VERSION__ - 0 < 199901L
5/*
6 * Git is in a testing period for mandatory C99 support in the compiler. If
7 * your compiler is reasonably recent, you can try to enable C99 support (or,
8 * for MSVC, C11 support). If you encounter a problem and can't enable C99
9 * support with your compiler (such as with "-std=gnu99") and don't have access
10 * to one with this support, such as GCC or Clang, you can remove this #if
11 * directive, but please report the details of your system to
12 * git@vger.kernel.org.
13 */
14#error "Required C99 support is in a test phase. Please see git-compat-util.h for more details."
15#endif
16
556702f8
JH
17#ifdef USE_MSVC_CRTDBG
18/*
19 * For these to work they must appear very early in each
20 * file -- before most of the standard header files.
21 */
22#include <stdlib.h>
23#include <crtdbg.h>
24#endif
25
75a044f7 26#include "compat/posix.h"
b97e9116 27
75a044f7 28struct strbuf;
89c855ed 29
2121a76d
PS
30#if defined(__GNUC__) || defined(__clang__)
31# define PRAGMA(pragma) _Pragma(#pragma)
32# define DISABLE_WARNING(warning) PRAGMA(GCC diagnostic ignored #warning)
33#else
34# define DISABLE_WARNING(warning)
35#endif
36
37#ifdef DISABLE_SIGN_COMPARE_WARNINGS
38DISABLE_WARNING(-Wsign-compare)
39#endif
89c855ed 40
8f1d2e6f 41#ifndef FLEX_ARRAY
8e973991
JH
42/*
43 * See if our compiler is known to support flexible array members.
44 */
deefc2d9
JH
45
46/*
47 * Check vendor specific quirks first, before checking the
48 * __STDC_VERSION__, as vendor compilers can lie and we need to be
49 * able to work them around. Note that by not defining FLEX_ARRAY
50 * here, we can fall back to use the "safer but a bit wasteful" one
51 * later.
52 */
53#if defined(__SUNPRO_C) && (__SUNPRO_C <= 0x580)
8e973991
JH
54#elif defined(__GNUC__)
55# if (__GNUC__ >= 3)
56# define FLEX_ARRAY /* empty */
57# else
58# define FLEX_ARRAY 0 /* older GNU extension */
59# endif
deefc2d9
JH
60#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
61# define FLEX_ARRAY /* empty */
8e973991
JH
62#endif
63
64/*
65 * Otherwise, default to safer but a bit wasteful traditional style
66 */
67#ifndef FLEX_ARRAY
68# define FLEX_ARRAY 1
8f1d2e6f
JH
69#endif
70#endif
71
89c855ed
EP
72
73/*
74 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
75 * @cond: the compile-time condition which must be true.
76 *
77 * Your compile will fail if the condition isn't true, or can't be evaluated
78 * by the compiler. This can be used in an expression: its value is "0".
79 *
80 * Example:
81 * #define foo_to_char(foo) \
82 * ((char *)(foo) \
83 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
84 */
85#define BUILD_ASSERT_OR_ZERO(cond) \
86 (sizeof(char [1 - 2*!(cond)]) - 1)
87
e2c6f7cd 88#if GIT_GNUC_PREREQ(3, 1)
89c855ed
EP
89 /* &arr[0] degrades to a pointer: a different type from an array */
90# define BARF_UNLESS_AN_ARRAY(arr) \
91 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
92 __typeof__(&(arr)[0])))
08e8c266
RS
93# define BARF_UNLESS_COPYABLE(dst, src) \
94 BUILD_ASSERT_OR_ZERO(__builtin_types_compatible_p(__typeof__(*(dst)), \
95 __typeof__(*(src))))
791aeddf
PS
96
97# define BARF_UNLESS_SIGNED(var) BUILD_ASSERT_OR_ZERO(((__typeof__(var)) -1) < 0)
98# define BARF_UNLESS_UNSIGNED(var) BUILD_ASSERT_OR_ZERO(((__typeof__(var)) -1) > 0)
e2c6f7cd
CB
99#else
100# define BARF_UNLESS_AN_ARRAY(arr) 0
08e8c266
RS
101# define BARF_UNLESS_COPYABLE(dst, src) \
102 BUILD_ASSERT_OR_ZERO(0 ? ((*(dst) = *(src)), 0) : \
103 sizeof(*(dst)) == sizeof(*(src)))
791aeddf
PS
104
105# define BARF_UNLESS_SIGNED(var) 0
106# define BARF_UNLESS_UNSIGNED(var) 0
89c855ed 107#endif
791aeddf 108
89c855ed
EP
109/*
110 * ARRAY_SIZE - get the number of elements in a visible array
68b69211 111 * @x: the array whose size you want.
89c855ed
EP
112 *
113 * This does not work on pointers, or arrays declared as [], or
114 * function parameters. With correct compiler support, such usage
115 * will cause a build error (see the build_assert_or_zero macro).
116 */
117#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
118
f630cfda 119#define bitsizeof(x) (CHAR_BIT * sizeof(x))
b4f2a6ac 120
c03c8315
EFL
121#define maximum_signed_value_of_type(a) \
122 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
123
1368f650
JN
124#define maximum_unsigned_value_of_type(a) \
125 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
126
c03c8315
EFL
127/*
128 * Signed integer overflow is undefined in C, so here's a helper macro
129 * to detect if the sum of two integers will overflow.
130 *
131 * Requires: a >= 0, typeof(a) equals typeof(b)
132 */
133#define signed_add_overflows(a, b) \
134 ((b) > maximum_signed_value_of_type(a) - (a))
135
1368f650
JN
136#define unsigned_add_overflows(a, b) \
137 ((b) > maximum_unsigned_value_of_type(a) - (a))
138
320d0b49
JK
139/*
140 * Returns true if the multiplication of "a" and "b" will
141 * overflow. The types of "a" and "b" must match and must be unsigned.
142 * Note that this macro evaluates "a" twice!
143 */
144#define unsigned_mult_overflows(a, b) \
145 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
146
e2ffeae3
JS
147/*
148 * Returns true if the left shift of "a" by "shift" bits will
149 * overflow. The type of "a" must be unsigned.
150 */
151#define unsigned_left_shift_overflows(a, shift) \
152 ((shift) < bitsizeof(a) && \
153 (a) > maximum_unsigned_value_of_type(a) >> (shift))
154
8723f216
NP
155#ifdef __GNUC__
156#define TYPEOF(x) (__typeof__(x))
157#else
158#define TYPEOF(x)
159#endif
160
f630cfda 161#define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
db7244bd 162#define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
8723f216 163
98cb6f30
PH
164#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
165
cf606e3d
AW
166/* Approximation of the length of the decimal representation of this type. */
167#define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
168
2406bf5f
MA
169#if defined(NO_UNIX_SOCKETS) || !defined(GIT_WINDOWS_NATIVE)
170static inline int _have_unix_sockets(void)
171{
172#if defined(NO_UNIX_SOCKETS)
173 return 0;
174#else
175 return 1;
176#endif
177}
178#define have_unix_sockets _have_unix_sockets
179#endif
180
9fd512c8
ÆAB
181/* Used by compat/win32/path-utils.h, and more */
182static inline int is_xplatform_dir_sep(int c)
183{
184 return c == '/' || c == '\\';
185}
186
496f2569 187#if defined(__CYGWIN__)
1cadad6f 188#include "compat/win32/path-utils.h"
496f2569 189#endif
cfc755d3
VR
190#if defined(__MINGW32__)
191/* pull in Windows compatibility stuff */
1cadad6f 192#include "compat/win32/path-utils.h"
cfc755d3
VR
193#include "compat/mingw.h"
194#elif defined(_MSC_VER)
22c3634c 195#include "compat/win32/path-utils.h"
cfc755d3 196#include "compat/msvc.h"
41b20017 197#endif
85023577 198
76759c7d
TB
199/* used on Mac OS X */
200#ifdef PRECOMPOSE_UNICODE
201#include "compat/precompose_utf8.h"
202#else
808e9195
JK
203static inline const char *precompose_argv_prefix(int argc UNUSED,
204 const char **argv UNUSED,
205 const char *prefix)
15b52a44 206{
5c327502 207 return prefix;
15b52a44 208}
5020774a
TB
209static inline const char *precompose_string_if_needed(const char *in)
210{
211 return in;
212}
213
fdf72966 214#define probe_utf8_pathname_composition()
76759c7d
TB
215#endif
216
684ec6c6 217#ifndef NO_OPENSSL
88c03eb5 218#ifdef __APPLE__
44bdba2f 219#undef __AVAILABILITY_MACROS_USES_AVAILABILITY
b195aa00 220#define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
88c03eb5
KM
221#include <AvailabilityMacros.h>
222#undef DEPRECATED_ATTRIBUTE
223#define DEPRECATED_ATTRIBUTE
224#undef __AVAILABILITY_MACROS_USES_AVAILABILITY
225#endif
684ec6c6
RS
226#include <openssl/ssl.h>
227#include <openssl/err.h>
228#endif
229
9806f5a7
NTND
230#ifdef HAVE_SYSINFO
231# include <sys/sysinfo.h>
232#endif
233
80ba074f
JS
234#ifndef PATH_SEP
235#define PATH_SEP ':'
236#endif
237
cb6a22c0
CW
238#ifdef HAVE_PATHS_H
239#include <paths.h>
240#endif
241#ifndef _PATH_DEFPATH
242#define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
243#endif
244
70fc5793 245#ifndef platform_core_config
a4e7e317 246struct config_context;
5cf88fd8
ÆAB
247static inline int noop_core_config(const char *var UNUSED,
248 const char *value UNUSED,
a4e7e317 249 const struct config_context *ctx UNUSED,
5cf88fd8 250 void *cb UNUSED)
70fc5793
JS
251{
252 return 0;
253}
254#define platform_core_config noop_core_config
255#endif
256
25fe217b 257#ifndef has_dos_drive_prefix
808e9195 258static inline int git_has_dos_drive_prefix(const char *path UNUSED)
bf728346
RS
259{
260 return 0;
261}
262#define has_dos_drive_prefix git_has_dos_drive_prefix
25fe217b
JS
263#endif
264
2f36eed9 265#ifndef skip_dos_drive_prefix
808e9195 266static inline int git_skip_dos_drive_prefix(char **path UNUSED)
2f36eed9
JS
267{
268 return 0;
269}
270#define skip_dos_drive_prefix git_skip_dos_drive_prefix
271#endif
272
bf728346
RS
273static inline int git_is_dir_sep(int c)
274{
275 return c == '/';
276}
9fd512c8 277#ifndef is_dir_sep
bf728346 278#define is_dir_sep git_is_dir_sep
c2369bdf
CZ
279#endif
280
bf728346
RS
281#ifndef offset_1st_component
282static inline int git_offset_1st_component(const char *path)
283{
284 return is_dir_sep(path[0]);
285}
286#define offset_1st_component git_offset_1st_component
25fe217b
JS
287#endif
288
193eda75
JS
289#ifndef fspathcmp
290#define fspathcmp git_fspathcmp
291#endif
292
293#ifndef fspathncmp
294#define fspathncmp git_fspathncmp
295#endif
296
d2c84dad
JS
297#ifndef is_valid_path
298#define is_valid_path(path) 1
299#endif
300
bdc77d1d 301#ifndef is_path_owned_by_current_user
ae9abbb6
CMAB
302
303#ifdef __TANDEM
304#define ROOT_UID 65535
305#else
306#define ROOT_UID 0
307#endif
308
309/*
310 * Do not use this function when
311 * (1) geteuid() did not say we are running as 'root', or
312 * (2) using this function will compromise the system.
313 *
314 * PORTABILITY WARNING:
315 * This code assumes uid_t is unsigned because that is what sudo does.
316 * If your uid_t type is signed and all your ids are positive then it
317 * should all work fine.
318 * If your version of sudo uses negative values for uid_t or it is
319 * buggy and return an overflowed value in SUDO_UID, then git might
320 * fail to grant access to your repository properly or even mistakenly
321 * grant access to someone else.
322 * In the unlikely scenario this happened to you, and that is how you
323 * got to this message, we would like to know about it; so sent us an
324 * email to git@vger.kernel.org indicating which platform you are
325 * using and which version of sudo, so we can improve this logic and
326 * maybe provide you with a patch that would prevent this issue again
327 * in the future.
328 */
329static inline void extract_id_from_env(const char *env, uid_t *id)
330{
331 const char *real_uid = getenv(env);
332
333 /* discard anything empty to avoid a more complex check below */
334 if (real_uid && *real_uid) {
335 char *endptr = NULL;
336 unsigned long env_id;
337
338 errno = 0;
339 /* silent overflow errors could trigger a bug here */
340 env_id = strtoul(real_uid, &endptr, 10);
341 if (!*endptr && !errno)
342 *id = env_id;
343 }
344}
345
776515ef 346static inline int is_path_owned_by_current_uid(const char *path,
5cf88fd8 347 struct strbuf *report UNUSED)
bdc77d1d
JS
348{
349 struct stat st;
ae9abbb6
CMAB
350 uid_t euid;
351
bdc77d1d
JS
352 if (lstat(path, &st))
353 return 0;
ae9abbb6
CMAB
354
355 euid = geteuid();
356 if (euid == ROOT_UID)
6b11e3d5
CMAB
357 {
358 if (st.st_uid == ROOT_UID)
359 return 1;
360 else
361 extract_id_from_env("SUDO_UID", &euid);
362 }
ae9abbb6
CMAB
363
364 return st.st_uid == euid;
bdc77d1d
JS
365}
366
367#define is_path_owned_by_current_user is_path_owned_by_current_uid
368#endif
369
d1c69255 370#ifndef find_last_dir_sep
bf728346
RS
371static inline char *git_find_last_dir_sep(const char *path)
372{
373 return strrchr(path, '/');
374}
375#define find_last_dir_sep git_find_last_dir_sep
d1c69255
TN
376#endif
377
05ac8582
AK
378#ifndef has_dir_sep
379static inline int git_has_dir_sep(const char *path)
380{
381 return !!strchr(path, '/');
382}
383#define has_dir_sep(path) git_has_dir_sep(path)
384#endif
385
501afcb8
JS
386#ifndef query_user_email
387#define query_user_email() NULL
388#endif
389
1305ef37
RB
390#ifdef __TANDEM
391#include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
392#include <floss.h(floss_getpwuid)>
393#ifndef NSIG
394/*
395 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
396 * known, by detective work using kill -l as a list is all signals
397 * instead of signal.h where it should be.
398 */
399# define NSIG 100
400#endif
401#endif
402
e4ac953b 403#if defined(__HP_cc) && (__HP_cc >= 61000)
b6ab349b
MR
404#define NORETURN __attribute__((noreturn))
405#define NORETURN_PTR
6520c846 406#elif defined(__GNUC__) && !defined(NO_NORETURN)
4050c0df 407#define NORETURN __attribute__((__noreturn__))
18660bc9 408#define NORETURN_PTR __attribute__((__noreturn__))
aba7dea8
RJ
409#elif defined(_MSC_VER)
410#define NORETURN __declspec(noreturn)
411#define NORETURN_PTR
4050c0df
JH
412#else
413#define NORETURN
18660bc9 414#define NORETURN_PTR
8cd7ebc8 415#ifndef __GNUC__
4050c0df
JH
416#ifndef __attribute__
417#define __attribute__(x)
418#endif
419#endif
8cd7ebc8 420#endif
4050c0df 421
9fe3edc4
RJ
422/* The sentinel attribute is valid from gcc version 4.0 */
423#if defined(__GNUC__) && (__GNUC__ >= 4)
424#define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
1e8697b5
ÆAB
425/* warn_unused_result exists as of gcc 3.4.0, but be lazy and check 4.0 */
426#define RESULT_MUST_BE_USED __attribute__ ((warn_unused_result))
9fe3edc4
RJ
427#else
428#define LAST_ARG_MUST_BE_NULL
1e8697b5 429#define RESULT_MUST_BE_USED
9fe3edc4
RJ
430#endif
431
a051ca5e
JH
432/*
433 * MAYBE_UNUSED marks a function parameter that may be unused, but
434 * whose use is not an error. It also can be used to annotate a
435 * function, a variable, or a type that may be unused.
436 *
437 * Depending on a configuration, all uses of such a thing may become
438 * #ifdef'ed away. Marking it with UNUSED would give a warning in a
439 * compilation where it is indeed used, and not marking it at all
440 * would give a warning in a compilation where it is unused. In such
441 * a case, MAYBE_UNUSED is the appropriate annotation to use.
442 */
bbd8eb3e
CMAB
443#define MAYBE_UNUSED __attribute__((__unused__))
444
51ea5519
NP
445#include "compat/bswap.h"
446
382f6940 447#include "wrapper.h"
9ccc0c08 448
4050c0df 449/* General helper functions */
55454427 450NORETURN void usage(const char *err);
b199d714
DL
451NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
452NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
453NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
18568ee8 454int die_message(const char *err, ...) __attribute__((format (printf, 1, 2)));
24f6e6d6 455int die_message_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
b199d714
DL
456int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
457int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
458void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
459void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
4050c0df 460
0148fd83
JH
461void show_usage_if_asked(int ac, const char **av, const char *err);
462
4511d56e
JH
463NORETURN void you_still_use_that(const char *command_name);
464
f2be034c
BG
465#ifndef NO_OPENSSL
466#ifdef APPLE_COMMON_CRYPTO
467#include "compat/apple-common-crypto.h"
468#else
469#include <openssl/evp.h>
470#include <openssl/hmac.h>
471#endif /* APPLE_COMMON_CRYPTO */
472#include <openssl/x509v3.h>
473#endif /* NO_OPENSSL */
474
5b52d9f1
CMAB
475#ifdef HAVE_OPENSSL_CSPRNG
476#include <openssl/rand.h>
477#endif
478
e208f9cc
JK
479/*
480 * Let callers be aware of the constant return value; this can help
9798f7e5 481 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
b7ba8587 482 * because other compilers may be confused by this.
e208f9cc 483 */
ff0a80af 484#if defined(__GNUC__)
87fe5df3
JK
485static inline int const_error(void)
486{
487 return -1;
488}
489#define error(...) (error(__VA_ARGS__), const_error())
4df5e918 490#define error_errno(...) (error_errno(__VA_ARGS__), const_error())
e208f9cc
JK
491#endif
492
5710dcce
JK
493typedef void (*report_fn)(const char *, va_list params);
494
495void set_die_routine(NORETURN_PTR report_fn routine);
18568ee8 496report_fn get_die_message_routine(void);
5710dcce
JK
497void set_error_routine(report_fn routine);
498report_fn get_error_routine(void);
499void set_warn_routine(report_fn routine);
500report_fn get_warn_routine(void);
55454427 501void set_die_is_recursing_routine(int (*routine)(void));
39a3f5ea 502
cf4fff57 503/*
8277dbe9 504 * If the string "str" begins with the string found in "prefix", return true.
cf4fff57
JK
505 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
506 * the string right after the prefix).
507 *
8277dbe9 508 * Otherwise, return false and leave "out" untouched.
cf4fff57
JK
509 *
510 * Examples:
511 *
512 * [extract branch name, fail if not a branch]
513 * if (!skip_prefix(ref, "refs/heads/", &branch)
514 * return -1;
515 *
516 * [skip prefix if present, otherwise use whole string]
517 * skip_prefix(name, "refs/heads/", &name);
518 */
8277dbe9
RS
519static inline bool skip_prefix(const char *str, const char *prefix,
520 const char **out)
fbca5837 521{
ba399c46 522 do {
cf4fff57
JK
523 if (!*prefix) {
524 *out = str;
8277dbe9 525 return true;
cf4fff57 526 }
ba399c46 527 } while (*str++ == *prefix++);
8277dbe9 528 return false;
fbca5837
MV
529}
530
ae989a61
JK
531/*
532 * Like skip_prefix, but promises never to read past "len" bytes of the input
533 * buffer, and returns the remaining number of bytes in "out" via "outlen".
534 */
8277dbe9
RS
535static inline bool skip_prefix_mem(const char *buf, size_t len,
536 const char *prefix,
537 const char **out, size_t *outlen)
ae989a61
JK
538{
539 size_t prefix_len = strlen(prefix);
540 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
541 *out = buf + prefix_len;
542 *outlen = len - prefix_len;
8277dbe9 543 return true;
ae989a61 544 }
8277dbe9 545 return false;
ae989a61
JK
546}
547
35480f0b 548/*
8277dbe9
RS
549 * If buf ends with suffix, return true and subtract the length of the suffix
550 * from *len. Otherwise, return false and leave *len untouched.
35480f0b 551 */
8277dbe9
RS
552static inline bool strip_suffix_mem(const char *buf, size_t *len,
553 const char *suffix)
35480f0b
JK
554{
555 size_t suflen = strlen(suffix);
556 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
8277dbe9 557 return false;
35480f0b 558 *len -= suflen;
8277dbe9 559 return true;
35480f0b
JK
560}
561
562/*
8277dbe9
RS
563 * If str ends with suffix, return true and set *len to the size of the string
564 * without the suffix. Otherwise, return false and set *len to the size of the
35480f0b
JK
565 * string.
566 *
567 * Note that we do _not_ NUL-terminate str to the new length.
568 */
8277dbe9
RS
569static inline bool strip_suffix(const char *str, const char *suffix,
570 size_t *len)
35480f0b
JK
571{
572 *len = strlen(str);
573 return strip_suffix_mem(str, len, suffix);
574}
575
568edcb9
RS
576#define SWAP(a, b) do { \
577 void *_swap_a_ptr = &(a); \
578 void *_swap_b_ptr = &(b); \
579 unsigned char _swap_buffer[sizeof(a)]; \
580 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
581 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
582 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
583 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
584} while (0)
585
b130a72b
JL
586#ifdef NO_MMAP
587
5faaf246 588/* This value must be multiple of (pagesize * 2) */
8c82534d
SP
589#define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
590
4050c0df
JH
591#else /* NO_MMAP */
592
5faaf246 593/* This value must be multiple of (pagesize * 2) */
22bac0ea
SP
594#define DEFAULT_PACKED_GIT_WINDOW_SIZE \
595 (sizeof(void*) >= 8 \
596 ? 1 * 1024 * 1024 * 1024 \
597 : 32 * 1024 * 1024)
4050c0df
JH
598
599#endif /* NO_MMAP */
600
fdb2a2a6
JH
601#ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
602#define on_disk_bytes(st) ((st).st_size)
603#else
604#define on_disk_bytes(st) ((st).st_blocks * 512)
605#endif
606
22bac0ea 607#define DEFAULT_PACKED_GIT_LIMIT \
be4ca290 608 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
8c82534d 609
97dc141f
PS
610int git_open_cloexec(const char *name, int flags);
611#define git_open(name) git_open_cloexec(name, O_RDONLY)
612
320d0b49
JK
613static inline size_t st_add(size_t a, size_t b)
614{
615 if (unsigned_add_overflows(a, b))
616 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
617 (uintmax_t)a, (uintmax_t)b);
618 return a + b;
619}
d616fbf2
ES
620#define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
621#define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
320d0b49
JK
622
623static inline size_t st_mult(size_t a, size_t b)
624{
625 if (unsigned_mult_overflows(a, b))
626 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
627 (uintmax_t)a, (uintmax_t)b);
628 return a * b;
629}
630
631static inline size_t st_sub(size_t a, size_t b)
632{
633 if (a < b)
634 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
635 (uintmax_t)a, (uintmax_t)b);
636 return a - b;
637}
a9a74636 638
e2ffeae3
JS
639static inline size_t st_left_shift(size_t a, unsigned shift)
640{
641 if (unsigned_left_shift_overflows(a, shift))
642 die("size_t overflow: %"PRIuMAX" << %u",
643 (uintmax_t)a, shift);
644 return a << shift;
645}
646
647static inline unsigned long cast_size_t_to_ulong(size_t a)
648{
649 if (a != (unsigned long)a)
650 die("object too large to read on this platform: %"
651 PRIuMAX" is cut off to %lu",
652 (uintmax_t)a, (unsigned long)a);
653 return (unsigned long)a;
654}
655
ed9f4148
TB
656static inline uint32_t cast_size_t_to_uint32_t(size_t a)
657{
658 if (a != (uint32_t)a)
659 die("object too large to read on this platform: %"
660 PRIuMAX" is cut off to %u",
661 (uintmax_t)a, (uint32_t)a);
662 return (uint32_t)a;
663}
664
48050c42
PS
665static inline int cast_size_t_to_int(size_t a)
666{
667 if (a > INT_MAX)
668 die("number too large to represent as int on this platform: %"PRIuMAX,
669 (uintmax_t)a);
670 return (int)a;
671}
672
b103881d
PW
673static inline uint64_t u64_mult(uint64_t a, uint64_t b)
674{
675 if (unsigned_mult_overflows(a, b))
676 die("uint64_t overflow: %"PRIuMAX" * %"PRIuMAX,
677 (uintmax_t)a, (uintmax_t)b);
678 return a * b;
679}
680
681static inline uint64_t u64_add(uint64_t a, uint64_t b)
682{
683 if (unsigned_add_overflows(a, b))
684 die("uint64_t overflow: %"PRIuMAX" + %"PRIuMAX,
685 (uintmax_t)a, (uintmax_t)b);
686 return a + b;
687}
688
ec4f39b2
JK
689/*
690 * Limit size of IO chunks, because huge chunks only cause pain. OS X
691 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
692 * the absence of bugs, large chunks can result in bad latencies when
693 * you decide to kill the process.
694 *
695 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
696 * that is smaller than that, clip it to SSIZE_MAX, as a call to
697 * read(2) or write(2) larger than that is allowed to fail. As the last
698 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
699 * to override this, if the definition of SSIZE_MAX given by the platform
700 * is broken.
701 */
702#ifndef MAX_IO_SIZE
703# define MAX_IO_SIZE_DEFAULT (8*1024*1024)
704# if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
705# define MAX_IO_SIZE SSIZE_MAX
706# else
707# define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
708# endif
709#endif
710
61f76a36
KS
711#ifdef HAVE_ALLOCA_H
712# include <alloca.h>
713# define xalloca(size) (alloca(size))
714# define xalloca_free(p) do {} while (0)
715#else
716# define xalloca(size) (xmalloc(size))
717# define xalloca_free(p) (free(p))
718#endif
14570dc6 719
481df65f
ÆAB
720/*
721 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
722 * that ptr is used twice, so don't pass e.g. ptr++.
723 */
724#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
725
e7792a74 726#define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
f1121499 727#define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
e7792a74 728#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
3ac22f82 729
60566cbb 730#define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
1891846f 731 BARF_UNLESS_COPYABLE((dst), (src)))
60566cbb
RS
732static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
733{
734 if (n)
735 memcpy(dst, src, st_mult(size, n));
736}
737
57839807 738#define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
1891846f 739 BARF_UNLESS_COPYABLE((dst), (src)))
57839807
RS
740static inline void move_array(void *dst, const void *src, size_t n, size_t size)
741{
742 if (n)
743 memmove(dst, src, st_mult(size, n));
744}
745
d2ec87a6
RS
746#define DUP_ARRAY(dst, src, n) do { \
747 size_t dup_array_n_ = (n); \
748 COPY_ARRAY(ALLOC_ARRAY((dst), dup_array_n_), (src), dup_array_n_); \
749} while (0)
750
36895391
JK
751/*
752 * These functions help you allocate structs with flex arrays, and copy
753 * the data directly into the array. For example, if you had:
754 *
755 * struct foo {
756 * int bar;
757 * char name[FLEX_ARRAY];
758 * };
759 *
760 * you can do:
761 *
762 * struct foo *f;
763 * FLEX_ALLOC_MEM(f, name, src, len);
764 *
765 * to allocate a "foo" with the contents of "src" in the "name" field.
766 * The resulting struct is automatically zero'd, and the flex-array field
767 * is NUL-terminated (whether the incoming src buffer was or not).
768 *
769 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
770 * but do want to store a pointer to some extra data in the same allocated
771 * block. For example, if you have:
772 *
773 * struct foo {
774 * char *name;
775 * int bar;
776 * };
777 *
778 * you can do:
779 *
780 * struct foo *f;
0bb1519f 781 * FLEXPTR_ALLOC_STR(f, name, src);
36895391
JK
782 *
783 * and "name" will point to a block of memory after the struct, which will be
784 * freed along with the struct (but the pointer can be repointed anywhere).
785 *
786 * The *_STR variants accept a string parameter rather than a ptr/len
787 * combination.
788 *
789 * Note that these macros will evaluate the first parameter multiple
790 * times, and it must be assignable as an lvalue.
791 */
792#define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
e9451782
RS
793 size_t flex_array_len_ = (len); \
794 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
795 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
36895391
JK
796} while (0)
797#define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
0ac52a38
RS
798 size_t flex_array_len_ = (len); \
799 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
800 memcpy((x) + 1, (buf), flex_array_len_); \
36895391
JK
801 (x)->ptrname = (void *)((x)+1); \
802} while(0)
803#define FLEX_ALLOC_STR(x, flexname, str) \
804 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
805#define FLEXPTR_ALLOC_STR(x, ptrname, str) \
806 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
807
91c080df
CW
808#define alloc_nr(x) (((x)+16)*3/2)
809
810/**
811 * Dynamically growing an array using realloc() is error prone and boring.
812 *
813 * Define your array with:
814 *
815 * - a pointer (`item`) that points at the array, initialized to `NULL`
816 * (although please name the variable based on its contents, not on its
817 * type);
818 *
819 * - an integer variable (`alloc`) that keeps track of how big the current
820 * allocation is, initialized to `0`;
821 *
822 * - another integer variable (`nr`) to keep track of how many elements the
823 * array currently has, initialized to `0`.
824 *
825 * Then before adding `n`th element to the item, call `ALLOC_GROW(item, n,
826 * alloc)`. This ensures that the array can hold at least `n` elements by
827 * calling `realloc(3)` and adjusting `alloc` variable.
828 *
829 * ------------
830 * sometype *item;
831 * size_t nr;
832 * size_t alloc
833 *
834 * for (i = 0; i < nr; i++)
835 * if (we like item[i] already)
836 * return;
837 *
838 * // we did not like any existing one, so add one
839 * ALLOC_GROW(item, nr + 1, alloc);
840 * item[nr++] = value you like;
841 * ------------
842 *
843 * You are responsible for updating the `nr` variable.
844 *
845 * If you need to specify the number of elements to allocate explicitly
846 * then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`.
847 *
848 * Consider using ALLOC_GROW_BY instead of ALLOC_GROW as it has some
849 * added niceties.
850 *
851 * DO NOT USE any expression with side-effect for 'x', 'nr', or 'alloc'.
852 */
853#define ALLOC_GROW(x, nr, alloc) \
854 do { \
855 if ((nr) > alloc) { \
856 if (alloc_nr(alloc) < (nr)) \
857 alloc = (nr); \
858 else \
859 alloc = alloc_nr(alloc); \
860 REALLOC_ARRAY(x, alloc); \
861 } \
862 } while (0)
863
864/*
865 * Similar to ALLOC_GROW but handles updating of the nr value and
866 * zeroing the bytes of the newly-grown array elements.
867 *
868 * DO NOT USE any expression with side-effect for any of the
869 * arguments.
870 */
871#define ALLOC_GROW_BY(x, nr, increase, alloc) \
872 do { \
873 if (increase) { \
874 size_t new_nr = nr + (increase); \
875 if (new_nr < nr) \
876 BUG("negative growth in ALLOC_GROW_BY"); \
877 ALLOC_GROW(x, new_nr, alloc); \
878 memset((x) + nr, 0, sizeof(*(x)) * (increase)); \
879 nr = new_nr; \
880 } \
881 } while (0)
882
d64ea0f8
JK
883static inline char *xstrdup_or_null(const char *str)
884{
885 return str ? xstrdup(str) : NULL;
886}
887
dc49cd76
SP
888static inline size_t xsize_t(off_t len)
889{
aafa5df0 890 if (len < 0 || (uintmax_t) len > SIZE_MAX)
46be82df 891 die("Cannot handle files this big");
aafa5df0 892 return (size_t) len;
dc49cd76
SP
893}
894
41a80924
JK
895/*
896 * Like skip_prefix, but compare case-insensitively. Note that the comparison
897 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
898 * locale-specific conversions).
899 */
900static inline int skip_iprefix(const char *str, const char *prefix,
901 const char **out)
902{
903 do {
904 if (!*prefix) {
905 *out = str;
906 return 1;
907 }
908 } while (tolower(*str++) == tolower(*prefix++));
909 return 0;
910}
911
6b8dda9a
MJC
912/*
913 * Like skip_prefix_mem, but compare case-insensitively. Note that the
914 * comparison is done via tolower(), so it is strictly ASCII (no multi-byte
915 * characters or locale-specific conversions).
916 */
917static inline int skip_iprefix_mem(const char *buf, size_t len,
918 const char *prefix,
919 const char **out, size_t *outlen)
920{
921 do {
922 if (!*prefix) {
923 *out = buf;
924 *outlen = len;
925 return 1;
926 }
927 } while (len-- > 0 && tolower(*buf++) == tolower(*prefix++));
928 return 0;
929}
930
6aead43d
JM
931static inline int strtoul_ui(char const *s, int base, unsigned int *result)
932{
933 unsigned long ul;
934 char *p;
935
936 errno = 0;
e6f2599c
MM
937 /* negative values would be accepted by strtoul */
938 if (strchr(s, '-'))
939 return -1;
6aead43d
JM
940 ul = strtoul(s, &p, base);
941 if (errno || *p || p == s || (unsigned int) ul != ul)
942 return -1;
943 *result = ul;
944 return 0;
945}
946
7791ecbc
JH
947static inline int strtol_i(char const *s, int base, int *result)
948{
949 long ul;
950 char *p;
951
952 errno = 0;
953 ul = strtol(s, &p, base);
954 if (errno || *p || p == s || (int) ul != ul)
955 return -1;
956 *result = ul;
957 return 0;
958}
959
2f895225
JS
960#ifndef REG_STARTEND
961#error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
962#endif
963
964static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
965 size_t nmatch, regmatch_t pmatch[], int eflags)
966{
967 assert(nmatch > 0 && pmatch);
968 pmatch[0].rm_so = 0;
969 pmatch[0].rm_eo = size;
970 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
971}
972
54463d32
RS
973#ifdef USE_ENHANCED_BASIC_REGULAR_EXPRESSIONS
974int git_regcomp(regex_t *preg, const char *pattern, int cflags);
975#define regcomp git_regcomp
976#endif
977
81a24b52
AR
978#ifndef DIR_HAS_BSD_GROUP_SEMANTICS
979# define FORCE_DIR_SET_GID S_ISGID
980#else
981# define FORCE_DIR_SET_GID 0
982#endif
983
34779c53
JS
984#ifdef UNRELIABLE_FSTAT
985#define fstat_is_reliable() 0
986#else
987#define fstat_is_reliable() 1
988#endif
989
746ea4ad
RJ
990/* usage.c: only to be used for testing BUG() implementation (see test-tool) */
991extern int BUG_exit_code;
992
0cc05b04
ÆAB
993/* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
994extern int bug_called_must_BUG;
995
d8193743
JK
996__attribute__((format (printf, 3, 4))) NORETURN
997void BUG_fl(const char *file, int line, const char *fmt, ...);
998#define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
07fbc15c
EN
999/* ASSERT: like assert(), but won't be compiled out with NDEBUG */
1000#define ASSERT(a) if (!(a)) BUG("Assertion `" #a "' failed.")
0cc05b04
ÆAB
1001__attribute__((format (printf, 3, 4)))
1002void bug_fl(const char *file, int line, const char *fmt, ...);
1003#define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1004#define BUG_if_bug(...) do { \
1005 if (bug_called_must_BUG) \
1006 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1007} while (0)
d8193743 1008
8a94d833 1009#ifndef FSYNC_METHOD_DEFAULT
abf38abe
NS
1010#ifdef __APPLE__
1011#define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1012#else
1013#define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1014#endif
8a94d833 1015#endif
abf38abe 1016
1b56cdf9
KM
1017#ifndef SHELL_PATH
1018# define SHELL_PATH "/bin/sh"
1019#endif
1020
dc5a18b3
JH
1021/*
1022 * Our code often opens a path to an optional file, to work on its
1023 * contents when we can successfully open it. We can ignore a failure
1024 * to open if such an optional file does not exist, but we do want to
1025 * report a failure in opening for other reasons (e.g. we got an I/O
1026 * error, or the file is there, but we lack the permission to open).
1027 *
1028 * Call this function after seeing an error from open() or fopen() to
1029 * see if the errno indicates a missing file that we can safely ignore.
1030 */
1031static inline int is_missing_file_error(int errno_)
1032{
1033 return (errno_ == ENOENT || errno_ == ENOTDIR);
1034}
1035
55454427 1036int cmd_main(int, const char **);
5c238e29 1037
ee4512ed
JH
1038/*
1039 * Intercept all calls to exit() and route them to trace2 to
1040 * optionally emit a message before calling the real exit().
1041 */
19d75948
ÆAB
1042int common_exit(const char *file, int line, int code);
1043#define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
ee4512ed 1044
c8af66ab
JK
1045/*
1046 * This include must come after system headers, since it introduces macros that
1047 * replace system names.
1048 */
1049#include "banned.h"
1050
973d5eea
EW
1051/*
1052 * container_of - Get the address of an object containing a field.
1053 *
1054 * @ptr: pointer to the field.
1055 * @type: type of the object.
1056 * @member: name of the field within the object.
1057 */
1058#define container_of(ptr, type, member) \
1059 ((type *) ((char *)(ptr) - offsetof(type, member)))
1060
f0e63c41
EW
1061/*
1062 * helper function for `container_of_or_null' to avoid multiple
1063 * evaluation of @ptr
1064 */
1065static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1066{
1067 return ptr ? (char *)ptr - offset : NULL;
1068}
1069
1070/*
1071 * like `container_of', but allows returned value to be NULL
1072 */
1073#define container_of_or_null(ptr, type, member) \
1074 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1075
23dee69f 1076/*
abcb66c6 1077 * like offsetof(), but takes a pointer to a variable of type which
23dee69f
EW
1078 * contains @member, instead of a specified type.
1079 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1080 * everywhere.
1081 */
1082#if defined(__GNUC__) /* clang sets this, too */
1083#define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1084#else /* !__GNUC__ */
1085#define OFFSETOF_VAR(ptr, member) \
1086 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1087#endif /* !__GNUC__ */
1088
82e79c63
JH
1089/*
1090 * Prevent an overly clever compiler from optimizing an expression
1091 * out, triggering a false positive when building with the
1092 * -Wunreachable-code option. false_but_the_compiler_does_not_know_it_
1093 * is defined in a compilation unit separate from where the macro is
1094 * used, initialized to 0, and never modified.
1095 */
1096#define NOT_CONSTANT(expr) ((expr) || false_but_the_compiler_does_not_know_it_)
1097extern int false_but_the_compiler_does_not_know_it_;
b97b360c 1098
85e4f762
EN
1099#ifdef CHECK_ASSERTION_SIDE_EFFECTS
1100#undef assert
1101extern int not_supposed_to_survive;
1102#define assert(expr) ((void)(not_supposed_to_survive || (expr)))
1103#endif /* CHECK_ASSERTION_SIDE_EFFECTS */
1104
5c238e29 1105#endif