]> git.ipfire.org Git - thirdparty/git.git/blob - git-compat-util.h
git-compat-util: undefine system names before redeclaring them
[thirdparty/git.git] / git-compat-util.h
1 #ifndef GIT_COMPAT_UTIL_H
2 #define GIT_COMPAT_UTIL_H
3
4 #ifdef USE_MSVC_CRTDBG
5 /*
6 * For these to work they must appear very early in each
7 * file -- before most of the standard header files.
8 */
9 #include <stdlib.h>
10 #include <crtdbg.h>
11 #endif
12
13 #define _FILE_OFFSET_BITS 64
14
15
16 /* Derived from Linux "Features Test Macro" header
17 * Convenience macros to test the versions of gcc (or
18 * a compatible compiler).
19 * Use them like this:
20 * #if GIT_GNUC_PREREQ (2,8)
21 * ... code requiring gcc 2.8 or later ...
22 * #endif
23 */
24 #if defined(__GNUC__) && defined(__GNUC_MINOR__)
25 # define GIT_GNUC_PREREQ(maj, min) \
26 ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
27 #else
28 #define GIT_GNUC_PREREQ(maj, min) 0
29 #endif
30
31
32 #ifndef FLEX_ARRAY
33 /*
34 * See if our compiler is known to support flexible array members.
35 */
36 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && (!defined(__SUNPRO_C) || (__SUNPRO_C > 0x580))
37 # define FLEX_ARRAY /* empty */
38 #elif defined(__GNUC__)
39 # if (__GNUC__ >= 3)
40 # define FLEX_ARRAY /* empty */
41 # else
42 # define FLEX_ARRAY 0 /* older GNU extension */
43 # endif
44 #endif
45
46 /*
47 * Otherwise, default to safer but a bit wasteful traditional style
48 */
49 #ifndef FLEX_ARRAY
50 # define FLEX_ARRAY 1
51 #endif
52 #endif
53
54
55 /*
56 * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
57 * @cond: the compile-time condition which must be true.
58 *
59 * Your compile will fail if the condition isn't true, or can't be evaluated
60 * by the compiler. This can be used in an expression: its value is "0".
61 *
62 * Example:
63 * #define foo_to_char(foo) \
64 * ((char *)(foo) \
65 * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
66 */
67 #define BUILD_ASSERT_OR_ZERO(cond) \
68 (sizeof(char [1 - 2*!(cond)]) - 1)
69
70 #if GIT_GNUC_PREREQ(3, 1)
71 /* &arr[0] degrades to a pointer: a different type from an array */
72 # define BARF_UNLESS_AN_ARRAY(arr) \
73 BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(__typeof__(arr), \
74 __typeof__(&(arr)[0])))
75 #else
76 # define BARF_UNLESS_AN_ARRAY(arr) 0
77 #endif
78 /*
79 * ARRAY_SIZE - get the number of elements in a visible array
80 * @x: the array whose size you want.
81 *
82 * This does not work on pointers, or arrays declared as [], or
83 * function parameters. With correct compiler support, such usage
84 * will cause a build error (see the build_assert_or_zero macro).
85 */
86 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
87
88 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
89
90 #define maximum_signed_value_of_type(a) \
91 (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
92
93 #define maximum_unsigned_value_of_type(a) \
94 (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
95
96 /*
97 * Signed integer overflow is undefined in C, so here's a helper macro
98 * to detect if the sum of two integers will overflow.
99 *
100 * Requires: a >= 0, typeof(a) equals typeof(b)
101 */
102 #define signed_add_overflows(a, b) \
103 ((b) > maximum_signed_value_of_type(a) - (a))
104
105 #define unsigned_add_overflows(a, b) \
106 ((b) > maximum_unsigned_value_of_type(a) - (a))
107
108 /*
109 * Returns true if the multiplication of "a" and "b" will
110 * overflow. The types of "a" and "b" must match and must be unsigned.
111 * Note that this macro evaluates "a" twice!
112 */
113 #define unsigned_mult_overflows(a, b) \
114 ((a) && (b) > maximum_unsigned_value_of_type(a) / (a))
115
116 #ifdef __GNUC__
117 #define TYPEOF(x) (__typeof__(x))
118 #else
119 #define TYPEOF(x)
120 #endif
121
122 #define MSB(x, bits) ((x) & TYPEOF(x)(~0ULL << (bitsizeof(x) - (bits))))
123 #define HAS_MULTI_BITS(i) ((i) & ((i) - 1)) /* checks if an integer has more than 1 bit set */
124
125 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
126
127 /* Approximation of the length of the decimal representation of this type. */
128 #define decimal_length(x) ((int)(sizeof(x) * 2.56 + 0.5) + 1)
129
130 #ifdef __MINGW64__
131 #define _POSIX_C_SOURCE 1
132 #elif defined(__sun__)
133 /*
134 * On Solaris, when _XOPEN_EXTENDED is set, its header file
135 * forces the programs to be XPG4v2, defeating any _XOPEN_SOURCE
136 * setting to say we are XPG5 or XPG6. Also on Solaris,
137 * XPG6 programs must be compiled with a c99 compiler, while
138 * non XPG6 programs must be compiled with a pre-c99 compiler.
139 */
140 # if __STDC_VERSION__ - 0 >= 199901L
141 # define _XOPEN_SOURCE 600
142 # else
143 # define _XOPEN_SOURCE 500
144 # endif
145 #elif !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__USLC__) && \
146 !defined(_M_UNIX) && !defined(__sgi) && !defined(__DragonFly__) && \
147 !defined(__TANDEM) && !defined(__QNX__) && !defined(__MirBSD__) && \
148 !defined(__CYGWIN__)
149 #define _XOPEN_SOURCE 600 /* glibc2 and AIX 5.3L need 500, OpenBSD needs 600 for S_ISLNK() */
150 #define _XOPEN_SOURCE_EXTENDED 1 /* AIX 5.3L needs this */
151 #endif
152 #define _ALL_SOURCE 1
153 #define _GNU_SOURCE 1
154 #define _BSD_SOURCE 1
155 #define _DEFAULT_SOURCE 1
156 #define _NETBSD_SOURCE 1
157 #define _SGI_SOURCE 1
158
159 #if defined(WIN32) && !defined(__CYGWIN__) /* Both MinGW and MSVC */
160 # if !defined(_WIN32_WINNT)
161 # define _WIN32_WINNT 0x0600
162 # endif
163 #define WIN32_LEAN_AND_MEAN /* stops windows.h including winsock.h */
164 #include <winsock2.h>
165 #include <windows.h>
166 #define GIT_WINDOWS_NATIVE
167 #endif
168
169 #include <unistd.h>
170 #include <stdio.h>
171 #include <sys/stat.h>
172 #include <fcntl.h>
173 #include <stddef.h>
174 #include <stdlib.h>
175 #include <stdarg.h>
176 #include <string.h>
177 #ifdef HAVE_STRINGS_H
178 #include <strings.h> /* for strcasecmp() */
179 #endif
180 #include <errno.h>
181 #include <limits.h>
182 #ifdef NEEDS_SYS_PARAM_H
183 #include <sys/param.h>
184 #endif
185 #include <sys/types.h>
186 #include <dirent.h>
187 #include <sys/time.h>
188 #include <time.h>
189 #include <signal.h>
190 #include <assert.h>
191 #include <regex.h>
192 #include <utime.h>
193 #include <syslog.h>
194 #if !defined(NO_POLL_H)
195 #include <poll.h>
196 #elif !defined(NO_SYS_POLL_H)
197 #include <sys/poll.h>
198 #else
199 /* Pull the compat stuff */
200 #include <poll.h>
201 #endif
202 #ifdef HAVE_BSD_SYSCTL
203 #include <sys/sysctl.h>
204 #endif
205
206 #if defined(__CYGWIN__)
207 #include "compat/win32/path-utils.h"
208 #endif
209 #if defined(__MINGW32__)
210 /* pull in Windows compatibility stuff */
211 #include "compat/win32/path-utils.h"
212 #include "compat/mingw.h"
213 #elif defined(_MSC_VER)
214 #include "compat/win32/path-utils.h"
215 #include "compat/msvc.h"
216 #else
217 #include <sys/utsname.h>
218 #include <sys/wait.h>
219 #include <sys/resource.h>
220 #include <sys/socket.h>
221 #include <sys/ioctl.h>
222 #include <termios.h>
223 #ifndef NO_SYS_SELECT_H
224 #include <sys/select.h>
225 #endif
226 #include <netinet/in.h>
227 #include <netinet/tcp.h>
228 #include <arpa/inet.h>
229 #include <netdb.h>
230 #include <pwd.h>
231 #include <sys/un.h>
232 #ifndef NO_INTTYPES_H
233 #include <inttypes.h>
234 #else
235 #include <stdint.h>
236 #endif
237 #ifdef NO_INTPTR_T
238 /*
239 * On I16LP32, ILP32 and LP64 "long" is the safe bet, however
240 * on LLP86, IL33LLP64 and P64 it needs to be "long long",
241 * while on IP16 and IP16L32 it is "int" (resp. "short")
242 * Size needs to match (or exceed) 'sizeof(void *)'.
243 * We can't take "long long" here as not everybody has it.
244 */
245 typedef long intptr_t;
246 typedef unsigned long uintptr_t;
247 #endif
248 #undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */
249 #include <grp.h>
250 #define _ALL_SOURCE 1
251 #endif
252
253 /* used on Mac OS X */
254 #ifdef PRECOMPOSE_UNICODE
255 #include "compat/precompose_utf8.h"
256 #else
257 static inline void precompose_argv(int argc, const char **argv)
258 {
259 ; /* nothing */
260 }
261 #define probe_utf8_pathname_composition()
262 #endif
263
264 #ifdef MKDIR_WO_TRAILING_SLASH
265 #define mkdir(a,b) compat_mkdir_wo_trailing_slash((a),(b))
266 int compat_mkdir_wo_trailing_slash(const char*, mode_t);
267 #endif
268
269 #ifdef NO_STRUCT_ITIMERVAL
270 struct itimerval {
271 struct timeval it_interval;
272 struct timeval it_value;
273 };
274 #endif
275
276 #ifdef NO_SETITIMER
277 static inline int git_setitimer(int which,
278 const struct itimerval *value,
279 struct itimerval *newvalue) {
280 return 0; /* pretend success */
281 }
282 #undef setitimer
283 #define setitimer(which,value,ovalue) git_setitimer(which,value,ovalue)
284 #endif
285
286 #ifndef NO_LIBGEN_H
287 #include <libgen.h>
288 #else
289 #define basename gitbasename
290 char *gitbasename(char *);
291 #define dirname gitdirname
292 char *gitdirname(char *);
293 #endif
294
295 #ifndef NO_ICONV
296 #include <iconv.h>
297 #endif
298
299 #ifndef NO_OPENSSL
300 #ifdef __APPLE__
301 #define __AVAILABILITY_MACROS_USES_AVAILABILITY 0
302 #include <AvailabilityMacros.h>
303 #undef DEPRECATED_ATTRIBUTE
304 #define DEPRECATED_ATTRIBUTE
305 #undef __AVAILABILITY_MACROS_USES_AVAILABILITY
306 #endif
307 #include <openssl/ssl.h>
308 #include <openssl/err.h>
309 #endif
310
311 #ifdef HAVE_SYSINFO
312 # include <sys/sysinfo.h>
313 #endif
314
315 /* On most systems <netdb.h> would have given us this, but
316 * not on some systems (e.g. z/OS).
317 */
318 #ifndef NI_MAXHOST
319 #define NI_MAXHOST 1025
320 #endif
321
322 #ifndef NI_MAXSERV
323 #define NI_MAXSERV 32
324 #endif
325
326 /* On most systems <limits.h> would have given us this, but
327 * not on some systems (e.g. GNU/Hurd).
328 */
329 #ifndef PATH_MAX
330 #define PATH_MAX 4096
331 #endif
332
333 typedef uintmax_t timestamp_t;
334 #define PRItime PRIuMAX
335 #define parse_timestamp strtoumax
336 #define TIME_MAX UINTMAX_MAX
337 #define TIME_MIN 0
338
339 #ifndef PATH_SEP
340 #define PATH_SEP ':'
341 #endif
342
343 #ifdef HAVE_PATHS_H
344 #include <paths.h>
345 #endif
346 #ifndef _PATH_DEFPATH
347 #define _PATH_DEFPATH "/usr/local/bin:/usr/bin:/bin"
348 #endif
349
350 #ifndef platform_core_config
351 static inline int noop_core_config(const char *var, const char *value, void *cb)
352 {
353 return 0;
354 }
355 #define platform_core_config noop_core_config
356 #endif
357
358 int lstat_cache_aware_rmdir(const char *path);
359 #if !defined(__MINGW32__) && !defined(_MSC_VER)
360 #define rmdir lstat_cache_aware_rmdir
361 #endif
362
363 #ifndef has_dos_drive_prefix
364 static inline int git_has_dos_drive_prefix(const char *path)
365 {
366 return 0;
367 }
368 #define has_dos_drive_prefix git_has_dos_drive_prefix
369 #endif
370
371 #ifndef skip_dos_drive_prefix
372 static inline int git_skip_dos_drive_prefix(char **path)
373 {
374 return 0;
375 }
376 #define skip_dos_drive_prefix git_skip_dos_drive_prefix
377 #endif
378
379 #ifndef is_dir_sep
380 static inline int git_is_dir_sep(int c)
381 {
382 return c == '/';
383 }
384 #define is_dir_sep git_is_dir_sep
385 #endif
386
387 #ifndef offset_1st_component
388 static inline int git_offset_1st_component(const char *path)
389 {
390 return is_dir_sep(path[0]);
391 }
392 #define offset_1st_component git_offset_1st_component
393 #endif
394
395 #ifndef is_valid_path
396 #define is_valid_path(path) 1
397 #endif
398
399 #ifndef is_path_owned_by_current_user
400
401 #ifdef __TANDEM
402 #define ROOT_UID 65535
403 #else
404 #define ROOT_UID 0
405 #endif
406
407 /*
408 * Do not use this function when
409 * (1) geteuid() did not say we are running as 'root', or
410 * (2) using this function will compromise the system.
411 *
412 * PORTABILITY WARNING:
413 * This code assumes uid_t is unsigned because that is what sudo does.
414 * If your uid_t type is signed and all your ids are positive then it
415 * should all work fine.
416 * If your version of sudo uses negative values for uid_t or it is
417 * buggy and return an overflowed value in SUDO_UID, then git might
418 * fail to grant access to your repository properly or even mistakenly
419 * grant access to someone else.
420 * In the unlikely scenario this happened to you, and that is how you
421 * got to this message, we would like to know about it; so sent us an
422 * email to git@vger.kernel.org indicating which platform you are
423 * using and which version of sudo, so we can improve this logic and
424 * maybe provide you with a patch that would prevent this issue again
425 * in the future.
426 */
427 static inline void extract_id_from_env(const char *env, uid_t *id)
428 {
429 const char *real_uid = getenv(env);
430
431 /* discard anything empty to avoid a more complex check below */
432 if (real_uid && *real_uid) {
433 char *endptr = NULL;
434 unsigned long env_id;
435
436 errno = 0;
437 /* silent overflow errors could trigger a bug here */
438 env_id = strtoul(real_uid, &endptr, 10);
439 if (!*endptr && !errno)
440 *id = env_id;
441 }
442 }
443
444 static inline int is_path_owned_by_current_uid(const char *path)
445 {
446 struct stat st;
447 uid_t euid;
448
449 if (lstat(path, &st))
450 return 0;
451
452 euid = geteuid();
453 if (euid == ROOT_UID)
454 {
455 if (st.st_uid == ROOT_UID)
456 return 1;
457 else
458 extract_id_from_env("SUDO_UID", &euid);
459 }
460
461 return st.st_uid == euid;
462 }
463
464 #define is_path_owned_by_current_user is_path_owned_by_current_uid
465 #endif
466
467 #ifndef find_last_dir_sep
468 static inline char *git_find_last_dir_sep(const char *path)
469 {
470 return strrchr(path, '/');
471 }
472 #define find_last_dir_sep git_find_last_dir_sep
473 #endif
474
475 #ifndef has_dir_sep
476 static inline int git_has_dir_sep(const char *path)
477 {
478 return !!strchr(path, '/');
479 }
480 #define has_dir_sep(path) git_has_dir_sep(path)
481 #endif
482
483 #ifndef query_user_email
484 #define query_user_email() NULL
485 #endif
486
487 #ifdef __TANDEM
488 #include <floss.h(floss_execl,floss_execlp,floss_execv,floss_execvp)>
489 #include <floss.h(floss_getpwuid)>
490 #ifndef NSIG
491 /*
492 * NonStop NSE and NSX do not provide NSIG. SIGGUARDIAN(99) is the highest
493 * known, by detective work using kill -l as a list is all signals
494 * instead of signal.h where it should be.
495 */
496 # define NSIG 100
497 #endif
498 #endif
499
500 #if defined(__HP_cc) && (__HP_cc >= 61000)
501 #define NORETURN __attribute__((noreturn))
502 #define NORETURN_PTR
503 #elif defined(__GNUC__) && !defined(NO_NORETURN)
504 #define NORETURN __attribute__((__noreturn__))
505 #define NORETURN_PTR __attribute__((__noreturn__))
506 #elif defined(_MSC_VER)
507 #define NORETURN __declspec(noreturn)
508 #define NORETURN_PTR
509 #else
510 #define NORETURN
511 #define NORETURN_PTR
512 #ifndef __GNUC__
513 #ifndef __attribute__
514 #define __attribute__(x)
515 #endif
516 #endif
517 #endif
518
519 /* The sentinel attribute is valid from gcc version 4.0 */
520 #if defined(__GNUC__) && (__GNUC__ >= 4)
521 #define LAST_ARG_MUST_BE_NULL __attribute__((sentinel))
522 #else
523 #define LAST_ARG_MUST_BE_NULL
524 #endif
525
526 #define MAYBE_UNUSED __attribute__((__unused__))
527
528 #include "compat/bswap.h"
529
530 #include "wildmatch.h"
531
532 struct strbuf;
533
534 /* General helper functions */
535 void vreportf(const char *prefix, const char *err, va_list params);
536 NORETURN void usage(const char *err);
537 NORETURN void usagef(const char *err, ...) __attribute__((format (printf, 1, 2)));
538 NORETURN void die(const char *err, ...) __attribute__((format (printf, 1, 2)));
539 NORETURN void die_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
540 int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
541 int error_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
542 void warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
543 void warning_errno(const char *err, ...) __attribute__((format (printf, 1, 2)));
544
545 #ifndef NO_OPENSSL
546 #ifdef APPLE_COMMON_CRYPTO
547 #include "compat/apple-common-crypto.h"
548 #else
549 #include <openssl/evp.h>
550 #include <openssl/hmac.h>
551 #endif /* APPLE_COMMON_CRYPTO */
552 #include <openssl/x509v3.h>
553 #endif /* NO_OPENSSL */
554
555 /*
556 * Let callers be aware of the constant return value; this can help
557 * gcc with -Wuninitialized analysis. We restrict this trick to gcc, though,
558 * because some compilers may not support variadic macros. Since we're only
559 * trying to help gcc, anyway, it's OK; other compilers will fall back to
560 * using the function as usual.
561 */
562 #if defined(__GNUC__)
563 static inline int const_error(void)
564 {
565 return -1;
566 }
567 #define error(...) (error(__VA_ARGS__), const_error())
568 #define error_errno(...) (error_errno(__VA_ARGS__), const_error())
569 #endif
570
571 typedef void (*report_fn)(const char *, va_list params);
572
573 void set_die_routine(NORETURN_PTR report_fn routine);
574 void set_error_routine(report_fn routine);
575 report_fn get_error_routine(void);
576 void set_warn_routine(report_fn routine);
577 report_fn get_warn_routine(void);
578 void set_die_is_recursing_routine(int (*routine)(void));
579
580 int starts_with(const char *str, const char *prefix);
581 int istarts_with(const char *str, const char *prefix);
582
583 /*
584 * If the string "str" begins with the string found in "prefix", return 1.
585 * The "out" parameter is set to "str + strlen(prefix)" (i.e., to the point in
586 * the string right after the prefix).
587 *
588 * Otherwise, return 0 and leave "out" untouched.
589 *
590 * Examples:
591 *
592 * [extract branch name, fail if not a branch]
593 * if (!skip_prefix(ref, "refs/heads/", &branch)
594 * return -1;
595 *
596 * [skip prefix if present, otherwise use whole string]
597 * skip_prefix(name, "refs/heads/", &name);
598 */
599 static inline int skip_prefix(const char *str, const char *prefix,
600 const char **out)
601 {
602 do {
603 if (!*prefix) {
604 *out = str;
605 return 1;
606 }
607 } while (*str++ == *prefix++);
608 return 0;
609 }
610
611 /*
612 * If the string "str" is the same as the string in "prefix", then the "arg"
613 * parameter is set to the "def" parameter and 1 is returned.
614 * If the string "str" begins with the string found in "prefix" and then a
615 * "=" sign, then the "arg" parameter is set to "str + strlen(prefix) + 1"
616 * (i.e., to the point in the string right after the prefix and the "=" sign),
617 * and 1 is returned.
618 *
619 * Otherwise, return 0 and leave "arg" untouched.
620 *
621 * When we accept both a "--key" and a "--key=<val>" option, this function
622 * can be used instead of !strcmp(arg, "--key") and then
623 * skip_prefix(arg, "--key=", &arg) to parse such an option.
624 */
625 int skip_to_optional_arg_default(const char *str, const char *prefix,
626 const char **arg, const char *def);
627
628 static inline int skip_to_optional_arg(const char *str, const char *prefix,
629 const char **arg)
630 {
631 return skip_to_optional_arg_default(str, prefix, arg, "");
632 }
633
634 /*
635 * Like skip_prefix, but promises never to read past "len" bytes of the input
636 * buffer, and returns the remaining number of bytes in "out" via "outlen".
637 */
638 static inline int skip_prefix_mem(const char *buf, size_t len,
639 const char *prefix,
640 const char **out, size_t *outlen)
641 {
642 size_t prefix_len = strlen(prefix);
643 if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
644 *out = buf + prefix_len;
645 *outlen = len - prefix_len;
646 return 1;
647 }
648 return 0;
649 }
650
651 /*
652 * If buf ends with suffix, return 1 and subtract the length of the suffix
653 * from *len. Otherwise, return 0 and leave *len untouched.
654 */
655 static inline int strip_suffix_mem(const char *buf, size_t *len,
656 const char *suffix)
657 {
658 size_t suflen = strlen(suffix);
659 if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
660 return 0;
661 *len -= suflen;
662 return 1;
663 }
664
665 /*
666 * If str ends with suffix, return 1 and set *len to the size of the string
667 * without the suffix. Otherwise, return 0 and set *len to the size of the
668 * string.
669 *
670 * Note that we do _not_ NUL-terminate str to the new length.
671 */
672 static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
673 {
674 *len = strlen(str);
675 return strip_suffix_mem(str, len, suffix);
676 }
677
678 static inline int ends_with(const char *str, const char *suffix)
679 {
680 size_t len;
681 return strip_suffix(str, suffix, &len);
682 }
683
684 #define SWAP(a, b) do { \
685 void *_swap_a_ptr = &(a); \
686 void *_swap_b_ptr = &(b); \
687 unsigned char _swap_buffer[sizeof(a)]; \
688 memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
689 memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
690 BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
691 memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
692 } while (0)
693
694 #if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
695
696 #ifndef PROT_READ
697 #define PROT_READ 1
698 #define PROT_WRITE 2
699 #define MAP_PRIVATE 1
700 #endif
701
702 #define mmap git_mmap
703 #define munmap git_munmap
704 void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
705 int git_munmap(void *start, size_t length);
706
707 #else /* NO_MMAP || USE_WIN32_MMAP */
708
709 #include <sys/mman.h>
710
711 #endif /* NO_MMAP || USE_WIN32_MMAP */
712
713 #ifdef NO_MMAP
714
715 /* This value must be multiple of (pagesize * 2) */
716 #define DEFAULT_PACKED_GIT_WINDOW_SIZE (1 * 1024 * 1024)
717
718 #else /* NO_MMAP */
719
720 /* This value must be multiple of (pagesize * 2) */
721 #define DEFAULT_PACKED_GIT_WINDOW_SIZE \
722 (sizeof(void*) >= 8 \
723 ? 1 * 1024 * 1024 * 1024 \
724 : 32 * 1024 * 1024)
725
726 #endif /* NO_MMAP */
727
728 #ifndef MAP_FAILED
729 #define MAP_FAILED ((void *)-1)
730 #endif
731
732 #ifdef NO_ST_BLOCKS_IN_STRUCT_STAT
733 #define on_disk_bytes(st) ((st).st_size)
734 #else
735 #define on_disk_bytes(st) ((st).st_blocks * 512)
736 #endif
737
738 #ifdef NEEDS_MODE_TRANSLATION
739 #undef S_IFMT
740 #undef S_IFREG
741 #undef S_IFDIR
742 #undef S_IFLNK
743 #undef S_IFBLK
744 #undef S_IFCHR
745 #undef S_IFIFO
746 #undef S_IFSOCK
747 #define S_IFMT 0170000
748 #define S_IFREG 0100000
749 #define S_IFDIR 0040000
750 #define S_IFLNK 0120000
751 #define S_IFBLK 0060000
752 #define S_IFCHR 0020000
753 #define S_IFIFO 0010000
754 #define S_IFSOCK 0140000
755 #ifdef stat
756 #undef stat
757 #endif
758 #define stat(path, buf) git_stat(path, buf)
759 int git_stat(const char *, struct stat *);
760 #ifdef fstat
761 #undef fstat
762 #endif
763 #define fstat(fd, buf) git_fstat(fd, buf)
764 int git_fstat(int, struct stat *);
765 #ifdef lstat
766 #undef lstat
767 #endif
768 #define lstat(path, buf) git_lstat(path, buf)
769 int git_lstat(const char *, struct stat *);
770 #endif
771
772 #define DEFAULT_PACKED_GIT_LIMIT \
773 ((1024L * 1024L) * (size_t)(sizeof(void*) >= 8 ? (32 * 1024L * 1024L) : 256))
774
775 #ifdef NO_PREAD
776 #define pread git_pread
777 ssize_t git_pread(int fd, void *buf, size_t count, off_t offset);
778 #endif
779 /*
780 * Forward decl that will remind us if its twin in cache.h changes.
781 * This function is used in compat/pread.c. But we can't include
782 * cache.h there.
783 */
784 ssize_t read_in_full(int fd, void *buf, size_t count);
785
786 #ifdef NO_SETENV
787 #define setenv gitsetenv
788 int gitsetenv(const char *, const char *, int);
789 #endif
790
791 #ifdef NO_MKDTEMP
792 #define mkdtemp gitmkdtemp
793 char *gitmkdtemp(char *);
794 #endif
795
796 #ifdef NO_UNSETENV
797 #define unsetenv gitunsetenv
798 void gitunsetenv(const char *);
799 #endif
800
801 #ifdef NO_STRCASESTR
802 #define strcasestr gitstrcasestr
803 char *gitstrcasestr(const char *haystack, const char *needle);
804 #endif
805
806 #ifdef NO_STRLCPY
807 #define strlcpy gitstrlcpy
808 size_t gitstrlcpy(char *, const char *, size_t);
809 #endif
810
811 #ifdef NO_STRTOUMAX
812 #define strtoumax gitstrtoumax
813 uintmax_t gitstrtoumax(const char *, char **, int);
814 #define strtoimax gitstrtoimax
815 intmax_t gitstrtoimax(const char *, char **, int);
816 #endif
817
818 #ifdef NO_HSTRERROR
819 #define hstrerror githstrerror
820 const char *githstrerror(int herror);
821 #endif
822
823 #ifdef NO_MEMMEM
824 #define memmem gitmemmem
825 void *gitmemmem(const void *haystack, size_t haystacklen,
826 const void *needle, size_t needlelen);
827 #endif
828
829 #ifdef OVERRIDE_STRDUP
830 #ifdef strdup
831 #undef strdup
832 #endif
833 #define strdup gitstrdup
834 char *gitstrdup(const char *s);
835 #endif
836
837 #ifdef NO_GETPAGESIZE
838 #define getpagesize() sysconf(_SC_PAGESIZE)
839 #endif
840
841 #ifndef O_CLOEXEC
842 #define O_CLOEXEC 0
843 #endif
844
845 #ifdef FREAD_READS_DIRECTORIES
846 # if !defined(SUPPRESS_FOPEN_REDEFINITION)
847 # ifdef fopen
848 # undef fopen
849 # endif
850 # define fopen(a,b) git_fopen(a,b)
851 # endif
852 FILE *git_fopen(const char*, const char*);
853 #endif
854
855 #ifdef SNPRINTF_RETURNS_BOGUS
856 #ifdef snprintf
857 #undef snprintf
858 #endif
859 #define snprintf git_snprintf
860 int git_snprintf(char *str, size_t maxsize,
861 const char *format, ...);
862 #ifdef vsnprintf
863 #undef vsnprintf
864 #endif
865 #define vsnprintf git_vsnprintf
866 int git_vsnprintf(char *str, size_t maxsize,
867 const char *format, va_list ap);
868 #endif
869
870 #ifdef __GLIBC_PREREQ
871 #if __GLIBC_PREREQ(2, 1)
872 #define HAVE_STRCHRNUL
873 #endif
874 #endif
875
876 #ifndef HAVE_STRCHRNUL
877 #define strchrnul gitstrchrnul
878 static inline char *gitstrchrnul(const char *s, int c)
879 {
880 while (*s && *s != c)
881 s++;
882 return (char *)s;
883 }
884 #endif
885
886 #ifdef NO_INET_PTON
887 int inet_pton(int af, const char *src, void *dst);
888 #endif
889
890 #ifdef NO_INET_NTOP
891 const char *inet_ntop(int af, const void *src, char *dst, size_t size);
892 #endif
893
894 #ifdef NO_PTHREADS
895 #define atexit git_atexit
896 int git_atexit(void (*handler)(void));
897 #endif
898
899 static inline size_t st_add(size_t a, size_t b)
900 {
901 if (unsigned_add_overflows(a, b))
902 die("size_t overflow: %"PRIuMAX" + %"PRIuMAX,
903 (uintmax_t)a, (uintmax_t)b);
904 return a + b;
905 }
906 #define st_add3(a,b,c) st_add(st_add((a),(b)),(c))
907 #define st_add4(a,b,c,d) st_add(st_add3((a),(b),(c)),(d))
908
909 static inline size_t st_mult(size_t a, size_t b)
910 {
911 if (unsigned_mult_overflows(a, b))
912 die("size_t overflow: %"PRIuMAX" * %"PRIuMAX,
913 (uintmax_t)a, (uintmax_t)b);
914 return a * b;
915 }
916
917 static inline size_t st_sub(size_t a, size_t b)
918 {
919 if (a < b)
920 die("size_t underflow: %"PRIuMAX" - %"PRIuMAX,
921 (uintmax_t)a, (uintmax_t)b);
922 return a - b;
923 }
924
925 #ifdef HAVE_ALLOCA_H
926 # include <alloca.h>
927 # define xalloca(size) (alloca(size))
928 # define xalloca_free(p) do {} while (0)
929 #else
930 # define xalloca(size) (xmalloc(size))
931 # define xalloca_free(p) (free(p))
932 #endif
933 char *xstrdup(const char *str);
934 void *xmalloc(size_t size);
935 void *xmallocz(size_t size);
936 void *xmallocz_gently(size_t size);
937 void *xmemdupz(const void *data, size_t len);
938 char *xstrndup(const char *str, size_t len);
939 void *xrealloc(void *ptr, size_t size);
940 void *xcalloc(size_t nmemb, size_t size);
941 void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
942 void *xmmap_gently(void *start, size_t length, int prot, int flags, int fd, off_t offset);
943 int xopen(const char *path, int flags, ...);
944 ssize_t xread(int fd, void *buf, size_t len);
945 ssize_t xwrite(int fd, const void *buf, size_t len);
946 ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
947 int xdup(int fd);
948 FILE *xfopen(const char *path, const char *mode);
949 FILE *xfdopen(int fd, const char *mode);
950 int xmkstemp(char *temp_filename);
951 int xmkstemp_mode(char *temp_filename, int mode);
952 char *xgetcwd(void);
953 FILE *fopen_for_writing(const char *path);
954 FILE *fopen_or_warn(const char *path, const char *mode);
955
956 /*
957 * Like strncmp, but only return zero if s is NUL-terminated and exactly len
958 * characters long. If it is not, consider it greater than t.
959 */
960 int xstrncmpz(const char *s, const char *t, size_t len);
961
962 /*
963 * FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
964 * that ptr is used twice, so don't pass e.g. ptr++.
965 */
966 #define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
967
968 #define ALLOC_ARRAY(x, alloc) (x) = xmalloc(st_mult(sizeof(*(x)), (alloc)))
969 #define CALLOC_ARRAY(x, alloc) (x) = xcalloc((alloc), sizeof(*(x)));
970 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), st_mult(sizeof(*(x)), (alloc)))
971
972 #define COPY_ARRAY(dst, src, n) copy_array((dst), (src), (n), sizeof(*(dst)) + \
973 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
974 static inline void copy_array(void *dst, const void *src, size_t n, size_t size)
975 {
976 if (n)
977 memcpy(dst, src, st_mult(size, n));
978 }
979
980 #define MOVE_ARRAY(dst, src, n) move_array((dst), (src), (n), sizeof(*(dst)) + \
981 BUILD_ASSERT_OR_ZERO(sizeof(*(dst)) == sizeof(*(src))))
982 static inline void move_array(void *dst, const void *src, size_t n, size_t size)
983 {
984 if (n)
985 memmove(dst, src, st_mult(size, n));
986 }
987
988 /*
989 * These functions help you allocate structs with flex arrays, and copy
990 * the data directly into the array. For example, if you had:
991 *
992 * struct foo {
993 * int bar;
994 * char name[FLEX_ARRAY];
995 * };
996 *
997 * you can do:
998 *
999 * struct foo *f;
1000 * FLEX_ALLOC_MEM(f, name, src, len);
1001 *
1002 * to allocate a "foo" with the contents of "src" in the "name" field.
1003 * The resulting struct is automatically zero'd, and the flex-array field
1004 * is NUL-terminated (whether the incoming src buffer was or not).
1005 *
1006 * The FLEXPTR_* variants operate on structs that don't use flex-arrays,
1007 * but do want to store a pointer to some extra data in the same allocated
1008 * block. For example, if you have:
1009 *
1010 * struct foo {
1011 * char *name;
1012 * int bar;
1013 * };
1014 *
1015 * you can do:
1016 *
1017 * struct foo *f;
1018 * FLEXPTR_ALLOC_STR(f, name, src);
1019 *
1020 * and "name" will point to a block of memory after the struct, which will be
1021 * freed along with the struct (but the pointer can be repointed anywhere).
1022 *
1023 * The *_STR variants accept a string parameter rather than a ptr/len
1024 * combination.
1025 *
1026 * Note that these macros will evaluate the first parameter multiple
1027 * times, and it must be assignable as an lvalue.
1028 */
1029 #define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
1030 size_t flex_array_len_ = (len); \
1031 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1032 memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
1033 } while (0)
1034 #define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
1035 size_t flex_array_len_ = (len); \
1036 (x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
1037 memcpy((x) + 1, (buf), flex_array_len_); \
1038 (x)->ptrname = (void *)((x)+1); \
1039 } while(0)
1040 #define FLEX_ALLOC_STR(x, flexname, str) \
1041 FLEX_ALLOC_MEM((x), flexname, (str), strlen(str))
1042 #define FLEXPTR_ALLOC_STR(x, ptrname, str) \
1043 FLEXPTR_ALLOC_MEM((x), ptrname, (str), strlen(str))
1044
1045 static inline char *xstrdup_or_null(const char *str)
1046 {
1047 return str ? xstrdup(str) : NULL;
1048 }
1049
1050 static inline size_t xsize_t(off_t len)
1051 {
1052 size_t size = (size_t) len;
1053
1054 if (len != (off_t) size)
1055 die("Cannot handle files this big");
1056 return size;
1057 }
1058
1059 __attribute__((format (printf, 3, 4)))
1060 int xsnprintf(char *dst, size_t max, const char *fmt, ...);
1061
1062 #ifndef HOST_NAME_MAX
1063 #define HOST_NAME_MAX 256
1064 #endif
1065
1066 int xgethostname(char *buf, size_t len);
1067
1068 /* in ctype.c, for kwset users */
1069 extern const unsigned char tolower_trans_tbl[256];
1070
1071 /* Sane ctype - no locale, and works with signed chars */
1072 #undef isascii
1073 #undef isspace
1074 #undef isdigit
1075 #undef isalpha
1076 #undef isalnum
1077 #undef isprint
1078 #undef islower
1079 #undef isupper
1080 #undef tolower
1081 #undef toupper
1082 #undef iscntrl
1083 #undef ispunct
1084 #undef isxdigit
1085
1086 extern const unsigned char sane_ctype[256];
1087 #define GIT_SPACE 0x01
1088 #define GIT_DIGIT 0x02
1089 #define GIT_ALPHA 0x04
1090 #define GIT_GLOB_SPECIAL 0x08
1091 #define GIT_REGEX_SPECIAL 0x10
1092 #define GIT_PATHSPEC_MAGIC 0x20
1093 #define GIT_CNTRL 0x40
1094 #define GIT_PUNCT 0x80
1095 #define sane_istest(x,mask) ((sane_ctype[(unsigned char)(x)] & (mask)) != 0)
1096 #define isascii(x) (((x) & ~0x7f) == 0)
1097 #define isspace(x) sane_istest(x,GIT_SPACE)
1098 #define isdigit(x) sane_istest(x,GIT_DIGIT)
1099 #define isalpha(x) sane_istest(x,GIT_ALPHA)
1100 #define isalnum(x) sane_istest(x,GIT_ALPHA | GIT_DIGIT)
1101 #define isprint(x) ((x) >= 0x20 && (x) <= 0x7e)
1102 #define islower(x) sane_iscase(x, 1)
1103 #define isupper(x) sane_iscase(x, 0)
1104 #define is_glob_special(x) sane_istest(x,GIT_GLOB_SPECIAL)
1105 #define is_regex_special(x) sane_istest(x,GIT_GLOB_SPECIAL | GIT_REGEX_SPECIAL)
1106 #define iscntrl(x) (sane_istest(x,GIT_CNTRL))
1107 #define ispunct(x) sane_istest(x, GIT_PUNCT | GIT_REGEX_SPECIAL | \
1108 GIT_GLOB_SPECIAL | GIT_PATHSPEC_MAGIC)
1109 #define isxdigit(x) (hexval_table[(unsigned char)(x)] != -1)
1110 #define tolower(x) sane_case((unsigned char)(x), 0x20)
1111 #define toupper(x) sane_case((unsigned char)(x), 0)
1112 #define is_pathspec_magic(x) sane_istest(x,GIT_PATHSPEC_MAGIC)
1113
1114 static inline int sane_case(int x, int high)
1115 {
1116 if (sane_istest(x, GIT_ALPHA))
1117 x = (x & ~0x20) | high;
1118 return x;
1119 }
1120
1121 static inline int sane_iscase(int x, int is_lower)
1122 {
1123 if (!sane_istest(x, GIT_ALPHA))
1124 return 0;
1125
1126 if (is_lower)
1127 return (x & 0x20) != 0;
1128 else
1129 return (x & 0x20) == 0;
1130 }
1131
1132 /*
1133 * Like skip_prefix, but compare case-insensitively. Note that the comparison
1134 * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
1135 * locale-specific conversions).
1136 */
1137 static inline int skip_iprefix(const char *str, const char *prefix,
1138 const char **out)
1139 {
1140 do {
1141 if (!*prefix) {
1142 *out = str;
1143 return 1;
1144 }
1145 } while (tolower(*str++) == tolower(*prefix++));
1146 return 0;
1147 }
1148
1149 static inline int strtoul_ui(char const *s, int base, unsigned int *result)
1150 {
1151 unsigned long ul;
1152 char *p;
1153
1154 errno = 0;
1155 /* negative values would be accepted by strtoul */
1156 if (strchr(s, '-'))
1157 return -1;
1158 ul = strtoul(s, &p, base);
1159 if (errno || *p || p == s || (unsigned int) ul != ul)
1160 return -1;
1161 *result = ul;
1162 return 0;
1163 }
1164
1165 static inline int strtol_i(char const *s, int base, int *result)
1166 {
1167 long ul;
1168 char *p;
1169
1170 errno = 0;
1171 ul = strtol(s, &p, base);
1172 if (errno || *p || p == s || (int) ul != ul)
1173 return -1;
1174 *result = ul;
1175 return 0;
1176 }
1177
1178 void git_stable_qsort(void *base, size_t nmemb, size_t size,
1179 int(*compar)(const void *, const void *));
1180 #ifdef INTERNAL_QSORT
1181 #define qsort git_stable_qsort
1182 #endif
1183
1184 #define QSORT(base, n, compar) sane_qsort((base), (n), sizeof(*(base)), compar)
1185 static inline void sane_qsort(void *base, size_t nmemb, size_t size,
1186 int(*compar)(const void *, const void *))
1187 {
1188 if (nmemb > 1)
1189 qsort(base, nmemb, size, compar);
1190 }
1191
1192 #define STABLE_QSORT(base, n, compar) \
1193 git_stable_qsort((base), (n), sizeof(*(base)), compar)
1194
1195 #ifndef HAVE_ISO_QSORT_S
1196 int git_qsort_s(void *base, size_t nmemb, size_t size,
1197 int (*compar)(const void *, const void *, void *), void *ctx);
1198 #define qsort_s git_qsort_s
1199 #endif
1200
1201 #define QSORT_S(base, n, compar, ctx) do { \
1202 if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
1203 BUG("qsort_s() failed"); \
1204 } while (0)
1205
1206 #ifndef REG_STARTEND
1207 #error "Git requires REG_STARTEND support. Compile with NO_REGEX=NeedsStartEnd"
1208 #endif
1209
1210 static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
1211 size_t nmatch, regmatch_t pmatch[], int eflags)
1212 {
1213 assert(nmatch > 0 && pmatch);
1214 pmatch[0].rm_so = 0;
1215 pmatch[0].rm_eo = size;
1216 return regexec(preg, buf, nmatch, pmatch, eflags | REG_STARTEND);
1217 }
1218
1219 #ifndef DIR_HAS_BSD_GROUP_SEMANTICS
1220 # define FORCE_DIR_SET_GID S_ISGID
1221 #else
1222 # define FORCE_DIR_SET_GID 0
1223 #endif
1224
1225 #ifdef NO_NSEC
1226 #undef USE_NSEC
1227 #define ST_CTIME_NSEC(st) 0
1228 #define ST_MTIME_NSEC(st) 0
1229 #else
1230 #ifdef USE_ST_TIMESPEC
1231 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctimespec.tv_nsec))
1232 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtimespec.tv_nsec))
1233 #else
1234 #define ST_CTIME_NSEC(st) ((unsigned int)((st).st_ctim.tv_nsec))
1235 #define ST_MTIME_NSEC(st) ((unsigned int)((st).st_mtim.tv_nsec))
1236 #endif
1237 #endif
1238
1239 #ifdef UNRELIABLE_FSTAT
1240 #define fstat_is_reliable() 0
1241 #else
1242 #define fstat_is_reliable() 1
1243 #endif
1244
1245 #ifndef va_copy
1246 /*
1247 * Since an obvious implementation of va_list would be to make it a
1248 * pointer into the stack frame, a simple assignment will work on
1249 * many systems. But let's try to be more portable.
1250 */
1251 #ifdef __va_copy
1252 #define va_copy(dst, src) __va_copy(dst, src)
1253 #else
1254 #define va_copy(dst, src) ((dst) = (src))
1255 #endif
1256 #endif
1257
1258 #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__C99_MACRO_WITH_VA_ARGS)
1259 #define HAVE_VARIADIC_MACROS 1
1260 #endif
1261
1262 /* usage.c: only to be used for testing BUG() implementation (see test-tool) */
1263 extern int BUG_exit_code;
1264
1265 #ifdef HAVE_VARIADIC_MACROS
1266 __attribute__((format (printf, 3, 4))) NORETURN
1267 void BUG_fl(const char *file, int line, const char *fmt, ...);
1268 #define BUG(...) BUG_fl(__FILE__, __LINE__, __VA_ARGS__)
1269 #else
1270 __attribute__((format (printf, 1, 2))) NORETURN
1271 void BUG(const char *fmt, ...);
1272 #endif
1273
1274 /*
1275 * Preserves errno, prints a message, but gives no warning for ENOENT.
1276 * Returns 0 on success, which includes trying to unlink an object that does
1277 * not exist.
1278 */
1279 int unlink_or_warn(const char *path);
1280 /*
1281 * Tries to unlink file. Returns 0 if unlink succeeded
1282 * or the file already didn't exist. Returns -1 and
1283 * appends a message to err suitable for
1284 * 'error("%s", err->buf)' on error.
1285 */
1286 int unlink_or_msg(const char *file, struct strbuf *err);
1287 /*
1288 * Preserves errno, prints a message, but gives no warning for ENOENT.
1289 * Returns 0 on success, which includes trying to remove a directory that does
1290 * not exist.
1291 */
1292 int rmdir_or_warn(const char *path);
1293 /*
1294 * Calls the correct function out of {unlink,rmdir}_or_warn based on
1295 * the supplied file mode.
1296 */
1297 int remove_or_warn(unsigned int mode, const char *path);
1298
1299 /*
1300 * Call access(2), but warn for any error except "missing file"
1301 * (ENOENT or ENOTDIR).
1302 */
1303 #define ACCESS_EACCES_OK (1U << 0)
1304 int access_or_warn(const char *path, int mode, unsigned flag);
1305 int access_or_die(const char *path, int mode, unsigned flag);
1306
1307 /* Warn on an inaccessible file if errno indicates this is an error */
1308 int warn_on_fopen_errors(const char *path);
1309
1310 #if !defined(USE_PARENS_AROUND_GETTEXT_N) && defined(__GNUC__)
1311 #define USE_PARENS_AROUND_GETTEXT_N 1
1312 #endif
1313
1314 #ifndef SHELL_PATH
1315 # define SHELL_PATH "/bin/sh"
1316 #endif
1317
1318 #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
1319 static inline void git_flockfile(FILE *fh)
1320 {
1321 ; /* nothing */
1322 }
1323 static inline void git_funlockfile(FILE *fh)
1324 {
1325 ; /* nothing */
1326 }
1327 #undef flockfile
1328 #undef funlockfile
1329 #undef getc_unlocked
1330 #define flockfile(fh) git_flockfile(fh)
1331 #define funlockfile(fh) git_funlockfile(fh)
1332 #define getc_unlocked(fh) getc(fh)
1333 #endif
1334
1335 #ifdef FILENO_IS_A_MACRO
1336 int git_fileno(FILE *stream);
1337 # ifndef COMPAT_CODE_FILENO
1338 # undef fileno
1339 # define fileno(p) git_fileno(p)
1340 # endif
1341 #endif
1342
1343 #ifdef NEED_ACCESS_ROOT_HANDLER
1344 int git_access(const char *path, int mode);
1345 # ifndef COMPAT_CODE_ACCESS
1346 # ifdef access
1347 # undef access
1348 # endif
1349 # define access(path, mode) git_access(path, mode)
1350 # endif
1351 #endif
1352
1353 /*
1354 * Our code often opens a path to an optional file, to work on its
1355 * contents when we can successfully open it. We can ignore a failure
1356 * to open if such an optional file does not exist, but we do want to
1357 * report a failure in opening for other reasons (e.g. we got an I/O
1358 * error, or the file is there, but we lack the permission to open).
1359 *
1360 * Call this function after seeing an error from open() or fopen() to
1361 * see if the errno indicates a missing file that we can safely ignore.
1362 */
1363 static inline int is_missing_file_error(int errno_)
1364 {
1365 return (errno_ == ENOENT || errno_ == ENOTDIR);
1366 }
1367
1368 int cmd_main(int, const char **);
1369
1370 /*
1371 * Intercept all calls to exit() and route them to trace2 to
1372 * optionally emit a message before calling the real exit().
1373 */
1374 int trace2_cmd_exit_fl(const char *file, int line, int code);
1375 #define exit(code) exit(trace2_cmd_exit_fl(__FILE__, __LINE__, (code)))
1376
1377 /*
1378 * You can mark a stack variable with UNLEAK(var) to avoid it being
1379 * reported as a leak by tools like LSAN or valgrind. The argument
1380 * should generally be the variable itself (not its address and not what
1381 * it points to). It's safe to use this on pointers which may already
1382 * have been freed, or on pointers which may still be in use.
1383 *
1384 * Use this _only_ for a variable that leaks by going out of scope at
1385 * program exit (so only from cmd_* functions or their direct helpers).
1386 * Normal functions, especially those which may be called multiple
1387 * times, should actually free their memory. This is only meant as
1388 * an annotation, and does nothing in non-leak-checking builds.
1389 */
1390 #ifdef SUPPRESS_ANNOTATED_LEAKS
1391 void unleak_memory(const void *ptr, size_t len);
1392 #define UNLEAK(var) unleak_memory(&(var), sizeof(var))
1393 #else
1394 #define UNLEAK(var) do {} while (0)
1395 #endif
1396
1397 /*
1398 * This include must come after system headers, since it introduces macros that
1399 * replace system names.
1400 */
1401 #include "banned.h"
1402
1403 /*
1404 * container_of - Get the address of an object containing a field.
1405 *
1406 * @ptr: pointer to the field.
1407 * @type: type of the object.
1408 * @member: name of the field within the object.
1409 */
1410 #define container_of(ptr, type, member) \
1411 ((type *) ((char *)(ptr) - offsetof(type, member)))
1412
1413 /*
1414 * helper function for `container_of_or_null' to avoid multiple
1415 * evaluation of @ptr
1416 */
1417 static inline void *container_of_or_null_offset(void *ptr, size_t offset)
1418 {
1419 return ptr ? (char *)ptr - offset : NULL;
1420 }
1421
1422 /*
1423 * like `container_of', but allows returned value to be NULL
1424 */
1425 #define container_of_or_null(ptr, type, member) \
1426 (type *)container_of_or_null_offset(ptr, offsetof(type, member))
1427
1428 /*
1429 * like offsetof(), but takes a pointer to a a variable of type which
1430 * contains @member, instead of a specified type.
1431 * @ptr is subject to multiple evaluation since we can't rely on __typeof__
1432 * everywhere.
1433 */
1434 #if defined(__GNUC__) /* clang sets this, too */
1435 #define OFFSETOF_VAR(ptr, member) offsetof(__typeof__(*ptr), member)
1436 #else /* !__GNUC__ */
1437 #define OFFSETOF_VAR(ptr, member) \
1438 ((uintptr_t)&(ptr)->member - (uintptr_t)(ptr))
1439 #endif /* !__GNUC__ */
1440
1441 void sleep_millisec(int millisec);
1442
1443 #endif