wrapper.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. /*
  2. * Various trivial helper wrappers around standard functions
  3. */
  4. #include "cache.h"
  5. #include "config.h"
  6. static int memory_limit_check(size_t size, int gentle)
  7. {
  8. static size_t limit = 0;
  9. if (!limit) {
  10. limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
  11. if (!limit)
  12. limit = SIZE_MAX;
  13. }
  14. if (size > limit) {
  15. if (gentle) {
  16. error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
  17. (uintmax_t)size, (uintmax_t)limit);
  18. return -1;
  19. } else
  20. die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
  21. (uintmax_t)size, (uintmax_t)limit);
  22. }
  23. return 0;
  24. }
  25. char *xstrdup(const char *str)
  26. {
  27. char *ret = strdup(str);
  28. if (!ret)
  29. die("Out of memory, strdup failed");
  30. return ret;
  31. }
  32. static void *do_xmalloc(size_t size, int gentle)
  33. {
  34. void *ret;
  35. if (memory_limit_check(size, gentle))
  36. return NULL;
  37. ret = malloc(size);
  38. if (!ret && !size)
  39. ret = malloc(1);
  40. if (!ret) {
  41. if (!gentle)
  42. die("Out of memory, malloc failed (tried to allocate %lu bytes)",
  43. (unsigned long)size);
  44. else {
  45. error("Out of memory, malloc failed (tried to allocate %lu bytes)",
  46. (unsigned long)size);
  47. return NULL;
  48. }
  49. }
  50. #ifdef XMALLOC_POISON
  51. memset(ret, 0xA5, size);
  52. #endif
  53. return ret;
  54. }
  55. void *xmalloc(size_t size)
  56. {
  57. return do_xmalloc(size, 0);
  58. }
  59. static void *do_xmallocz(size_t size, int gentle)
  60. {
  61. void *ret;
  62. if (unsigned_add_overflows(size, 1)) {
  63. if (gentle) {
  64. error("Data too large to fit into virtual memory space.");
  65. return NULL;
  66. } else
  67. die("Data too large to fit into virtual memory space.");
  68. }
  69. ret = do_xmalloc(size + 1, gentle);
  70. if (ret)
  71. ((char*)ret)[size] = 0;
  72. return ret;
  73. }
  74. void *xmallocz(size_t size)
  75. {
  76. return do_xmallocz(size, 0);
  77. }
  78. void *xmallocz_gently(size_t size)
  79. {
  80. return do_xmallocz(size, 1);
  81. }
  82. /*
  83. * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
  84. * "data" to the allocated memory, zero terminates the allocated memory,
  85. * and returns a pointer to the allocated memory. If the allocation fails,
  86. * the program dies.
  87. */
  88. void *xmemdupz(const void *data, size_t len)
  89. {
  90. return memcpy(xmallocz(len), data, len);
  91. }
  92. char *xstrndup(const char *str, size_t len)
  93. {
  94. char *p = memchr(str, '\0', len);
  95. return xmemdupz(str, p ? p - str : len);
  96. }
  97. int xstrncmpz(const char *s, const char *t, size_t len)
  98. {
  99. int res = strncmp(s, t, len);
  100. if (res)
  101. return res;
  102. return s[len] == '\0' ? 0 : 1;
  103. }
  104. void *xrealloc(void *ptr, size_t size)
  105. {
  106. void *ret;
  107. if (!size) {
  108. free(ptr);
  109. return xmalloc(0);
  110. }
  111. memory_limit_check(size, 0);
  112. ret = realloc(ptr, size);
  113. if (!ret)
  114. die("Out of memory, realloc failed");
  115. return ret;
  116. }
  117. void *xcalloc(size_t nmemb, size_t size)
  118. {
  119. void *ret;
  120. if (unsigned_mult_overflows(nmemb, size))
  121. die("data too large to fit into virtual memory space");
  122. memory_limit_check(size * nmemb, 0);
  123. ret = calloc(nmemb, size);
  124. if (!ret && (!nmemb || !size))
  125. ret = calloc(1, 1);
  126. if (!ret)
  127. die("Out of memory, calloc failed");
  128. return ret;
  129. }
  130. /*
  131. * Limit size of IO chunks, because huge chunks only cause pain. OS X
  132. * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
  133. * the absence of bugs, large chunks can result in bad latencies when
  134. * you decide to kill the process.
  135. *
  136. * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
  137. * that is smaller than that, clip it to SSIZE_MAX, as a call to
  138. * read(2) or write(2) larger than that is allowed to fail. As the last
  139. * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
  140. * to override this, if the definition of SSIZE_MAX given by the platform
  141. * is broken.
  142. */
  143. #ifndef MAX_IO_SIZE
  144. # define MAX_IO_SIZE_DEFAULT (8*1024*1024)
  145. # if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
  146. # define MAX_IO_SIZE SSIZE_MAX
  147. # else
  148. # define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
  149. # endif
  150. #endif
  151. /**
  152. * xopen() is the same as open(), but it die()s if the open() fails.
  153. */
  154. int xopen(const char *path, int oflag, ...)
  155. {
  156. mode_t mode = 0;
  157. va_list ap;
  158. /*
  159. * va_arg() will have undefined behavior if the specified type is not
  160. * compatible with the argument type. Since integers are promoted to
  161. * ints, we fetch the next argument as an int, and then cast it to a
  162. * mode_t to avoid undefined behavior.
  163. */
  164. va_start(ap, oflag);
  165. if (oflag & O_CREAT)
  166. mode = va_arg(ap, int);
  167. va_end(ap);
  168. for (;;) {
  169. int fd = open(path, oflag, mode);
  170. if (fd >= 0)
  171. return fd;
  172. if (errno == EINTR)
  173. continue;
  174. if ((oflag & O_RDWR) == O_RDWR)
  175. die_errno(_("could not open '%s' for reading and writing"), path);
  176. else if ((oflag & O_WRONLY) == O_WRONLY)
  177. die_errno(_("could not open '%s' for writing"), path);
  178. else
  179. die_errno(_("could not open '%s' for reading"), path);
  180. }
  181. }
  182. static int handle_nonblock(int fd, short poll_events, int err)
  183. {
  184. struct pollfd pfd;
  185. if (err != EAGAIN && err != EWOULDBLOCK)
  186. return 0;
  187. pfd.fd = fd;
  188. pfd.events = poll_events;
  189. /*
  190. * no need to check for errors, here;
  191. * a subsequent read/write will detect unrecoverable errors
  192. */
  193. poll(&pfd, 1, -1);
  194. return 1;
  195. }
  196. /*
  197. * xread() is the same a read(), but it automatically restarts read()
  198. * operations with a recoverable error (EAGAIN and EINTR). xread()
  199. * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
  200. */
  201. ssize_t xread(int fd, void *buf, size_t len)
  202. {
  203. ssize_t nr;
  204. if (len > MAX_IO_SIZE)
  205. len = MAX_IO_SIZE;
  206. while (1) {
  207. nr = read(fd, buf, len);
  208. if (nr < 0) {
  209. if (errno == EINTR)
  210. continue;
  211. if (handle_nonblock(fd, POLLIN, errno))
  212. continue;
  213. }
  214. return nr;
  215. }
  216. }
  217. /*
  218. * xwrite() is the same a write(), but it automatically restarts write()
  219. * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
  220. * GUARANTEE that "len" bytes is written even if the operation is successful.
  221. */
  222. ssize_t xwrite(int fd, const void *buf, size_t len)
  223. {
  224. ssize_t nr;
  225. if (len > MAX_IO_SIZE)
  226. len = MAX_IO_SIZE;
  227. while (1) {
  228. nr = write(fd, buf, len);
  229. if (nr < 0) {
  230. if (errno == EINTR)
  231. continue;
  232. if (handle_nonblock(fd, POLLOUT, errno))
  233. continue;
  234. }
  235. return nr;
  236. }
  237. }
  238. /*
  239. * xpread() is the same as pread(), but it automatically restarts pread()
  240. * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
  241. * NOT GUARANTEE that "len" bytes is read even if the data is available.
  242. */
  243. ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
  244. {
  245. ssize_t nr;
  246. if (len > MAX_IO_SIZE)
  247. len = MAX_IO_SIZE;
  248. while (1) {
  249. nr = pread(fd, buf, len, offset);
  250. if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
  251. continue;
  252. return nr;
  253. }
  254. }
  255. ssize_t read_in_full(int fd, void *buf, size_t count)
  256. {
  257. char *p = buf;
  258. ssize_t total = 0;
  259. while (count > 0) {
  260. ssize_t loaded = xread(fd, p, count);
  261. if (loaded < 0)
  262. return -1;
  263. if (loaded == 0)
  264. return total;
  265. count -= loaded;
  266. p += loaded;
  267. total += loaded;
  268. }
  269. return total;
  270. }
  271. ssize_t write_in_full(int fd, const void *buf, size_t count)
  272. {
  273. const char *p = buf;
  274. ssize_t total = 0;
  275. while (count > 0) {
  276. ssize_t written = xwrite(fd, p, count);
  277. if (written < 0)
  278. return -1;
  279. if (!written) {
  280. errno = ENOSPC;
  281. return -1;
  282. }
  283. count -= written;
  284. p += written;
  285. total += written;
  286. }
  287. return total;
  288. }
  289. ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
  290. {
  291. char *p = buf;
  292. ssize_t total = 0;
  293. while (count > 0) {
  294. ssize_t loaded = xpread(fd, p, count, offset);
  295. if (loaded < 0)
  296. return -1;
  297. if (loaded == 0)
  298. return total;
  299. count -= loaded;
  300. p += loaded;
  301. total += loaded;
  302. offset += loaded;
  303. }
  304. return total;
  305. }
  306. int xdup(int fd)
  307. {
  308. int ret = dup(fd);
  309. if (ret < 0)
  310. die_errno("dup failed");
  311. return ret;
  312. }
  313. /**
  314. * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
  315. */
  316. FILE *xfopen(const char *path, const char *mode)
  317. {
  318. for (;;) {
  319. FILE *fp = fopen(path, mode);
  320. if (fp)
  321. return fp;
  322. if (errno == EINTR)
  323. continue;
  324. if (*mode && mode[1] == '+')
  325. die_errno(_("could not open '%s' for reading and writing"), path);
  326. else if (*mode == 'w' || *mode == 'a')
  327. die_errno(_("could not open '%s' for writing"), path);
  328. else
  329. die_errno(_("could not open '%s' for reading"), path);
  330. }
  331. }
  332. FILE *xfdopen(int fd, const char *mode)
  333. {
  334. FILE *stream = fdopen(fd, mode);
  335. if (stream == NULL)
  336. die_errno("Out of memory? fdopen failed");
  337. return stream;
  338. }
  339. FILE *fopen_for_writing(const char *path)
  340. {
  341. FILE *ret = fopen(path, "w");
  342. if (!ret && errno == EPERM) {
  343. if (!unlink(path))
  344. ret = fopen(path, "w");
  345. else
  346. errno = EPERM;
  347. }
  348. return ret;
  349. }
  350. static void warn_on_inaccessible(const char *path)
  351. {
  352. warning_errno(_("unable to access '%s'"), path);
  353. }
  354. int warn_on_fopen_errors(const char *path)
  355. {
  356. if (errno != ENOENT && errno != ENOTDIR) {
  357. warn_on_inaccessible(path);
  358. return -1;
  359. }
  360. return 0;
  361. }
  362. FILE *fopen_or_warn(const char *path, const char *mode)
  363. {
  364. FILE *fp = fopen(path, mode);
  365. if (fp)
  366. return fp;
  367. warn_on_fopen_errors(path);
  368. return NULL;
  369. }
  370. int xmkstemp(char *filename_template)
  371. {
  372. int fd;
  373. char origtemplate[PATH_MAX];
  374. strlcpy(origtemplate, filename_template, sizeof(origtemplate));
  375. fd = mkstemp(filename_template);
  376. if (fd < 0) {
  377. int saved_errno = errno;
  378. const char *nonrelative_template;
  379. if (strlen(filename_template) != strlen(origtemplate))
  380. filename_template = origtemplate;
  381. nonrelative_template = absolute_path(filename_template);
  382. errno = saved_errno;
  383. die_errno("Unable to create temporary file '%s'",
  384. nonrelative_template);
  385. }
  386. return fd;
  387. }
  388. /* Adapted from libiberty's mkstemp.c. */
  389. #undef TMP_MAX
  390. #define TMP_MAX 16384
  391. int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
  392. {
  393. static const char letters[] =
  394. "abcdefghijklmnopqrstuvwxyz"
  395. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  396. "0123456789";
  397. static const int num_letters = ARRAY_SIZE(letters) - 1;
  398. static const char x_pattern[] = "XXXXXX";
  399. static const int num_x = ARRAY_SIZE(x_pattern) - 1;
  400. uint64_t value;
  401. struct timeval tv;
  402. char *filename_template;
  403. size_t len;
  404. int fd, count;
  405. len = strlen(pattern);
  406. if (len < num_x + suffix_len) {
  407. errno = EINVAL;
  408. return -1;
  409. }
  410. if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
  411. errno = EINVAL;
  412. return -1;
  413. }
  414. /*
  415. * Replace pattern's XXXXXX characters with randomness.
  416. * Try TMP_MAX different filenames.
  417. */
  418. gettimeofday(&tv, NULL);
  419. value = ((uint64_t)tv.tv_usec << 16) ^ tv.tv_sec ^ getpid();
  420. filename_template = &pattern[len - num_x - suffix_len];
  421. for (count = 0; count < TMP_MAX; ++count) {
  422. uint64_t v = value;
  423. int i;
  424. /* Fill in the random bits. */
  425. for (i = 0; i < num_x; i++) {
  426. filename_template[i] = letters[v % num_letters];
  427. v /= num_letters;
  428. }
  429. fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
  430. if (fd >= 0)
  431. return fd;
  432. /*
  433. * Fatal error (EPERM, ENOSPC etc).
  434. * It doesn't make sense to loop.
  435. */
  436. if (errno != EEXIST)
  437. break;
  438. /*
  439. * This is a random value. It is only necessary that
  440. * the next TMP_MAX values generated by adding 7777 to
  441. * VALUE are different with (module 2^32).
  442. */
  443. value += 7777;
  444. }
  445. /* We return the null string if we can't find a unique file name. */
  446. pattern[0] = '\0';
  447. return -1;
  448. }
  449. int git_mkstemp_mode(char *pattern, int mode)
  450. {
  451. /* mkstemp is just mkstemps with no suffix */
  452. return git_mkstemps_mode(pattern, 0, mode);
  453. }
  454. int xmkstemp_mode(char *filename_template, int mode)
  455. {
  456. int fd;
  457. char origtemplate[PATH_MAX];
  458. strlcpy(origtemplate, filename_template, sizeof(origtemplate));
  459. fd = git_mkstemp_mode(filename_template, mode);
  460. if (fd < 0) {
  461. int saved_errno = errno;
  462. const char *nonrelative_template;
  463. if (!filename_template[0])
  464. filename_template = origtemplate;
  465. nonrelative_template = absolute_path(filename_template);
  466. errno = saved_errno;
  467. die_errno("Unable to create temporary file '%s'",
  468. nonrelative_template);
  469. }
  470. return fd;
  471. }
  472. static int warn_if_unremovable(const char *op, const char *file, int rc)
  473. {
  474. int err;
  475. if (!rc || errno == ENOENT)
  476. return 0;
  477. err = errno;
  478. warning_errno("unable to %s '%s'", op, file);
  479. errno = err;
  480. return rc;
  481. }
  482. int unlink_or_msg(const char *file, struct strbuf *err)
  483. {
  484. int rc = unlink(file);
  485. assert(err);
  486. if (!rc || errno == ENOENT)
  487. return 0;
  488. strbuf_addf(err, "unable to unlink '%s': %s",
  489. file, strerror(errno));
  490. return -1;
  491. }
  492. int unlink_or_warn(const char *file)
  493. {
  494. return warn_if_unremovable("unlink", file, unlink(file));
  495. }
  496. int rmdir_or_warn(const char *file)
  497. {
  498. return warn_if_unremovable("rmdir", file, rmdir(file));
  499. }
  500. int remove_or_warn(unsigned int mode, const char *file)
  501. {
  502. return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
  503. }
  504. static int access_error_is_ok(int err, unsigned flag)
  505. {
  506. return (is_missing_file_error(err) ||
  507. ((flag & ACCESS_EACCES_OK) && err == EACCES));
  508. }
  509. int access_or_warn(const char *path, int mode, unsigned flag)
  510. {
  511. int ret = access(path, mode);
  512. if (ret && !access_error_is_ok(errno, flag))
  513. warn_on_inaccessible(path);
  514. return ret;
  515. }
  516. int access_or_die(const char *path, int mode, unsigned flag)
  517. {
  518. int ret = access(path, mode);
  519. if (ret && !access_error_is_ok(errno, flag))
  520. die_errno(_("unable to access '%s'"), path);
  521. return ret;
  522. }
  523. char *xgetcwd(void)
  524. {
  525. struct strbuf sb = STRBUF_INIT;
  526. if (strbuf_getcwd(&sb))
  527. die_errno(_("unable to get current working directory"));
  528. return strbuf_detach(&sb, NULL);
  529. }
  530. int xsnprintf(char *dst, size_t max, const char *fmt, ...)
  531. {
  532. va_list ap;
  533. int len;
  534. va_start(ap, fmt);
  535. len = vsnprintf(dst, max, fmt, ap);
  536. va_end(ap);
  537. if (len < 0)
  538. BUG("your snprintf is broken");
  539. if (len >= max)
  540. BUG("attempt to snprintf into too-small buffer");
  541. return len;
  542. }
  543. void write_file_buf(const char *path, const char *buf, size_t len)
  544. {
  545. int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  546. if (write_in_full(fd, buf, len) < 0)
  547. die_errno(_("could not write to '%s'"), path);
  548. if (close(fd))
  549. die_errno(_("could not close '%s'"), path);
  550. }
  551. void write_file(const char *path, const char *fmt, ...)
  552. {
  553. va_list params;
  554. struct strbuf sb = STRBUF_INIT;
  555. va_start(params, fmt);
  556. strbuf_vaddf(&sb, fmt, params);
  557. va_end(params);
  558. strbuf_complete_line(&sb);
  559. write_file_buf(path, sb.buf, sb.len);
  560. strbuf_release(&sb);
  561. }
  562. void sleep_millisec(int millisec)
  563. {
  564. poll(NULL, 0, millisec);
  565. }
  566. int xgethostname(char *buf, size_t len)
  567. {
  568. /*
  569. * If the full hostname doesn't fit in buf, POSIX does not
  570. * specify whether the buffer will be null-terminated, so to
  571. * be safe, do it ourselves.
  572. */
  573. int ret = gethostname(buf, len);
  574. if (!ret)
  575. buf[len - 1] = 0;
  576. return ret;
  577. }
  578. int is_empty_or_missing_file(const char *filename)
  579. {
  580. struct stat st;
  581. if (stat(filename, &st) < 0) {
  582. if (errno == ENOENT)
  583. return 1;
  584. die_errno(_("could not stat %s"), filename);
  585. }
  586. return !st.st_size;
  587. }