blob: ea3cf64d4c399ae84c156b850002459a8ffde72c [file] [log] [blame]
Linus Torvalds112db552008-06-22 12:19:25 -07001/*
2 * Various trivial helper wrappers around standard functions
3 */
4#include "cache.h"
Brandon Williamsb2141fc2017-06-14 11:07:36 -07005#include "config.h"
Linus Torvalds112db552008-06-22 12:19:25 -07006
Jonathan Niedere0500292010-11-06 14:00:38 -05007static void do_nothing(size_t size)
Nicolas Pitrea9a74632010-03-24 16:22:34 -04008{
Nicolas Pitrea9a74632010-03-24 16:22:34 -04009}
10
Jonathan Niedere0500292010-11-06 14:00:38 -050011static void (*try_to_free_routine)(size_t size) = do_nothing;
Nicolas Pitrea9a74632010-03-24 16:22:34 -040012
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070013static int memory_limit_check(size_t size, int gentle)
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070014{
Steffen Prohaska9927d962014-08-26 17:23:22 +020015 static size_t limit = 0;
16 if (!limit) {
17 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
18 if (!limit)
19 limit = SIZE_MAX;
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070020 }
Junio C Hamanof0d89002014-10-08 13:05:32 -070021 if (size > limit) {
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070022 if (gentle) {
Junio C Hamanof0d89002014-10-08 13:05:32 -070023 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
24 (uintmax_t)size, (uintmax_t)limit);
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070025 return -1;
26 } else
Junio C Hamanof0d89002014-10-08 13:05:32 -070027 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
28 (uintmax_t)size, (uintmax_t)limit);
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070029 }
30 return 0;
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070031}
32
Johannes Sixt851c34b2010-05-08 17:13:49 +020033try_to_free_t set_try_to_free_routine(try_to_free_t routine)
Nicolas Pitrea9a74632010-03-24 16:22:34 -040034{
Johannes Sixt851c34b2010-05-08 17:13:49 +020035 try_to_free_t old = try_to_free_routine;
Junio C Hamano00b0d7f2010-12-21 09:24:18 -080036 if (!routine)
37 routine = do_nothing;
Johannes Sixt851c34b2010-05-08 17:13:49 +020038 try_to_free_routine = routine;
39 return old;
Nicolas Pitrea9a74632010-03-24 16:22:34 -040040}
41
Linus Torvalds112db552008-06-22 12:19:25 -070042char *xstrdup(const char *str)
43{
44 char *ret = strdup(str);
45 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -040046 try_to_free_routine(strlen(str) + 1);
Linus Torvalds112db552008-06-22 12:19:25 -070047 ret = strdup(str);
48 if (!ret)
49 die("Out of memory, strdup failed");
50 }
51 return ret;
52}
53
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070054static void *do_xmalloc(size_t size, int gentle)
Linus Torvalds112db552008-06-22 12:19:25 -070055{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070056 void *ret;
57
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070058 if (memory_limit_check(size, gentle))
59 return NULL;
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070060 ret = malloc(size);
Linus Torvalds112db552008-06-22 12:19:25 -070061 if (!ret && !size)
62 ret = malloc(1);
63 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -040064 try_to_free_routine(size);
Linus Torvalds112db552008-06-22 12:19:25 -070065 ret = malloc(size);
66 if (!ret && !size)
67 ret = malloc(1);
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070068 if (!ret) {
69 if (!gentle)
70 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
71 (unsigned long)size);
72 else {
73 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
74 (unsigned long)size);
75 return NULL;
76 }
77 }
Linus Torvalds112db552008-06-22 12:19:25 -070078 }
79#ifdef XMALLOC_POISON
80 memset(ret, 0xA5, size);
81#endif
82 return ret;
83}
84
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070085void *xmalloc(size_t size)
86{
87 return do_xmalloc(size, 0);
88}
89
90static void *do_xmallocz(size_t size, int gentle)
Ilari Liusvaara5bf92192010-01-26 20:24:12 +020091{
92 void *ret;
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +070093 if (unsigned_add_overflows(size, 1)) {
94 if (gentle) {
95 error("Data too large to fit into virtual memory space.");
96 return NULL;
97 } else
98 die("Data too large to fit into virtual memory space.");
99 }
100 ret = do_xmalloc(size + 1, gentle);
101 if (ret)
102 ((char*)ret)[size] = 0;
Ilari Liusvaara5bf92192010-01-26 20:24:12 +0200103 return ret;
104}
105
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +0700106void *xmallocz(size_t size)
107{
108 return do_xmallocz(size, 0);
109}
110
111void *xmallocz_gently(size_t size)
112{
113 return do_xmallocz(size, 1);
114}
115
Linus Torvalds112db552008-06-22 12:19:25 -0700116/*
117 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
118 * "data" to the allocated memory, zero terminates the allocated memory,
119 * and returns a pointer to the allocated memory. If the allocation fails,
120 * the program dies.
121 */
122void *xmemdupz(const void *data, size_t len)
123{
Ilari Liusvaara5bf92192010-01-26 20:24:12 +0200124 return memcpy(xmallocz(len), data, len);
Linus Torvalds112db552008-06-22 12:19:25 -0700125}
126
127char *xstrndup(const char *str, size_t len)
128{
129 char *p = memchr(str, '\0', len);
130 return xmemdupz(str, p ? p - str : len);
131}
132
133void *xrealloc(void *ptr, size_t size)
134{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +0700135 void *ret;
136
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +0700137 memory_limit_check(size, 0);
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +0700138 ret = realloc(ptr, size);
Linus Torvalds112db552008-06-22 12:19:25 -0700139 if (!ret && !size)
140 ret = realloc(ptr, 1);
141 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -0400142 try_to_free_routine(size);
Linus Torvalds112db552008-06-22 12:19:25 -0700143 ret = realloc(ptr, size);
144 if (!ret && !size)
145 ret = realloc(ptr, 1);
146 if (!ret)
147 die("Out of memory, realloc failed");
148 }
149 return ret;
150}
151
152void *xcalloc(size_t nmemb, size_t size)
153{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +0700154 void *ret;
155
Jeff Kinge7792a72016-02-22 17:43:18 -0500156 if (unsigned_mult_overflows(nmemb, size))
157 die("data too large to fit into virtual memory space");
158
Nguyễn Thái Ngọc Duyf8bb1d92014-08-16 10:08:02 +0700159 memory_limit_check(size * nmemb, 0);
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +0700160 ret = calloc(nmemb, size);
Linus Torvalds112db552008-06-22 12:19:25 -0700161 if (!ret && (!nmemb || !size))
162 ret = calloc(1, 1);
163 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -0400164 try_to_free_routine(nmemb * size);
Linus Torvalds112db552008-06-22 12:19:25 -0700165 ret = calloc(nmemb, size);
166 if (!ret && (!nmemb || !size))
167 ret = calloc(1, 1);
168 if (!ret)
169 die("Out of memory, calloc failed");
170 }
171 return ret;
172}
173
Linus Torvalds112db552008-06-22 12:19:25 -0700174/*
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200175 * Limit size of IO chunks, because huge chunks only cause pain. OS X
176 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
Masanari Iida382d20e2013-11-13 00:17:42 +0900177 * the absence of bugs, large chunks can result in bad latencies when
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200178 * you decide to kill the process.
Junio C Hamanoa983e6a2015-02-11 13:13:10 -0800179 *
180 * We pick 8 MiB as our default, but if the platform defines SSIZE_MAX
181 * that is smaller than that, clip it to SSIZE_MAX, as a call to
182 * read(2) or write(2) larger than that is allowed to fail. As the last
183 * resort, we allow a port to pass via CFLAGS e.g. "-DMAX_IO_SIZE=value"
184 * to override this, if the definition of SSIZE_MAX given by the platform
185 * is broken.
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200186 */
Junio C Hamanoa983e6a2015-02-11 13:13:10 -0800187#ifndef MAX_IO_SIZE
188# define MAX_IO_SIZE_DEFAULT (8*1024*1024)
189# if defined(SSIZE_MAX) && (SSIZE_MAX < MAX_IO_SIZE_DEFAULT)
190# define MAX_IO_SIZE SSIZE_MAX
191# else
192# define MAX_IO_SIZE MAX_IO_SIZE_DEFAULT
193# endif
194#endif
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200195
Paul Tan3ff53df2015-08-04 21:51:22 +0800196/**
197 * xopen() is the same as open(), but it die()s if the open() fails.
198 */
199int xopen(const char *path, int oflag, ...)
200{
201 mode_t mode = 0;
202 va_list ap;
203
204 /*
205 * va_arg() will have undefined behavior if the specified type is not
206 * compatible with the argument type. Since integers are promoted to
207 * ints, we fetch the next argument as an int, and then cast it to a
208 * mode_t to avoid undefined behavior.
209 */
210 va_start(ap, oflag);
211 if (oflag & O_CREAT)
212 mode = va_arg(ap, int);
213 va_end(ap);
214
215 for (;;) {
216 int fd = open(path, oflag, mode);
217 if (fd >= 0)
218 return fd;
219 if (errno == EINTR)
220 continue;
221
222 if ((oflag & O_RDWR) == O_RDWR)
223 die_errno(_("could not open '%s' for reading and writing"), path);
224 else if ((oflag & O_WRONLY) == O_WRONLY)
225 die_errno(_("could not open '%s' for writing"), path);
226 else
227 die_errno(_("could not open '%s' for reading"), path);
228 }
229}
230
Eric Wongd751dd12016-07-10 08:20:46 +0000231static int handle_nonblock(int fd, short poll_events, int err)
232{
233 struct pollfd pfd;
234
235 if (err != EAGAIN && err != EWOULDBLOCK)
236 return 0;
237
238 pfd.fd = fd;
239 pfd.events = poll_events;
240
241 /*
242 * no need to check for errors, here;
243 * a subsequent read/write will detect unrecoverable errors
244 */
245 poll(&pfd, 1, -1);
246 return 1;
247}
248
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200249/*
Linus Torvalds112db552008-06-22 12:19:25 -0700250 * xread() is the same a read(), but it automatically restarts read()
251 * operations with a recoverable error (EAGAIN and EINTR). xread()
252 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
253 */
254ssize_t xread(int fd, void *buf, size_t len)
255{
256 ssize_t nr;
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200257 if (len > MAX_IO_SIZE)
258 len = MAX_IO_SIZE;
Linus Torvalds112db552008-06-22 12:19:25 -0700259 while (1) {
260 nr = read(fd, buf, len);
Stefan Beller1079c4b2015-12-15 16:04:07 -0800261 if (nr < 0) {
262 if (errno == EINTR)
263 continue;
Eric Wongd751dd12016-07-10 08:20:46 +0000264 if (handle_nonblock(fd, POLLIN, errno))
Eric Wongc22f6202016-06-27 03:56:35 +0000265 continue;
Stefan Beller1079c4b2015-12-15 16:04:07 -0800266 }
Linus Torvalds112db552008-06-22 12:19:25 -0700267 return nr;
268 }
269}
270
271/*
272 * xwrite() is the same a write(), but it automatically restarts write()
273 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
274 * GUARANTEE that "len" bytes is written even if the operation is successful.
275 */
276ssize_t xwrite(int fd, const void *buf, size_t len)
277{
278 ssize_t nr;
Steffen Prohaska0b6806b2013-08-20 08:43:54 +0200279 if (len > MAX_IO_SIZE)
280 len = MAX_IO_SIZE;
Linus Torvalds112db552008-06-22 12:19:25 -0700281 while (1) {
282 nr = write(fd, buf, len);
Eric Wongef1cf012016-06-26 23:21:12 +0000283 if (nr < 0) {
284 if (errno == EINTR)
285 continue;
Eric Wongd751dd12016-07-10 08:20:46 +0000286 if (handle_nonblock(fd, POLLOUT, errno))
Eric Wongef1cf012016-06-26 23:21:12 +0000287 continue;
Eric Wongef1cf012016-06-26 23:21:12 +0000288 }
289
Linus Torvalds112db552008-06-22 12:19:25 -0700290 return nr;
291 }
292}
293
Yiannis Marangos9aa91af2014-04-10 21:54:12 +0300294/*
295 * xpread() is the same as pread(), but it automatically restarts pread()
296 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
297 * NOT GUARANTEE that "len" bytes is read even if the data is available.
298 */
299ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
300{
301 ssize_t nr;
302 if (len > MAX_IO_SIZE)
303 len = MAX_IO_SIZE;
304 while (1) {
305 nr = pread(fd, buf, len, offset);
306 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
307 continue;
308 return nr;
309 }
310}
311
Junio C Hamano559e8402008-07-20 16:13:05 -0700312ssize_t read_in_full(int fd, void *buf, size_t count)
313{
314 char *p = buf;
315 ssize_t total = 0;
316
317 while (count > 0) {
318 ssize_t loaded = xread(fd, p, count);
Jeff King56d7c272011-05-26 12:30:27 -0400319 if (loaded < 0)
320 return -1;
321 if (loaded == 0)
322 return total;
Junio C Hamano559e8402008-07-20 16:13:05 -0700323 count -= loaded;
324 p += loaded;
325 total += loaded;
326 }
327
328 return total;
329}
330
331ssize_t write_in_full(int fd, const void *buf, size_t count)
332{
333 const char *p = buf;
334 ssize_t total = 0;
335
336 while (count > 0) {
337 ssize_t written = xwrite(fd, p, count);
338 if (written < 0)
339 return -1;
340 if (!written) {
341 errno = ENOSPC;
342 return -1;
343 }
344 count -= written;
345 p += written;
346 total += written;
347 }
348
349 return total;
350}
351
Yiannis Marangos426ddee2014-04-10 21:31:21 +0300352ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
353{
354 char *p = buf;
355 ssize_t total = 0;
356
357 while (count > 0) {
358 ssize_t loaded = xpread(fd, p, count, offset);
359 if (loaded < 0)
360 return -1;
361 if (loaded == 0)
362 return total;
363 count -= loaded;
364 p += loaded;
365 total += loaded;
366 offset += loaded;
367 }
368
369 return total;
370}
371
Linus Torvalds112db552008-06-22 12:19:25 -0700372int xdup(int fd)
373{
374 int ret = dup(fd);
375 if (ret < 0)
Thomas Rastd824cbb2009-06-27 17:58:46 +0200376 die_errno("dup failed");
Linus Torvalds112db552008-06-22 12:19:25 -0700377 return ret;
378}
379
Paul Tan260eec22015-08-04 21:51:23 +0800380/**
381 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
382 */
383FILE *xfopen(const char *path, const char *mode)
384{
385 for (;;) {
386 FILE *fp = fopen(path, mode);
387 if (fp)
388 return fp;
389 if (errno == EINTR)
390 continue;
391
392 if (*mode && mode[1] == '+')
393 die_errno(_("could not open '%s' for reading and writing"), path);
394 else if (*mode == 'w' || *mode == 'a')
395 die_errno(_("could not open '%s' for writing"), path);
396 else
397 die_errno(_("could not open '%s' for reading"), path);
398 }
399}
400
Linus Torvalds112db552008-06-22 12:19:25 -0700401FILE *xfdopen(int fd, const char *mode)
402{
403 FILE *stream = fdopen(fd, mode);
404 if (stream == NULL)
Thomas Rastd824cbb2009-06-27 17:58:46 +0200405 die_errno("Out of memory? fdopen failed");
Linus Torvalds112db552008-06-22 12:19:25 -0700406 return stream;
407}
408
Johannes Schindelin79d75822016-01-06 14:09:43 +0100409FILE *fopen_for_writing(const char *path)
410{
411 FILE *ret = fopen(path, "w");
412
413 if (!ret && errno == EPERM) {
414 if (!unlink(path))
415 ret = fopen(path, "w");
416 else
417 errno = EPERM;
418 }
419 return ret;
420}
421
Nguyễn Thái Ngọc Duy382fb072017-05-08 17:40:37 +0700422static void warn_on_inaccessible(const char *path)
423{
424 warning_errno(_("unable to access '%s'"), path);
425}
426
Nguyễn Thái Ngọc Duy11dc1fc2017-05-03 17:16:49 +0700427int warn_on_fopen_errors(const char *path)
428{
429 if (errno != ENOENT && errno != ENOTDIR) {
430 warn_on_inaccessible(path);
431 return -1;
432 }
433
434 return 0;
435}
436
Nguyễn Thái Ngọc Duye9d983f2017-05-03 17:16:50 +0700437FILE *fopen_or_warn(const char *path, const char *mode)
438{
439 FILE *fp = fopen(path, mode);
440
441 if (fp)
442 return fp;
443
444 warn_on_fopen_errors(path);
445 return NULL;
446}
447
Brandon Williamseb78e232018-02-14 10:59:56 -0800448int xmkstemp(char *filename_template)
Linus Torvalds112db552008-06-22 12:19:25 -0700449{
450 int fd;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100451 char origtemplate[PATH_MAX];
Brandon Williamseb78e232018-02-14 10:59:56 -0800452 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
Linus Torvalds112db552008-06-22 12:19:25 -0700453
Brandon Williamseb78e232018-02-14 10:59:56 -0800454 fd = mkstemp(filename_template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100455 if (fd < 0) {
456 int saved_errno = errno;
457 const char *nonrelative_template;
458
Brandon Williamseb78e232018-02-14 10:59:56 -0800459 if (strlen(filename_template) != strlen(origtemplate))
460 filename_template = origtemplate;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100461
Brandon Williamseb78e232018-02-14 10:59:56 -0800462 nonrelative_template = absolute_path(filename_template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100463 errno = saved_errno;
464 die_errno("Unable to create temporary file '%s'",
465 nonrelative_template);
466 }
Linus Torvalds112db552008-06-22 12:19:25 -0700467 return fd;
468}
Linus Torvalds39c68542009-01-07 19:54:47 -0800469
Jonathan Nieder33f23932010-11-06 06:46:31 -0500470/* Adapted from libiberty's mkstemp.c. */
471
472#undef TMP_MAX
473#define TMP_MAX 16384
474
475int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
476{
477 static const char letters[] =
478 "abcdefghijklmnopqrstuvwxyz"
479 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
480 "0123456789";
481 static const int num_letters = 62;
482 uint64_t value;
483 struct timeval tv;
Brandon Williamseb78e232018-02-14 10:59:56 -0800484 char *filename_template;
Jonathan Nieder33f23932010-11-06 06:46:31 -0500485 size_t len;
486 int fd, count;
487
488 len = strlen(pattern);
489
490 if (len < 6 + suffix_len) {
491 errno = EINVAL;
492 return -1;
493 }
494
495 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
496 errno = EINVAL;
497 return -1;
498 }
499
500 /*
501 * Replace pattern's XXXXXX characters with randomness.
502 * Try TMP_MAX different filenames.
503 */
504 gettimeofday(&tv, NULL);
505 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
Brandon Williamseb78e232018-02-14 10:59:56 -0800506 filename_template = &pattern[len - 6 - suffix_len];
Jonathan Nieder33f23932010-11-06 06:46:31 -0500507 for (count = 0; count < TMP_MAX; ++count) {
508 uint64_t v = value;
509 /* Fill in the random bits. */
Brandon Williamseb78e232018-02-14 10:59:56 -0800510 filename_template[0] = letters[v % num_letters]; v /= num_letters;
511 filename_template[1] = letters[v % num_letters]; v /= num_letters;
512 filename_template[2] = letters[v % num_letters]; v /= num_letters;
513 filename_template[3] = letters[v % num_letters]; v /= num_letters;
514 filename_template[4] = letters[v % num_letters]; v /= num_letters;
515 filename_template[5] = letters[v % num_letters]; v /= num_letters;
Jonathan Nieder33f23932010-11-06 06:46:31 -0500516
517 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
Dale R. Worleya2cb86c2013-07-12 10:58:35 +0200518 if (fd >= 0)
Jonathan Nieder33f23932010-11-06 06:46:31 -0500519 return fd;
520 /*
521 * Fatal error (EPERM, ENOSPC etc).
522 * It doesn't make sense to loop.
523 */
524 if (errno != EEXIST)
525 break;
526 /*
527 * This is a random value. It is only necessary that
528 * the next TMP_MAX values generated by adding 7777 to
529 * VALUE are different with (module 2^32).
530 */
531 value += 7777;
532 }
533 /* We return the null string if we can't find a unique file name. */
534 pattern[0] = '\0';
535 return -1;
536}
537
538int git_mkstemp_mode(char *pattern, int mode)
539{
540 /* mkstemp is just mkstemps with no suffix */
541 return git_mkstemps_mode(pattern, 0, mode);
542}
543
Brandon Williamseb78e232018-02-14 10:59:56 -0800544int xmkstemp_mode(char *filename_template, int mode)
Matthieu Moyb862b612010-02-22 23:32:13 +0100545{
546 int fd;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100547 char origtemplate[PATH_MAX];
Brandon Williamseb78e232018-02-14 10:59:56 -0800548 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
Matthieu Moyb862b612010-02-22 23:32:13 +0100549
Brandon Williamseb78e232018-02-14 10:59:56 -0800550 fd = git_mkstemp_mode(filename_template, mode);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100551 if (fd < 0) {
552 int saved_errno = errno;
553 const char *nonrelative_template;
554
Brandon Williamseb78e232018-02-14 10:59:56 -0800555 if (!filename_template[0])
556 filename_template = origtemplate;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100557
Brandon Williamseb78e232018-02-14 10:59:56 -0800558 nonrelative_template = absolute_path(filename_template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100559 errno = saved_errno;
560 die_errno("Unable to create temporary file '%s'",
561 nonrelative_template);
562 }
Matthieu Moyb862b612010-02-22 23:32:13 +0100563 return fd;
564}
565
Peter Collingbourne10e13ec2010-03-26 15:25:32 +0000566static int warn_if_unremovable(const char *op, const char *file, int rc)
Alex Riesenfc71db32009-04-29 23:21:46 +0200567{
Ronnie Sahlberg1054af72014-07-16 11:01:18 -0700568 int err;
569 if (!rc || errno == ENOENT)
570 return 0;
571 err = errno;
Simon Ruderich0a288d12017-11-01 15:44:44 +0100572 warning_errno("unable to %s '%s'", op, file);
Ronnie Sahlberg1054af72014-07-16 11:01:18 -0700573 errno = err;
Alex Riesenfc71db32009-04-29 23:21:46 +0200574 return rc;
575}
576
Ronnie Sahlberg9ccc0c02014-07-16 11:20:36 -0700577int unlink_or_msg(const char *file, struct strbuf *err)
578{
579 int rc = unlink(file);
580
581 assert(err);
582
583 if (!rc || errno == ENOENT)
584 return 0;
585
Simon Ruderich0a288d12017-11-01 15:44:44 +0100586 strbuf_addf(err, "unable to unlink '%s': %s",
Ronnie Sahlberg9ccc0c02014-07-16 11:20:36 -0700587 file, strerror(errno));
588 return -1;
589}
590
Peter Collingbourne10e13ec2010-03-26 15:25:32 +0000591int unlink_or_warn(const char *file)
592{
593 return warn_if_unremovable("unlink", file, unlink(file));
594}
Peter Collingbourned1723292010-03-26 15:25:33 +0000595
596int rmdir_or_warn(const char *file)
597{
598 return warn_if_unremovable("rmdir", file, rmdir(file));
599}
Peter Collingbourne80d706a2010-03-26 15:25:34 +0000600
601int remove_or_warn(unsigned int mode, const char *file)
602{
603 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
604}
Jeff King2f705872012-05-21 19:10:20 -0400605
Jonathan Nieder4698c8f2013-04-12 14:03:18 -0700606static int access_error_is_ok(int err, unsigned flag)
607{
Junio C Hamanoc7054202017-05-30 09:23:33 +0900608 return (is_missing_file_error(err) ||
609 ((flag & ACCESS_EACCES_OK) && err == EACCES));
Jonathan Nieder4698c8f2013-04-12 14:03:18 -0700610}
611
612int access_or_warn(const char *path, int mode, unsigned flag)
Jeff Kingba8bd832012-08-21 02:10:59 -0400613{
614 int ret = access(path, mode);
Jonathan Nieder4698c8f2013-04-12 14:03:18 -0700615 if (ret && !access_error_is_ok(errno, flag))
Junio C Hamano55b38a42012-08-21 14:52:07 -0700616 warn_on_inaccessible(path);
Jeff Kingba8bd832012-08-21 02:10:59 -0400617 return ret;
618}
619
Jonathan Nieder4698c8f2013-04-12 14:03:18 -0700620int access_or_die(const char *path, int mode, unsigned flag)
Jonathan Nieder96b9e0e2012-10-13 17:04:02 -0700621{
622 int ret = access(path, mode);
Jonathan Nieder4698c8f2013-04-12 14:03:18 -0700623 if (ret && !access_error_is_ok(errno, flag))
Jonathan Nieder96b9e0e2012-10-13 17:04:02 -0700624 die_errno(_("unable to access '%s'"), path);
625 return ret;
626}
627
René Scharfeaa14e982014-07-28 20:29:50 +0200628char *xgetcwd(void)
629{
630 struct strbuf sb = STRBUF_INIT;
631 if (strbuf_getcwd(&sb))
632 die_errno(_("unable to get current working directory"));
633 return strbuf_detach(&sb, NULL);
634}
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700635
Jeff King7b03c892015-09-24 17:05:37 -0400636int xsnprintf(char *dst, size_t max, const char *fmt, ...)
637{
638 va_list ap;
639 int len;
640
641 va_start(ap, fmt);
642 len = vsnprintf(dst, max, fmt, ap);
643 va_end(ap);
644
645 if (len < 0)
Johannes Schindelin033abf92018-05-02 11:38:39 +0200646 BUG("your snprintf is broken");
Jeff King7b03c892015-09-24 17:05:37 -0400647 if (len >= max)
Johannes Schindelin033abf92018-05-02 11:38:39 +0200648 BUG("attempt to snprintf into too-small buffer");
Jeff King7b03c892015-09-24 17:05:37 -0400649 return len;
650}
651
Jeff King52563d72016-07-08 05:12:22 -0400652void write_file_buf(const char *path, const char *buf, size_t len)
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700653{
Jeff King52563d72016-07-08 05:12:22 -0400654 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
Jeff King06f46f22017-09-13 13:16:03 -0400655 if (write_in_full(fd, buf, len) < 0)
Simon Ruderich0a288d12017-11-01 15:44:44 +0100656 die_errno(_("could not write to '%s'"), path);
Jeff King52563d72016-07-08 05:12:22 -0400657 if (close(fd))
Simon Ruderich0a288d12017-11-01 15:44:44 +0100658 die_errno(_("could not close '%s'"), path);
Jeff King52563d72016-07-08 05:12:22 -0400659}
660
Jeff Kingef223182016-07-08 05:09:34 -0400661void write_file(const char *path, const char *fmt, ...)
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700662{
Jeff Kingef223182016-07-08 05:09:34 -0400663 va_list params;
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700664 struct strbuf sb = STRBUF_INIT;
Jeff Kingef223182016-07-08 05:09:34 -0400665
666 va_start(params, fmt);
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700667 strbuf_vaddf(&sb, fmt, params);
Jeff Kingef223182016-07-08 05:09:34 -0400668 va_end(params);
669
Junio C Hamanoe7ffa382015-08-24 09:39:48 -0700670 strbuf_complete_line(&sb);
Jeff King52563d72016-07-08 05:12:22 -0400671
672 write_file_buf(path, sb.buf, sb.len);
Nguyễn Thái Ngọc Duy316e53e2014-11-30 15:24:45 +0700673 strbuf_release(&sb);
Junio C Hamano12d6ce12015-08-24 13:03:07 -0700674}
675
Johannes Sixt2024d312015-06-05 21:45:05 +0200676void sleep_millisec(int millisec)
677{
678 poll(NULL, 0, millisec);
679}
David Turner5781a9a2017-04-18 17:57:43 -0400680
681int xgethostname(char *buf, size_t len)
682{
683 /*
684 * If the full hostname doesn't fit in buf, POSIX does not
685 * specify whether the buffer will be null-terminated, so to
686 * be safe, do it ourselves.
687 */
688 int ret = gethostname(buf, len);
689 if (!ret)
690 buf[len - 1] = 0;
691 return ret;
692}
Pranit Bauvae3b1e3b2019-01-02 07:38:32 -0800693
694int is_empty_or_missing_file(const char *filename)
695{
696 struct stat st;
697
698 if (stat(filename, &st) < 0) {
699 if (errno == ENOENT)
700 return 1;
701 die_errno(_("could not stat %s"), filename);
702 }
703
704 return !st.st_size;
705}