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