Merge branch 'bw/use-write-script-in-tests'
[git/git.git] / wrapper.c
CommitLineData
112db553
LT
1/*
2 * Various trivial helper wrappers around standard functions
3 */
4#include "cache.h"
5
e0500293 6static void do_nothing(size_t size)
a9a74636 7{
a9a74636
NP
8}
9
e0500293 10static void (*try_to_free_routine)(size_t size) = do_nothing;
a9a74636 11
f8bb1d94 12static int memory_limit_check(size_t size, int gentle)
d41489a6
NTND
13{
14 static int limit = -1;
15 if (limit == -1) {
16 const char *env = getenv("GIT_ALLOC_LIMIT");
17 limit = env ? atoi(env) * 1024 : 0;
18 }
f8bb1d94
NTND
19 if (limit && size > limit) {
20 if (gentle) {
21 error("attempting to allocate %"PRIuMAX" over limit %d",
22 (intmax_t)size, limit);
23 return -1;
24 } else
25 die("attempting to allocate %"PRIuMAX" over limit %d",
26 (intmax_t)size, limit);
27 }
28 return 0;
d41489a6
NTND
29}
30
851c34b0 31try_to_free_t set_try_to_free_routine(try_to_free_t routine)
a9a74636 32{
851c34b0 33 try_to_free_t old = try_to_free_routine;
00b0d7f7
JH
34 if (!routine)
35 routine = do_nothing;
851c34b0
JS
36 try_to_free_routine = routine;
37 return old;
a9a74636
NP
38}
39
112db553
LT
40char *xstrdup(const char *str)
41{
42 char *ret = strdup(str);
43 if (!ret) {
a9a74636 44 try_to_free_routine(strlen(str) + 1);
112db553
LT
45 ret = strdup(str);
46 if (!ret)
47 die("Out of memory, strdup failed");
48 }
49 return ret;
50}
51
f8bb1d94 52static void *do_xmalloc(size_t size, int gentle)
112db553 53{
d41489a6
NTND
54 void *ret;
55
f8bb1d94
NTND
56 if (memory_limit_check(size, gentle))
57 return NULL;
d41489a6 58 ret = malloc(size);
112db553
LT
59 if (!ret && !size)
60 ret = malloc(1);
61 if (!ret) {
a9a74636 62 try_to_free_routine(size);
112db553
LT
63 ret = malloc(size);
64 if (!ret && !size)
65 ret = malloc(1);
f8bb1d94
NTND
66 if (!ret) {
67 if (!gentle)
68 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
69 (unsigned long)size);
70 else {
71 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
72 (unsigned long)size);
73 return NULL;
74 }
75 }
112db553
LT
76 }
77#ifdef XMALLOC_POISON
78 memset(ret, 0xA5, size);
79#endif
80 return ret;
81}
82
f8bb1d94
NTND
83void *xmalloc(size_t size)
84{
85 return do_xmalloc(size, 0);
86}
87
88static void *do_xmallocz(size_t size, int gentle)
5bf9219d
IL
89{
90 void *ret;
f8bb1d94
NTND
91 if (unsigned_add_overflows(size, 1)) {
92 if (gentle) {
93 error("Data too large to fit into virtual memory space.");
94 return NULL;
95 } else
96 die("Data too large to fit into virtual memory space.");
97 }
98 ret = do_xmalloc(size + 1, gentle);
99 if (ret)
100 ((char*)ret)[size] = 0;
5bf9219d
IL
101 return ret;
102}
103
f8bb1d94
NTND
104void *xmallocz(size_t size)
105{
106 return do_xmallocz(size, 0);
107}
108
109void *xmallocz_gently(size_t size)
110{
111 return do_xmallocz(size, 1);
112}
113
112db553
LT
114/*
115 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
116 * "data" to the allocated memory, zero terminates the allocated memory,
117 * and returns a pointer to the allocated memory. If the allocation fails,
118 * the program dies.
119 */
120void *xmemdupz(const void *data, size_t len)
121{
5bf9219d 122 return memcpy(xmallocz(len), data, len);
112db553
LT
123}
124
125char *xstrndup(const char *str, size_t len)
126{
127 char *p = memchr(str, '\0', len);
128 return xmemdupz(str, p ? p - str : len);
129}
130
131void *xrealloc(void *ptr, size_t size)
132{
d41489a6
NTND
133 void *ret;
134
f8bb1d94 135 memory_limit_check(size, 0);
d41489a6 136 ret = realloc(ptr, size);
112db553
LT
137 if (!ret && !size)
138 ret = realloc(ptr, 1);
139 if (!ret) {
a9a74636 140 try_to_free_routine(size);
112db553
LT
141 ret = realloc(ptr, size);
142 if (!ret && !size)
143 ret = realloc(ptr, 1);
144 if (!ret)
145 die("Out of memory, realloc failed");
146 }
147 return ret;
148}
149
150void *xcalloc(size_t nmemb, size_t size)
151{
d41489a6
NTND
152 void *ret;
153
f8bb1d94 154 memory_limit_check(size * nmemb, 0);
d41489a6 155 ret = calloc(nmemb, size);
112db553
LT
156 if (!ret && (!nmemb || !size))
157 ret = calloc(1, 1);
158 if (!ret) {
a9a74636 159 try_to_free_routine(nmemb * size);
112db553
LT
160 ret = calloc(nmemb, size);
161 if (!ret && (!nmemb || !size))
162 ret = calloc(1, 1);
163 if (!ret)
164 die("Out of memory, calloc failed");
165 }
166 return ret;
167}
168
0b6806b9
SP
169/*
170 * Limit size of IO chunks, because huge chunks only cause pain. OS X
171 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
382d20e3 172 * the absence of bugs, large chunks can result in bad latencies when
0b6806b9
SP
173 * you decide to kill the process.
174 */
175#define MAX_IO_SIZE (8*1024*1024)
176
112db553
LT
177/*
178 * xread() is the same a read(), but it automatically restarts read()
179 * operations with a recoverable error (EAGAIN and EINTR). xread()
180 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
181 */
182ssize_t xread(int fd, void *buf, size_t len)
183{
184 ssize_t nr;
0b6806b9
SP
185 if (len > MAX_IO_SIZE)
186 len = MAX_IO_SIZE;
112db553
LT
187 while (1) {
188 nr = read(fd, buf, len);
189 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
190 continue;
191 return nr;
192 }
193}
194
195/*
196 * xwrite() is the same a write(), but it automatically restarts write()
197 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
198 * GUARANTEE that "len" bytes is written even if the operation is successful.
199 */
200ssize_t xwrite(int fd, const void *buf, size_t len)
201{
202 ssize_t nr;
0b6806b9
SP
203 if (len > MAX_IO_SIZE)
204 len = MAX_IO_SIZE;
112db553
LT
205 while (1) {
206 nr = write(fd, buf, len);
207 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
9aa91af0
YM
208 continue;
209 return nr;
210 }
211}
212
213/*
214 * xpread() is the same as pread(), but it automatically restarts pread()
215 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
216 * NOT GUARANTEE that "len" bytes is read even if the data is available.
217 */
218ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
219{
220 ssize_t nr;
221 if (len > MAX_IO_SIZE)
222 len = MAX_IO_SIZE;
223 while (1) {
224 nr = pread(fd, buf, len, offset);
225 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
112db553
LT
226 continue;
227 return nr;
228 }
229}
230
559e840b
JH
231ssize_t read_in_full(int fd, void *buf, size_t count)
232{
233 char *p = buf;
234 ssize_t total = 0;
235
236 while (count > 0) {
237 ssize_t loaded = xread(fd, p, count);
56d7c27a
JK
238 if (loaded < 0)
239 return -1;
240 if (loaded == 0)
241 return total;
559e840b
JH
242 count -= loaded;
243 p += loaded;
244 total += loaded;
245 }
246
247 return total;
248}
249
250ssize_t write_in_full(int fd, const void *buf, size_t count)
251{
252 const char *p = buf;
253 ssize_t total = 0;
254
255 while (count > 0) {
256 ssize_t written = xwrite(fd, p, count);
257 if (written < 0)
258 return -1;
259 if (!written) {
260 errno = ENOSPC;
261 return -1;
262 }
263 count -= written;
264 p += written;
265 total += written;
266 }
267
268 return total;
269}
270
426ddeea
YM
271ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
272{
273 char *p = buf;
274 ssize_t total = 0;
275
276 while (count > 0) {
277 ssize_t loaded = xpread(fd, p, count, offset);
278 if (loaded < 0)
279 return -1;
280 if (loaded == 0)
281 return total;
282 count -= loaded;
283 p += loaded;
284 total += loaded;
285 offset += loaded;
286 }
287
288 return total;
289}
290
112db553
LT
291int xdup(int fd)
292{
293 int ret = dup(fd);
294 if (ret < 0)
d824cbba 295 die_errno("dup failed");
112db553
LT
296 return ret;
297}
298
299FILE *xfdopen(int fd, const char *mode)
300{
301 FILE *stream = fdopen(fd, mode);
302 if (stream == NULL)
d824cbba 303 die_errno("Out of memory? fdopen failed");
112db553
LT
304 return stream;
305}
306
307int xmkstemp(char *template)
308{
309 int fd;
6cf6bb3e
AE
310 char origtemplate[PATH_MAX];
311 strlcpy(origtemplate, template, sizeof(origtemplate));
112db553
LT
312
313 fd = mkstemp(template);
6cf6bb3e
AE
314 if (fd < 0) {
315 int saved_errno = errno;
316 const char *nonrelative_template;
317
f7be59b4 318 if (strlen(template) != strlen(origtemplate))
6cf6bb3e
AE
319 template = origtemplate;
320
e2a57aac 321 nonrelative_template = absolute_path(template);
6cf6bb3e
AE
322 errno = saved_errno;
323 die_errno("Unable to create temporary file '%s'",
324 nonrelative_template);
325 }
112db553
LT
326 return fd;
327}
39c68542 328
33f23936
JN
329/* git_mkstemp() - create tmp file honoring TMPDIR variable */
330int git_mkstemp(char *path, size_t len, const char *template)
331{
332 const char *tmp;
333 size_t n;
334
335 tmp = getenv("TMPDIR");
336 if (!tmp)
337 tmp = "/tmp";
338 n = snprintf(path, len, "%s/%s", tmp, template);
339 if (len <= n) {
340 errno = ENAMETOOLONG;
341 return -1;
342 }
343 return mkstemp(path);
344}
345
346/* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
347int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
348{
349 const char *tmp;
350 size_t n;
351
352 tmp = getenv("TMPDIR");
353 if (!tmp)
354 tmp = "/tmp";
355 n = snprintf(path, len, "%s/%s", tmp, template);
356 if (len <= n) {
357 errno = ENAMETOOLONG;
358 return -1;
359 }
360 return mkstemps(path, suffix_len);
361}
362
363/* Adapted from libiberty's mkstemp.c. */
364
365#undef TMP_MAX
366#define TMP_MAX 16384
367
368int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
369{
370 static const char letters[] =
371 "abcdefghijklmnopqrstuvwxyz"
372 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
373 "0123456789";
374 static const int num_letters = 62;
375 uint64_t value;
376 struct timeval tv;
377 char *template;
378 size_t len;
379 int fd, count;
380
381 len = strlen(pattern);
382
383 if (len < 6 + suffix_len) {
384 errno = EINVAL;
385 return -1;
386 }
387
388 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
389 errno = EINVAL;
390 return -1;
391 }
392
393 /*
394 * Replace pattern's XXXXXX characters with randomness.
395 * Try TMP_MAX different filenames.
396 */
397 gettimeofday(&tv, NULL);
398 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
399 template = &pattern[len - 6 - suffix_len];
400 for (count = 0; count < TMP_MAX; ++count) {
401 uint64_t v = value;
402 /* Fill in the random bits. */
403 template[0] = letters[v % num_letters]; v /= num_letters;
404 template[1] = letters[v % num_letters]; v /= num_letters;
405 template[2] = letters[v % num_letters]; v /= num_letters;
406 template[3] = letters[v % num_letters]; v /= num_letters;
407 template[4] = letters[v % num_letters]; v /= num_letters;
408 template[5] = letters[v % num_letters]; v /= num_letters;
409
410 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
a2cb86c1 411 if (fd >= 0)
33f23936
JN
412 return fd;
413 /*
414 * Fatal error (EPERM, ENOSPC etc).
415 * It doesn't make sense to loop.
416 */
417 if (errno != EEXIST)
418 break;
419 /*
420 * This is a random value. It is only necessary that
421 * the next TMP_MAX values generated by adding 7777 to
422 * VALUE are different with (module 2^32).
423 */
424 value += 7777;
425 }
426 /* We return the null string if we can't find a unique file name. */
427 pattern[0] = '\0';
428 return -1;
429}
430
431int git_mkstemp_mode(char *pattern, int mode)
432{
433 /* mkstemp is just mkstemps with no suffix */
434 return git_mkstemps_mode(pattern, 0, mode);
435}
436
ec145c9c 437#ifdef NO_MKSTEMPS
33f23936
JN
438int gitmkstemps(char *pattern, int suffix_len)
439{
440 return git_mkstemps_mode(pattern, suffix_len, 0600);
441}
ec145c9c 442#endif
33f23936 443
b862b61c
MM
444int xmkstemp_mode(char *template, int mode)
445{
446 int fd;
6cf6bb3e
AE
447 char origtemplate[PATH_MAX];
448 strlcpy(origtemplate, template, sizeof(origtemplate));
b862b61c
MM
449
450 fd = git_mkstemp_mode(template, mode);
6cf6bb3e
AE
451 if (fd < 0) {
452 int saved_errno = errno;
453 const char *nonrelative_template;
454
455 if (!template[0])
456 template = origtemplate;
457
e2a57aac 458 nonrelative_template = absolute_path(template);
6cf6bb3e
AE
459 errno = saved_errno;
460 die_errno("Unable to create temporary file '%s'",
461 nonrelative_template);
462 }
b862b61c
MM
463 return fd;
464}
465
10e13ec8 466static int warn_if_unremovable(const char *op, const char *file, int rc)
fc71db39 467{
fc71db39
AR
468 if (rc < 0) {
469 int err = errno;
470 if (ENOENT != err) {
10e13ec8
PC
471 warning("unable to %s %s: %s",
472 op, file, strerror(errno));
fc71db39
AR
473 errno = err;
474 }
475 }
476 return rc;
477}
478
10e13ec8
PC
479int unlink_or_warn(const char *file)
480{
481 return warn_if_unremovable("unlink", file, unlink(file));
482}
d1723296
PC
483
484int rmdir_or_warn(const char *file)
485{
486 return warn_if_unremovable("rmdir", file, rmdir(file));
487}
80d706af
PC
488
489int remove_or_warn(unsigned int mode, const char *file)
490{
491 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
492}
2f705875 493
55b38a48
JH
494void warn_on_inaccessible(const char *path)
495{
496 warning(_("unable to access '%s': %s"), path, strerror(errno));
497}
498
4698c8fe
JN
499static int access_error_is_ok(int err, unsigned flag)
500{
501 return err == ENOENT || err == ENOTDIR ||
502 ((flag & ACCESS_EACCES_OK) && err == EACCES);
503}
504
505int access_or_warn(const char *path, int mode, unsigned flag)
ba8bd830
JK
506{
507 int ret = access(path, mode);
4698c8fe 508 if (ret && !access_error_is_ok(errno, flag))
55b38a48 509 warn_on_inaccessible(path);
ba8bd830
JK
510 return ret;
511}
512
4698c8fe 513int access_or_die(const char *path, int mode, unsigned flag)
96b9e0e3
JN
514{
515 int ret = access(path, mode);
4698c8fe 516 if (ret && !access_error_is_ok(errno, flag))
96b9e0e3
JN
517 die_errno(_("unable to access '%s'"), path);
518 return ret;
519}
520
2f705875
JK
521struct passwd *xgetpwuid_self(void)
522{
523 struct passwd *pw;
524
525 errno = 0;
526 pw = getpwuid(getuid());
527 if (!pw)
528 die(_("unable to look up current user in the passwd file: %s"),
529 errno ? strerror(errno) : _("no such user"));
530 return pw;
531}
aa14e980
RS
532
533char *xgetcwd(void)
534{
535 struct strbuf sb = STRBUF_INIT;
536 if (strbuf_getcwd(&sb))
537 die_errno(_("unable to get current working directory"));
538 return strbuf_detach(&sb, NULL);
539}