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