sha1_file: don't convert off_t to size_t too early to avoid potential die()
[git/mingw.git] / wrapper.c
blobc5204f7a07bd011df913c888475746834df79d7d
1 /*
2 * Various trivial helper wrappers around standard functions
3 */
4 #include "cache.h"
6 static void do_nothing(size_t size)
10 static void (*try_to_free_routine)(size_t size) = do_nothing;
12 static void memory_limit_check(size_t size)
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;
20 if (size > limit)
21 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
22 (uintmax_t)size, (uintmax_t)limit);
25 try_to_free_t set_try_to_free_routine(try_to_free_t routine)
27 try_to_free_t old = try_to_free_routine;
28 if (!routine)
29 routine = do_nothing;
30 try_to_free_routine = routine;
31 return old;
34 char *xstrdup(const char *str)
36 char *ret = strdup(str);
37 if (!ret) {
38 try_to_free_routine(strlen(str) + 1);
39 ret = strdup(str);
40 if (!ret)
41 die("Out of memory, strdup failed");
43 return ret;
46 void *xmalloc(size_t size)
48 void *ret;
50 memory_limit_check(size);
51 ret = malloc(size);
52 if (!ret && !size)
53 ret = malloc(1);
54 if (!ret) {
55 try_to_free_routine(size);
56 ret = malloc(size);
57 if (!ret && !size)
58 ret = malloc(1);
59 if (!ret)
60 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
61 (unsigned long)size);
63 #ifdef XMALLOC_POISON
64 memset(ret, 0xA5, size);
65 #endif
66 return ret;
69 void *xmallocz(size_t size)
71 void *ret;
72 if (unsigned_add_overflows(size, 1))
73 die("Data too large to fit into virtual memory space.");
74 ret = xmalloc(size + 1);
75 ((char*)ret)[size] = 0;
76 return ret;
80 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
81 * "data" to the allocated memory, zero terminates the allocated memory,
82 * and returns a pointer to the allocated memory. If the allocation fails,
83 * the program dies.
85 void *xmemdupz(const void *data, size_t len)
87 return memcpy(xmallocz(len), data, len);
90 char *xstrndup(const char *str, size_t len)
92 char *p = memchr(str, '\0', len);
93 return xmemdupz(str, p ? p - str : len);
96 void *xrealloc(void *ptr, size_t size)
98 void *ret;
100 memory_limit_check(size);
101 ret = realloc(ptr, size);
102 if (!ret && !size)
103 ret = realloc(ptr, 1);
104 if (!ret) {
105 try_to_free_routine(size);
106 ret = realloc(ptr, size);
107 if (!ret && !size)
108 ret = realloc(ptr, 1);
109 if (!ret)
110 die("Out of memory, realloc failed");
112 return ret;
115 void *xcalloc(size_t nmemb, size_t size)
117 void *ret;
119 memory_limit_check(size * nmemb);
120 ret = calloc(nmemb, size);
121 if (!ret && (!nmemb || !size))
122 ret = calloc(1, 1);
123 if (!ret) {
124 try_to_free_routine(nmemb * size);
125 ret = calloc(nmemb, size);
126 if (!ret && (!nmemb || !size))
127 ret = calloc(1, 1);
128 if (!ret)
129 die("Out of memory, calloc failed");
131 return ret;
135 * Limit size of IO chunks, because huge chunks only cause pain. OS X
136 * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in
137 * the absence of bugs, large chunks can result in bad latencies when
138 * you decide to kill the process.
140 #define MAX_IO_SIZE (8*1024*1024)
143 * xread() is the same a read(), but it automatically restarts read()
144 * operations with a recoverable error (EAGAIN and EINTR). xread()
145 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
147 ssize_t xread(int fd, void *buf, size_t len)
149 ssize_t nr;
150 if (len > MAX_IO_SIZE)
151 len = MAX_IO_SIZE;
152 while (1) {
153 nr = read(fd, buf, len);
154 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
155 continue;
156 return nr;
161 * xwrite() is the same a write(), but it automatically restarts write()
162 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
163 * GUARANTEE that "len" bytes is written even if the operation is successful.
165 ssize_t xwrite(int fd, const void *buf, size_t len)
167 ssize_t nr;
168 if (len > MAX_IO_SIZE)
169 len = MAX_IO_SIZE;
170 while (1) {
171 nr = write(fd, buf, len);
172 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
173 continue;
174 return nr;
179 * xpread() is the same as pread(), but it automatically restarts pread()
180 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
181 * NOT GUARANTEE that "len" bytes is read even if the data is available.
183 ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
185 ssize_t nr;
186 if (len > MAX_IO_SIZE)
187 len = MAX_IO_SIZE;
188 while (1) {
189 nr = pread(fd, buf, len, offset);
190 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
191 continue;
192 return nr;
196 ssize_t read_in_full(int fd, void *buf, size_t count)
198 char *p = buf;
199 ssize_t total = 0;
201 while (count > 0) {
202 ssize_t loaded = xread(fd, p, count);
203 if (loaded < 0)
204 return -1;
205 if (loaded == 0)
206 return total;
207 count -= loaded;
208 p += loaded;
209 total += loaded;
212 return total;
215 ssize_t write_in_full(int fd, const void *buf, size_t count)
217 const char *p = buf;
218 ssize_t total = 0;
220 while (count > 0) {
221 ssize_t written = xwrite(fd, p, count);
222 if (written < 0)
223 return -1;
224 if (!written) {
225 errno = ENOSPC;
226 return -1;
228 count -= written;
229 p += written;
230 total += written;
233 return total;
236 ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
238 char *p = buf;
239 ssize_t total = 0;
241 while (count > 0) {
242 ssize_t loaded = xpread(fd, p, count, offset);
243 if (loaded < 0)
244 return -1;
245 if (loaded == 0)
246 return total;
247 count -= loaded;
248 p += loaded;
249 total += loaded;
250 offset += loaded;
253 return total;
256 int xdup(int fd)
258 int ret = dup(fd);
259 if (ret < 0)
260 die_errno("dup failed");
261 return ret;
264 FILE *xfdopen(int fd, const char *mode)
266 FILE *stream = fdopen(fd, mode);
267 if (stream == NULL)
268 die_errno("Out of memory? fdopen failed");
269 return stream;
272 int xmkstemp(char *template)
274 int fd;
275 char origtemplate[PATH_MAX];
276 strlcpy(origtemplate, template, sizeof(origtemplate));
278 fd = mkstemp(template);
279 if (fd < 0) {
280 int saved_errno = errno;
281 const char *nonrelative_template;
283 if (strlen(template) != strlen(origtemplate))
284 template = origtemplate;
286 nonrelative_template = absolute_path(template);
287 errno = saved_errno;
288 die_errno("Unable to create temporary file '%s'",
289 nonrelative_template);
291 return fd;
294 /* git_mkstemp() - create tmp file honoring TMPDIR variable */
295 int git_mkstemp(char *path, size_t len, const char *template)
297 const char *tmp;
298 size_t n;
300 tmp = getenv("TMPDIR");
301 if (!tmp)
302 tmp = "/tmp";
303 n = snprintf(path, len, "%s/%s", tmp, template);
304 if (len <= n) {
305 errno = ENAMETOOLONG;
306 return -1;
308 return mkstemp(path);
311 /* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
312 int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
314 const char *tmp;
315 size_t n;
317 tmp = getenv("TMPDIR");
318 if (!tmp)
319 tmp = "/tmp";
320 n = snprintf(path, len, "%s/%s", tmp, template);
321 if (len <= n) {
322 errno = ENAMETOOLONG;
323 return -1;
325 return mkstemps(path, suffix_len);
328 /* Adapted from libiberty's mkstemp.c. */
330 #undef TMP_MAX
331 #define TMP_MAX 16384
333 int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
335 static const char letters[] =
336 "abcdefghijklmnopqrstuvwxyz"
337 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
338 "0123456789";
339 static const int num_letters = 62;
340 uint64_t value;
341 struct timeval tv;
342 char *template;
343 size_t len;
344 int fd, count;
346 len = strlen(pattern);
348 if (len < 6 + suffix_len) {
349 errno = EINVAL;
350 return -1;
353 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
354 errno = EINVAL;
355 return -1;
359 * Replace pattern's XXXXXX characters with randomness.
360 * Try TMP_MAX different filenames.
362 gettimeofday(&tv, NULL);
363 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
364 template = &pattern[len - 6 - suffix_len];
365 for (count = 0; count < TMP_MAX; ++count) {
366 uint64_t v = value;
367 /* Fill in the random bits. */
368 template[0] = letters[v % num_letters]; v /= num_letters;
369 template[1] = letters[v % num_letters]; v /= num_letters;
370 template[2] = letters[v % num_letters]; v /= num_letters;
371 template[3] = letters[v % num_letters]; v /= num_letters;
372 template[4] = letters[v % num_letters]; v /= num_letters;
373 template[5] = letters[v % num_letters]; v /= num_letters;
375 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
376 if (fd >= 0)
377 return fd;
379 * Fatal error (EPERM, ENOSPC etc).
380 * It doesn't make sense to loop.
382 if (errno != EEXIST)
383 break;
385 * This is a random value. It is only necessary that
386 * the next TMP_MAX values generated by adding 7777 to
387 * VALUE are different with (module 2^32).
389 value += 7777;
391 /* We return the null string if we can't find a unique file name. */
392 pattern[0] = '\0';
393 return -1;
396 int git_mkstemp_mode(char *pattern, int mode)
398 /* mkstemp is just mkstemps with no suffix */
399 return git_mkstemps_mode(pattern, 0, mode);
402 #ifdef NO_MKSTEMPS
403 int gitmkstemps(char *pattern, int suffix_len)
405 return git_mkstemps_mode(pattern, suffix_len, 0600);
407 #endif
409 int xmkstemp_mode(char *template, int mode)
411 int fd;
412 char origtemplate[PATH_MAX];
413 strlcpy(origtemplate, template, sizeof(origtemplate));
415 fd = git_mkstemp_mode(template, mode);
416 if (fd < 0) {
417 int saved_errno = errno;
418 const char *nonrelative_template;
420 if (!template[0])
421 template = origtemplate;
423 nonrelative_template = absolute_path(template);
424 errno = saved_errno;
425 die_errno("Unable to create temporary file '%s'",
426 nonrelative_template);
428 return fd;
431 static int warn_if_unremovable(const char *op, const char *file, int rc)
433 if (rc < 0) {
434 int err = errno;
435 if (ENOENT != err) {
436 warning("unable to %s %s: %s",
437 op, file, strerror(errno));
438 errno = err;
441 return rc;
444 int unlink_or_warn(const char *file)
446 return warn_if_unremovable("unlink", file, unlink(file));
449 int rmdir_or_warn(const char *file)
451 return warn_if_unremovable("rmdir", file, rmdir(file));
454 int remove_or_warn(unsigned int mode, const char *file)
456 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
459 void warn_on_inaccessible(const char *path)
461 warning(_("unable to access '%s': %s"), path, strerror(errno));
464 static int access_error_is_ok(int err, unsigned flag)
466 return err == ENOENT || err == ENOTDIR ||
467 ((flag & ACCESS_EACCES_OK) && err == EACCES);
470 int access_or_warn(const char *path, int mode, unsigned flag)
472 int ret = access(path, mode);
473 if (ret && !access_error_is_ok(errno, flag))
474 warn_on_inaccessible(path);
475 return ret;
478 int access_or_die(const char *path, int mode, unsigned flag)
480 int ret = access(path, mode);
481 if (ret && !access_error_is_ok(errno, flag))
482 die_errno(_("unable to access '%s'"), path);
483 return ret;
486 struct passwd *xgetpwuid_self(void)
488 struct passwd *pw;
490 errno = 0;
491 pw = getpwuid(getuid());
492 if (!pw)
493 die(_("unable to look up current user in the passwd file: %s"),
494 errno ? strerror(errno) : _("no such user"));
495 return pw;