]> git.ipfire.org Git - thirdparty/git.git/blob - wrapper.c
Merge branch 'la/trailer-cleanups' into maint-2.43
[thirdparty/git.git] / wrapper.c
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "parse.h"
7 #include "gettext.h"
8 #include "repository.h"
9 #include "strbuf.h"
10 #include "trace2.h"
11
12 #ifdef HAVE_RTLGENRANDOM
13 /* This is required to get access to RtlGenRandom. */
14 #define SystemFunction036 NTAPI SystemFunction036
15 #include <ntsecapi.h>
16 #undef SystemFunction036
17 #endif
18
19 static int memory_limit_check(size_t size, int gentle)
20 {
21 static size_t limit = 0;
22 if (!limit) {
23 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
24 if (!limit)
25 limit = SIZE_MAX;
26 }
27 if (size > limit) {
28 if (gentle) {
29 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
30 (uintmax_t)size, (uintmax_t)limit);
31 return -1;
32 } else
33 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
34 (uintmax_t)size, (uintmax_t)limit);
35 }
36 return 0;
37 }
38
39 char *xstrdup(const char *str)
40 {
41 char *ret = strdup(str);
42 if (!ret)
43 die("Out of memory, strdup failed");
44 return ret;
45 }
46
47 static void *do_xmalloc(size_t size, int gentle)
48 {
49 void *ret;
50
51 if (memory_limit_check(size, gentle))
52 return NULL;
53 ret = malloc(size);
54 if (!ret && !size)
55 ret = malloc(1);
56 if (!ret) {
57 if (!gentle)
58 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
59 (unsigned long)size);
60 else {
61 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
62 (unsigned long)size);
63 return NULL;
64 }
65 }
66 #ifdef XMALLOC_POISON
67 memset(ret, 0xA5, size);
68 #endif
69 return ret;
70 }
71
72 void *xmalloc(size_t size)
73 {
74 return do_xmalloc(size, 0);
75 }
76
77 static void *do_xmallocz(size_t size, int gentle)
78 {
79 void *ret;
80 if (unsigned_add_overflows(size, 1)) {
81 if (gentle) {
82 error("Data too large to fit into virtual memory space.");
83 return NULL;
84 } else
85 die("Data too large to fit into virtual memory space.");
86 }
87 ret = do_xmalloc(size + 1, gentle);
88 if (ret)
89 ((char*)ret)[size] = 0;
90 return ret;
91 }
92
93 void *xmallocz(size_t size)
94 {
95 return do_xmallocz(size, 0);
96 }
97
98 void *xmallocz_gently(size_t size)
99 {
100 return do_xmallocz(size, 1);
101 }
102
103 /*
104 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
105 * "data" to the allocated memory, zero terminates the allocated memory,
106 * and returns a pointer to the allocated memory. If the allocation fails,
107 * the program dies.
108 */
109 void *xmemdupz(const void *data, size_t len)
110 {
111 return memcpy(xmallocz(len), data, len);
112 }
113
114 char *xstrndup(const char *str, size_t len)
115 {
116 char *p = memchr(str, '\0', len);
117 return xmemdupz(str, p ? p - str : len);
118 }
119
120 int xstrncmpz(const char *s, const char *t, size_t len)
121 {
122 int res = strncmp(s, t, len);
123 if (res)
124 return res;
125 return s[len] == '\0' ? 0 : 1;
126 }
127
128 void *xrealloc(void *ptr, size_t size)
129 {
130 void *ret;
131
132 if (!size) {
133 free(ptr);
134 return xmalloc(0);
135 }
136
137 memory_limit_check(size, 0);
138 ret = realloc(ptr, size);
139 if (!ret)
140 die("Out of memory, realloc failed");
141 return ret;
142 }
143
144 void *xcalloc(size_t nmemb, size_t size)
145 {
146 void *ret;
147
148 if (unsigned_mult_overflows(nmemb, size))
149 die("data too large to fit into virtual memory space");
150
151 memory_limit_check(size * nmemb, 0);
152 ret = calloc(nmemb, size);
153 if (!ret && (!nmemb || !size))
154 ret = calloc(1, 1);
155 if (!ret)
156 die("Out of memory, calloc failed");
157 return ret;
158 }
159
160 void xsetenv(const char *name, const char *value, int overwrite)
161 {
162 if (setenv(name, value, overwrite))
163 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
164 }
165
166 /**
167 * xopen() is the same as open(), but it die()s if the open() fails.
168 */
169 int xopen(const char *path, int oflag, ...)
170 {
171 mode_t mode = 0;
172 va_list ap;
173
174 /*
175 * va_arg() will have undefined behavior if the specified type is not
176 * compatible with the argument type. Since integers are promoted to
177 * ints, we fetch the next argument as an int, and then cast it to a
178 * mode_t to avoid undefined behavior.
179 */
180 va_start(ap, oflag);
181 if (oflag & O_CREAT)
182 mode = va_arg(ap, int);
183 va_end(ap);
184
185 for (;;) {
186 int fd = open(path, oflag, mode);
187 if (fd >= 0)
188 return fd;
189 if (errno == EINTR)
190 continue;
191
192 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
193 die_errno(_("unable to create '%s'"), path);
194 else if ((oflag & O_RDWR) == O_RDWR)
195 die_errno(_("could not open '%s' for reading and writing"), path);
196 else if ((oflag & O_WRONLY) == O_WRONLY)
197 die_errno(_("could not open '%s' for writing"), path);
198 else
199 die_errno(_("could not open '%s' for reading"), path);
200 }
201 }
202
203 static int handle_nonblock(int fd, short poll_events, int err)
204 {
205 struct pollfd pfd;
206
207 if (err != EAGAIN && err != EWOULDBLOCK)
208 return 0;
209
210 pfd.fd = fd;
211 pfd.events = poll_events;
212
213 /*
214 * no need to check for errors, here;
215 * a subsequent read/write will detect unrecoverable errors
216 */
217 poll(&pfd, 1, -1);
218 return 1;
219 }
220
221 /*
222 * xread() is the same a read(), but it automatically restarts read()
223 * operations with a recoverable error (EAGAIN and EINTR). xread()
224 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
225 */
226 ssize_t xread(int fd, void *buf, size_t len)
227 {
228 ssize_t nr;
229 if (len > MAX_IO_SIZE)
230 len = MAX_IO_SIZE;
231 while (1) {
232 nr = read(fd, buf, len);
233 if (nr < 0) {
234 if (errno == EINTR)
235 continue;
236 if (handle_nonblock(fd, POLLIN, errno))
237 continue;
238 }
239 return nr;
240 }
241 }
242
243 /*
244 * xwrite() is the same a write(), but it automatically restarts write()
245 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
246 * GUARANTEE that "len" bytes is written even if the operation is successful.
247 */
248 ssize_t xwrite(int fd, const void *buf, size_t len)
249 {
250 ssize_t nr;
251 if (len > MAX_IO_SIZE)
252 len = MAX_IO_SIZE;
253 while (1) {
254 nr = write(fd, buf, len);
255 if (nr < 0) {
256 if (errno == EINTR)
257 continue;
258 if (handle_nonblock(fd, POLLOUT, errno))
259 continue;
260 }
261
262 return nr;
263 }
264 }
265
266 /*
267 * xpread() is the same as pread(), but it automatically restarts pread()
268 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
269 * NOT GUARANTEE that "len" bytes is read even if the data is available.
270 */
271 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
272 {
273 ssize_t nr;
274 if (len > MAX_IO_SIZE)
275 len = MAX_IO_SIZE;
276 while (1) {
277 nr = pread(fd, buf, len, offset);
278 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
279 continue;
280 return nr;
281 }
282 }
283
284 ssize_t read_in_full(int fd, void *buf, size_t count)
285 {
286 char *p = buf;
287 ssize_t total = 0;
288
289 while (count > 0) {
290 ssize_t loaded = xread(fd, p, count);
291 if (loaded < 0)
292 return -1;
293 if (loaded == 0)
294 return total;
295 count -= loaded;
296 p += loaded;
297 total += loaded;
298 }
299
300 return total;
301 }
302
303 ssize_t write_in_full(int fd, const void *buf, size_t count)
304 {
305 const char *p = buf;
306 ssize_t total = 0;
307
308 while (count > 0) {
309 ssize_t written = xwrite(fd, p, count);
310 if (written < 0)
311 return -1;
312 if (!written) {
313 errno = ENOSPC;
314 return -1;
315 }
316 count -= written;
317 p += written;
318 total += written;
319 }
320
321 return total;
322 }
323
324 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
325 {
326 char *p = buf;
327 ssize_t total = 0;
328
329 while (count > 0) {
330 ssize_t loaded = xpread(fd, p, count, offset);
331 if (loaded < 0)
332 return -1;
333 if (loaded == 0)
334 return total;
335 count -= loaded;
336 p += loaded;
337 total += loaded;
338 offset += loaded;
339 }
340
341 return total;
342 }
343
344 int xdup(int fd)
345 {
346 int ret = dup(fd);
347 if (ret < 0)
348 die_errno("dup failed");
349 return ret;
350 }
351
352 /**
353 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
354 */
355 FILE *xfopen(const char *path, const char *mode)
356 {
357 for (;;) {
358 FILE *fp = fopen(path, mode);
359 if (fp)
360 return fp;
361 if (errno == EINTR)
362 continue;
363
364 if (*mode && mode[1] == '+')
365 die_errno(_("could not open '%s' for reading and writing"), path);
366 else if (*mode == 'w' || *mode == 'a')
367 die_errno(_("could not open '%s' for writing"), path);
368 else
369 die_errno(_("could not open '%s' for reading"), path);
370 }
371 }
372
373 FILE *xfdopen(int fd, const char *mode)
374 {
375 FILE *stream = fdopen(fd, mode);
376 if (!stream)
377 die_errno("Out of memory? fdopen failed");
378 return stream;
379 }
380
381 FILE *fopen_for_writing(const char *path)
382 {
383 FILE *ret = fopen(path, "w");
384
385 if (!ret && errno == EPERM) {
386 if (!unlink(path))
387 ret = fopen(path, "w");
388 else
389 errno = EPERM;
390 }
391 return ret;
392 }
393
394 static void warn_on_inaccessible(const char *path)
395 {
396 warning_errno(_("unable to access '%s'"), path);
397 }
398
399 int warn_on_fopen_errors(const char *path)
400 {
401 if (errno != ENOENT && errno != ENOTDIR) {
402 warn_on_inaccessible(path);
403 return -1;
404 }
405
406 return 0;
407 }
408
409 FILE *fopen_or_warn(const char *path, const char *mode)
410 {
411 FILE *fp = fopen(path, mode);
412
413 if (fp)
414 return fp;
415
416 warn_on_fopen_errors(path);
417 return NULL;
418 }
419
420 int xmkstemp(char *filename_template)
421 {
422 int fd;
423 char origtemplate[PATH_MAX];
424 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
425
426 fd = mkstemp(filename_template);
427 if (fd < 0) {
428 int saved_errno = errno;
429 const char *nonrelative_template;
430
431 if (strlen(filename_template) != strlen(origtemplate))
432 filename_template = origtemplate;
433
434 nonrelative_template = absolute_path(filename_template);
435 errno = saved_errno;
436 die_errno("Unable to create temporary file '%s'",
437 nonrelative_template);
438 }
439 return fd;
440 }
441
442 /* Adapted from libiberty's mkstemp.c. */
443
444 #undef TMP_MAX
445 #define TMP_MAX 16384
446
447 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
448 {
449 static const char letters[] =
450 "abcdefghijklmnopqrstuvwxyz"
451 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
452 "0123456789";
453 static const int num_letters = ARRAY_SIZE(letters) - 1;
454 static const char x_pattern[] = "XXXXXX";
455 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
456 char *filename_template;
457 size_t len;
458 int fd, count;
459
460 len = strlen(pattern);
461
462 if (len < num_x + suffix_len) {
463 errno = EINVAL;
464 return -1;
465 }
466
467 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
468 errno = EINVAL;
469 return -1;
470 }
471
472 /*
473 * Replace pattern's XXXXXX characters with randomness.
474 * Try TMP_MAX different filenames.
475 */
476 filename_template = &pattern[len - num_x - suffix_len];
477 for (count = 0; count < TMP_MAX; ++count) {
478 int i;
479 uint64_t v;
480 if (csprng_bytes(&v, sizeof(v)) < 0)
481 return error_errno("unable to get random bytes for temporary file");
482
483 /* Fill in the random bits. */
484 for (i = 0; i < num_x; i++) {
485 filename_template[i] = letters[v % num_letters];
486 v /= num_letters;
487 }
488
489 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
490 if (fd >= 0)
491 return fd;
492 /*
493 * Fatal error (EPERM, ENOSPC etc).
494 * It doesn't make sense to loop.
495 */
496 if (errno != EEXIST)
497 break;
498 }
499 /* We return the null string if we can't find a unique file name. */
500 pattern[0] = '\0';
501 return -1;
502 }
503
504 int git_mkstemp_mode(char *pattern, int mode)
505 {
506 /* mkstemp is just mkstemps with no suffix */
507 return git_mkstemps_mode(pattern, 0, mode);
508 }
509
510 int xmkstemp_mode(char *filename_template, int mode)
511 {
512 int fd;
513 char origtemplate[PATH_MAX];
514 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
515
516 fd = git_mkstemp_mode(filename_template, mode);
517 if (fd < 0) {
518 int saved_errno = errno;
519 const char *nonrelative_template;
520
521 if (!filename_template[0])
522 filename_template = origtemplate;
523
524 nonrelative_template = absolute_path(filename_template);
525 errno = saved_errno;
526 die_errno("Unable to create temporary file '%s'",
527 nonrelative_template);
528 }
529 return fd;
530 }
531
532 /*
533 * Some platforms return EINTR from fsync. Since fsync is invoked in some
534 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
535 */
536 static int fsync_loop(int fd)
537 {
538 int err;
539
540 do {
541 err = fsync(fd);
542 } while (err < 0 && errno == EINTR);
543 return err;
544 }
545
546 int git_fsync(int fd, enum fsync_action action)
547 {
548 switch (action) {
549 case FSYNC_WRITEOUT_ONLY:
550 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_WRITEOUT_ONLY, 1);
551
552 #ifdef __APPLE__
553 /*
554 * On macOS, fsync just causes filesystem cache writeback but
555 * does not flush hardware caches.
556 */
557 return fsync_loop(fd);
558 #endif
559
560 #ifdef HAVE_SYNC_FILE_RANGE
561 /*
562 * On linux 2.6.17 and above, sync_file_range is the way to
563 * issue a writeback without a hardware flush. An offset of
564 * 0 and size of 0 indicates writeout of the entire file and the
565 * wait flags ensure that all dirty data is written to the disk
566 * (potentially in a disk-side cache) before we continue.
567 */
568
569 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
570 SYNC_FILE_RANGE_WRITE |
571 SYNC_FILE_RANGE_WAIT_AFTER);
572 #endif
573
574 #ifdef fsync_no_flush
575 return fsync_no_flush(fd);
576 #endif
577
578 errno = ENOSYS;
579 return -1;
580
581 case FSYNC_HARDWARE_FLUSH:
582 trace2_counter_add(TRACE2_COUNTER_ID_FSYNC_HARDWARE_FLUSH, 1);
583
584 /*
585 * On macOS, a special fcntl is required to really flush the
586 * caches within the storage controller. As of this writing,
587 * this is a very expensive operation on Apple SSDs.
588 */
589 #ifdef __APPLE__
590 return fcntl(fd, F_FULLFSYNC);
591 #else
592 return fsync_loop(fd);
593 #endif
594 default:
595 BUG("unexpected git_fsync(%d) call", action);
596 }
597 }
598
599 static int warn_if_unremovable(const char *op, const char *file, int rc)
600 {
601 int err;
602 if (!rc || errno == ENOENT)
603 return 0;
604 err = errno;
605 warning_errno("unable to %s '%s'", op, file);
606 errno = err;
607 return rc;
608 }
609
610 int unlink_or_msg(const char *file, struct strbuf *err)
611 {
612 int rc = unlink(file);
613
614 assert(err);
615
616 if (!rc || errno == ENOENT)
617 return 0;
618
619 strbuf_addf(err, "unable to unlink '%s': %s",
620 file, strerror(errno));
621 return -1;
622 }
623
624 int unlink_or_warn(const char *file)
625 {
626 return warn_if_unremovable("unlink", file, unlink(file));
627 }
628
629 int rmdir_or_warn(const char *file)
630 {
631 return warn_if_unremovable("rmdir", file, rmdir(file));
632 }
633
634 static int access_error_is_ok(int err, unsigned flag)
635 {
636 return (is_missing_file_error(err) ||
637 ((flag & ACCESS_EACCES_OK) && err == EACCES));
638 }
639
640 int access_or_warn(const char *path, int mode, unsigned flag)
641 {
642 int ret = access(path, mode);
643 if (ret && !access_error_is_ok(errno, flag))
644 warn_on_inaccessible(path);
645 return ret;
646 }
647
648 int access_or_die(const char *path, int mode, unsigned flag)
649 {
650 int ret = access(path, mode);
651 if (ret && !access_error_is_ok(errno, flag))
652 die_errno(_("unable to access '%s'"), path);
653 return ret;
654 }
655
656 char *xgetcwd(void)
657 {
658 struct strbuf sb = STRBUF_INIT;
659 if (strbuf_getcwd(&sb))
660 die_errno(_("unable to get current working directory"));
661 return strbuf_detach(&sb, NULL);
662 }
663
664 int xsnprintf(char *dst, size_t max, const char *fmt, ...)
665 {
666 va_list ap;
667 int len;
668
669 va_start(ap, fmt);
670 len = vsnprintf(dst, max, fmt, ap);
671 va_end(ap);
672
673 if (len < 0)
674 BUG("your snprintf is broken");
675 if (len >= max)
676 BUG("attempt to snprintf into too-small buffer");
677 return len;
678 }
679
680 void write_file_buf(const char *path, const char *buf, size_t len)
681 {
682 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
683 if (write_in_full(fd, buf, len) < 0)
684 die_errno(_("could not write to '%s'"), path);
685 if (close(fd))
686 die_errno(_("could not close '%s'"), path);
687 }
688
689 void write_file(const char *path, const char *fmt, ...)
690 {
691 va_list params;
692 struct strbuf sb = STRBUF_INIT;
693
694 va_start(params, fmt);
695 strbuf_vaddf(&sb, fmt, params);
696 va_end(params);
697
698 strbuf_complete_line(&sb);
699
700 write_file_buf(path, sb.buf, sb.len);
701 strbuf_release(&sb);
702 }
703
704 void sleep_millisec(int millisec)
705 {
706 poll(NULL, 0, millisec);
707 }
708
709 int xgethostname(char *buf, size_t len)
710 {
711 /*
712 * If the full hostname doesn't fit in buf, POSIX does not
713 * specify whether the buffer will be null-terminated, so to
714 * be safe, do it ourselves.
715 */
716 int ret = gethostname(buf, len);
717 if (!ret)
718 buf[len - 1] = 0;
719 return ret;
720 }
721
722 int is_empty_or_missing_file(const char *filename)
723 {
724 struct stat st;
725
726 if (stat(filename, &st) < 0) {
727 if (errno == ENOENT)
728 return 1;
729 die_errno(_("could not stat %s"), filename);
730 }
731
732 return !st.st_size;
733 }
734
735 int open_nofollow(const char *path, int flags)
736 {
737 #ifdef O_NOFOLLOW
738 return open(path, flags | O_NOFOLLOW);
739 #else
740 struct stat st;
741 if (lstat(path, &st) < 0)
742 return -1;
743 if (S_ISLNK(st.st_mode)) {
744 errno = ELOOP;
745 return -1;
746 }
747 return open(path, flags);
748 #endif
749 }
750
751 int csprng_bytes(void *buf, size_t len)
752 {
753 #if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
754 /* This function never returns an error. */
755 arc4random_buf(buf, len);
756 return 0;
757 #elif defined(HAVE_GETRANDOM)
758 ssize_t res;
759 char *p = buf;
760 while (len) {
761 res = getrandom(p, len, 0);
762 if (res < 0)
763 return -1;
764 len -= res;
765 p += res;
766 }
767 return 0;
768 #elif defined(HAVE_GETENTROPY)
769 int res;
770 char *p = buf;
771 while (len) {
772 /* getentropy has a maximum size of 256 bytes. */
773 size_t chunk = len < 256 ? len : 256;
774 res = getentropy(p, chunk);
775 if (res < 0)
776 return -1;
777 len -= chunk;
778 p += chunk;
779 }
780 return 0;
781 #elif defined(HAVE_RTLGENRANDOM)
782 if (!RtlGenRandom(buf, len))
783 return -1;
784 return 0;
785 #elif defined(HAVE_OPENSSL_CSPRNG)
786 int res = RAND_bytes(buf, len);
787 if (res == 1)
788 return 0;
789 if (res == -1)
790 errno = ENOTSUP;
791 else
792 errno = EIO;
793 return -1;
794 #else
795 ssize_t res;
796 char *p = buf;
797 int fd, err;
798 fd = open("/dev/urandom", O_RDONLY);
799 if (fd < 0)
800 return -1;
801 while (len) {
802 res = xread(fd, p, len);
803 if (res < 0) {
804 err = errno;
805 close(fd);
806 errno = err;
807 return -1;
808 }
809 len -= res;
810 p += res;
811 }
812 close(fd);
813 return 0;
814 #endif
815 }
816
817 uint32_t git_rand(void)
818 {
819 uint32_t result;
820
821 if (csprng_bytes(&result, sizeof(result)) < 0)
822 die(_("unable to get random bytes"));
823
824 return result;
825 }