]> git.ipfire.org Git - thirdparty/git.git/blob - git-compat-util.h
5bd69ec04034d4b977f1d41066cbc34b6871e9c0
[thirdparty/git.git] / git-compat-util.h
1 #ifndef GIT_COMPAT_UTIL_H
2 #define GIT_COMPAT_UTIL_H
3
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
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
26 #include "compat/posix.h"
27
28 struct strbuf;
29
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
38 DISABLE_WARNING(-Wsign-compare)
39 #endif
40
41 #ifndef FLEX_ARRAY
42 /*
43 * See if our compiler is known to support flexible array members.
44 */
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)
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
60 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
61 # define FLEX_ARRAY /* empty */
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
69 #endif
70 #endif
71
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
88 #if GIT_GNUC_PREREQ(3, 1)
89 /* &arr[0] degrades to a pointer: a different type from an array */
90 # define BARF_UNLESS_AN_ARRAY(arr) \
91 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
92 __typeof__(&(arr)[0])))
93 # define BARF_UNLESS_COPYABLE(dst, src) \
94 BUILD_ASSERT_OR_ZERO(__builtin_types_compatible_p(__typeof__(*(dst)), \
95 __typeof__(*(src))))
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)
99 #else
100 # define BARF_UNLESS_AN_ARRAY(arr) 0
101 # define BARF_UNLESS_COPYABLE(dst, src) \
102 BUILD_ASSERT_OR_ZERO(0 ? ((*(dst) = *(src)), 0) : \
103 sizeof(*(dst)) == sizeof(*(src)))
104
105 # define BARF_UNLESS_SIGNED(var) 0
106 # define BARF_UNLESS_UNSIGNED(var) 0
107 #endif
108
109 /*
110 * ARRAY_SIZE - get the number of elements in a visible array
111 * @x: the array whose size you want.
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
119 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
120
121 #define maximum_signed_value_of_type(a) \
122 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
123
124 #define maximum_unsigned_value_of_type(a) \
125 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
126
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
136 #define unsigned_add_overflows(a, b) \
137 ((b) > maximum_unsigned_value_of_type(a) - (a))
138
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
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
155 #ifdef __GNUC__
156 #define TYPEOF(x) (__typeof__(x))
157 #else
158 #define TYPEOF(x)
159 #endif
160
161 #define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
162 #define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
163
164 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
165
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
169 #if defined(NO_UNIX_SOCKETS) || !defined(GIT_WINDOWS_NATIVE)
170 static 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
181 /* Used by compat/win32/path-utils.h, and more */
182 static inline int is_xplatform_dir_sep(int c)
183 {
184 return c == '/' || c == '\\';
185 }
186
187 #if defined(__CYGWIN__)
188 #include "compat/win32/path-utils.h"
189 #endif
190 #if defined(__MINGW32__)
191 /* pull in Windows compatibility stuff */
192 #include "compat/win32/path-utils.h"
193 #include "compat/mingw.h"
194 #elif defined(_MSC_VER)
195 #include "compat/win32/path-utils.h"
196 #include "compat/msvc.h"
197 #endif
198
199 /* used on Mac OS X */
200 #ifdef PRECOMPOSE_UNICODE
201 #include "compat/precompose_utf8.h"
202 #else
203 static inline const char *precompose_argv_prefix(int argc UNUSED,
204 const char **argv UNUSED,
205 const char *prefix)
206 {
207 return prefix;
208 }
209 static inline const char *precompose_string_if_needed(const char *in)
210 {
211 return in;
212 }
213
214 #define probe_utf8_pathname_composition()
215 #endif
216
217 #ifndef NO_OPENSSL
218 #ifdef __APPLE__
219 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
220 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
221 #include <AvailabilityMacros.h>
222 #undef DEPRECATED_ATTRIBUTE
223 #define DEPRECATED_ATTRIBUTE
224 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
225 #endif
226 #include <openssl/ssl.h>
227 #include <openssl/err.h>
228 #endif
229
230 #ifdef HAVE_SYSINFO
231 # include <sys/sysinfo.h>
232 #endif
233
234 #ifndef PATH_SEP
235 #define PATH_SEP ':'
236 #endif
237
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
245 #ifndef platform_core_config
246 struct config_context;
247 static inline int noop_core_config(const char *var UNUSED,
248 const char *value UNUSED,
249 const struct config_context *ctx UNUSED,
250 void *cb UNUSED)
251 {
252 return 0;
253 }
254 #define platform_core_config noop_core_config
255 #endif
256
257 #ifndef has_dos_drive_prefix
258 static inline int git_has_dos_drive_prefix(const char *path UNUSED)
259 {
260 return 0;
261 }
262 #define has_dos_drive_prefix git_has_dos_drive_prefix
263 #endif
264
265 #ifndef skip_dos_drive_prefix
266 static inline int git_skip_dos_drive_prefix(char **path UNUSED)
267 {
268 return 0;
269 }
270 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
271 #endif
272
273 static inline int git_is_dir_sep(int c)
274 {
275 return c == '/';
276 }
277 #ifndef is_dir_sep
278 #define is_dir_sep git_is_dir_sep
279 #endif
280
281 #ifndef offset_1st_component
282 static 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
287 #endif
288
289 #ifndef fspathcmp
290 #define fspathcmp git_fspathcmp
291 #endif
292
293 #ifndef fspathncmp
294 #define fspathncmp git_fspathncmp
295 #endif
296
297 #ifndef is_valid_path
298 #define is_valid_path(path) 1
299 #endif
300
301 #ifndef is_path_owned_by_current_user
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 */
329 static 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
346 static inline int is_path_owned_by_current_uid(const char *path,
347 struct strbuf *report UNUSED)
348 {
349 struct stat st;
350 uid_t euid;
351
352 if (lstat(path, &st))
353 return 0;
354
355 euid = geteuid();
356 if (euid == ROOT_UID)
357 {
358 if (st.st_uid == ROOT_UID)
359 return 1;
360 else
361 extract_id_from_env("SUDO_UID", &euid);
362 }
363
364 return st.st_uid == euid;
365 }
366
367 #define is_path_owned_by_current_user is_path_owned_by_current_uid
368 #endif
369
370 #ifndef find_last_dir_sep
371 static 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
376 #endif
377
378 #ifndef has_dir_sep
379 static 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
386 #ifndef query_user_email
387 #define query_user_email() NULL
388 #endif
389
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
403 #if defined(__HP_cc) && (__HP_cc >= 61000)
404 #define NORETURN __attribute__((noreturn))
405 #define NORETURN_PTR
406 #elif defined(__GNUC__) && !defined(NO_NORETURN)
407 #define NORETURN __attribute__((__noreturn__))
408 #define NORETURN_PTR __attribute__((__noreturn__))
409 #elif defined(_MSC_VER)
410 #define NORETURN __declspec(noreturn)
411 #define NORETURN_PTR
412 #else
413 #define NORETURN
414 #define NORETURN_PTR
415 #ifndef __GNUC__
416 #ifndef __attribute__
417 #define __attribute__(x)
418 #endif
419 #endif
420 #endif
421
422 /* The sentinel attribute is valid from gcc version 4.0 */
423 #if defined(__GNUC__) && (__GNUC__ >= 4)
424 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
425 /* warn_unused_result exists as of gcc 3.4.0, but be lazy and check 4.0 */
426 #define RESULT_MUST_BE_USED __attribute__ ((warn_unused_result))
427 #else
428 #define LAST_ARG_MUST_BE_NULL
429 #define RESULT_MUST_BE_USED
430 #endif
431
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 */
443 #define MAYBE_UNUSED __attribute__((__unused__))
444
445 #include "compat/bswap.h"
446
447 #include "wrapper.h"
448
449 /* General helper functions */
450 NORETURN void usage(const char *err);
451 NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
452 NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
453 NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
454 int die_message(const char *err, ...) __attribute__((format (printf, 1, 2)));
455 int die_message_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
456 int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
457 int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
458 void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
459 void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
460
461 void show_usage_if_asked(int ac, const char **av, const char *err);
462
463 NORETURN void you_still_use_that(const char *command_name);
464
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
475 #ifdef HAVE_OPENSSL_CSPRNG
476 #include <openssl/rand.h>
477 #endif
478
479 /*
480 * Let callers be aware of the constant return value; this can help
481 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
482 * because other compilers may be confused by this.
483 */
484 #if defined(__GNUC__)
485 static inline int const_error(void)
486 {
487 return -1;
488 }
489 #define error(...) (error(__VA_ARGS__), const_error())
490 #define error_errno(...) (error_errno(__VA_ARGS__), const_error())
491 #endif
492
493 typedef void (*report_fn)(const char *, va_list params);
494
495 void set_die_routine(NORETURN_PTR report_fn routine);
496 report_fn get_die_message_routine(void);
497 void set_error_routine(report_fn routine);
498 report_fn get_error_routine(void);
499 void set_warn_routine(report_fn routine);
500 report_fn get_warn_routine(void);
501 void set_die_is_recursing_routine(int (*routine)(void));
502
503 /*
504 * If the string "str" begins with the string found in "prefix", return true.
505 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
506 * the string right after the prefix).
507 *
508 * Otherwise, return false and leave "out" untouched.
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 */
519 static inline bool skip_prefix(const char *str, const char *prefix,
520 const char **out)
521 {
522 do {
523 if (!*prefix) {
524 *out = str;
525 return true;
526 }
527 } while (*str++ == *prefix++);
528 return false;
529 }
530
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 */
535 static inline bool skip_prefix_mem(const char *buf, size_t len,
536 const char *prefix,
537 const char **out, size_t *outlen)
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;
543 return true;
544 }
545 return false;
546 }
547
548 /*
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.
551 */
552 static inline bool strip_suffix_mem(const char *buf, size_t *len,
553 const char *suffix)
554 {
555 size_t suflen = strlen(suffix);
556 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
557 return false;
558 *len -= suflen;
559 return true;
560 }
561
562 /*
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
565 * string.
566 *
567 * Note that we do _not_ NUL-terminate str to the new length.
568 */
569 static inline bool strip_suffix(const char *str, const char *suffix,
570 size_t *len)
571 {
572 *len = strlen(str);
573 return strip_suffix_mem(str, len, suffix);
574 }
575
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
586 #ifdef NO_MMAP
587
588 /* This value must be multiple of (pagesize * 2) */
589 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
590
591 #else /* NO_MMAP */
592
593 /* This value must be multiple of (pagesize * 2) */
594 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
595 (sizeof(void*) >= 8 \
596 ? 1 * 1024 * 1024 * 1024 \
597 : 32 * 1024 * 1024)
598
599 #endif /* NO_MMAP */
600
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
607 #define DEFAULT_PACKED_GIT_LIMIT \
608 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
609
610 int git_open_cloexec(const char *name, int flags);
611 #define git_open(name) git_open_cloexec(name, O_RDONLY)
612
613 static 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 }
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))
622
623 static 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
631 static 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 }
638
639 static 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
647 static 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
656 static 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
665 static 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
673 static 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
681 static 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
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
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
719
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
726 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
727 #define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)))
728 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
729
730 #define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
731 BARF_UNLESS_COPYABLE((dst), (src)))
732 static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
733 {
734 if (n)
735 memcpy(dst, src, st_mult(size, n));
736 }
737
738 #define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
739 BARF_UNLESS_COPYABLE((dst), (src)))
740 static inline void move_array(void *dst, const void *src, size_t n, size_t size)
741 {
742 if (n)
743 memmove(dst, src, st_mult(size, n));
744 }
745
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
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;
781 * FLEXPTR_ALLOC_STR(f, name, src);
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 { \
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_); \
796 } while (0)
797 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
798 size_t flex_array_len_ = (len); \
799 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
800 memcpy((x) + 1, (buf), flex_array_len_); \
801 (x)->ptrname = (void *)((x)+1); \
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
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
883 static inline char *xstrdup_or_null(const char *str)
884 {
885 return str ? xstrdup(str) : NULL;
886 }
887
888 static inline size_t xsize_t(off_t len)
889 {
890 if (len < 0 || (uintmax_t) len > SIZE_MAX)
891 die("Cannot handle files this big");
892 return (size_t) len;
893 }
894
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 */
900 static 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
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 */
917 static 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
931 static inline int strtoul_ui(char const *s, int base, unsigned int *result)
932 {
933 unsigned long ul;
934 char *p;
935
936 errno = 0;
937 /* negative values would be accepted by strtoul */
938 if (strchr(s, '-'))
939 return -1;
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
947 static 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
960 #ifndef REG_STARTEND
961 #error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
962 #endif
963
964 static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
965 size_t nmatch, regmatch_t pmatch[], int eflags)
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
973 #ifdef USE_ENHANCED_BASIC_REGULAR_EXPRESSIONS
974 int git_regcomp(regex_t *preg, const char *pattern, int cflags);
975 #define regcomp git_regcomp
976 #endif
977
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
984 #ifdef UNRELIABLE_FSTAT
985 #define fstat_is_reliable() 0
986 #else
987 #define fstat_is_reliable() 1
988 #endif
989
990 /* usage.c: only to be used for testing BUG() implementation (see test-tool) */
991 extern int BUG_exit_code;
992
993 /* usage.c: if bug() is called we should have a BUG_if_bug() afterwards */
994 extern int bug_called_must_BUG;
995
996 __attribute__((format (printf, 3, 4))) NORETURN
997 void BUG_fl(const char *file, int line, const char *fmt, ...);
998 #define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
999 /* ASSERT: like assert(), but won't be compiled out with NDEBUG */
1000 #define ASSERT(a) if (!(a)) BUG("Assertion `" #a "' failed.")
1001 __attribute__((format (printf, 3, 4)))
1002 void bug_fl(const char *file, int line, const char *fmt, ...);
1003 #define bug(...) bug_fl(__FILE__, __LINE__, __VA_ARGS__)
1004 #define BUG_if_bug(...) do { \
1005 if (bug_called_must_BUG) \
1006 BUG_fl(__FILE__, __LINE__, __VA_ARGS__); \
1007 } while (0)
1008
1009 #ifndef FSYNC_METHOD_DEFAULT
1010 #ifdef __APPLE__
1011 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_WRITEOUT_ONLY
1012 #else
1013 #define FSYNC_METHOD_DEFAULT FSYNC_METHOD_FSYNC
1014 #endif
1015 #endif
1016
1017 #ifndef SHELL_PATH
1018 # define SHELL_PATH "/bin/sh"
1019 #endif
1020
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 */
1031 static inline int is_missing_file_error(int errno_)
1032 {
1033 return (errno_ == ENOENT || errno_ == ENOTDIR);
1034 }
1035
1036 int cmd_main(int, const char **);
1037
1038 /*
1039 * Intercept all calls to exit() and route them to trace2 to
1040 * optionally emit a message before calling the real exit().
1041 */
1042 int common_exit(const char *file, int line, int code);
1043 #define exit(code) exit(common_exit(__FILE__, __LINE__, (code)))
1044
1045 /*
1046 * This include must come after system headers, since it introduces macros that
1047 * replace system names.
1048 */
1049 #include "banned.h"
1050
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
1061 /*
1062 * helper function for `container_of_or_null' to avoid multiple
1063 * evaluation of @ptr
1064 */
1065 static 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
1076 /*
1077 * like offsetof(), but takes a pointer to a variable of type which
1078 * contains @member, instead of a specified type.
1079 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
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
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_)
1097 extern int false_but_the_compiler_does_not_know_it_;
1098
1099 #ifdef CHECK_ASSERTION_SIDE_EFFECTS
1100 #undef assert
1101 extern int not_supposed_to_survive;
1102 #define assert(expr) ((void)(not_supposed_to_survive || (expr)))
1103 #endif /* CHECK_ASSERTION_SIDE_EFFECTS */
1104
1105 #endif