THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1355 lines
36KB

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