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