blob: bac59d2c41bae7441038b30728c696b6280f4c2d [file] [log] [blame]
Linus Torvalds112db552008-06-22 12:19:25 -07001/*
2 * Various trivial helper wrappers around standard functions
3 */
4#include "cache.h"
5
Jonathan Niedere0500292010-11-06 14:00:38 -05006static void do_nothing(size_t size)
Nicolas Pitrea9a74632010-03-24 16:22:34 -04007{
Nicolas Pitrea9a74632010-03-24 16:22:34 -04008}
9
Jonathan Niedere0500292010-11-06 14:00:38 -050010static void (*try_to_free_routine)(size_t size) = do_nothing;
Nicolas Pitrea9a74632010-03-24 16:22:34 -040011
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070012static void memory_limit_check(size_t size)
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 }
19 if (limit && size > limit)
20 die("attempting to allocate %"PRIuMAX" over limit %d",
21 (intmax_t)size, limit);
22}
23
Johannes Sixt851c34b2010-05-08 17:13:49 +020024try_to_free_t set_try_to_free_routine(try_to_free_t routine)
Nicolas Pitrea9a74632010-03-24 16:22:34 -040025{
Johannes Sixt851c34b2010-05-08 17:13:49 +020026 try_to_free_t old = try_to_free_routine;
Junio C Hamano00b0d7f2010-12-21 09:24:18 -080027 if (!routine)
28 routine = do_nothing;
Johannes Sixt851c34b2010-05-08 17:13:49 +020029 try_to_free_routine = routine;
30 return old;
Nicolas Pitrea9a74632010-03-24 16:22:34 -040031}
32
Linus Torvalds112db552008-06-22 12:19:25 -070033char *xstrdup(const char *str)
34{
35 char *ret = strdup(str);
36 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -040037 try_to_free_routine(strlen(str) + 1);
Linus Torvalds112db552008-06-22 12:19:25 -070038 ret = strdup(str);
39 if (!ret)
40 die("Out of memory, strdup failed");
41 }
42 return ret;
43}
44
45void *xmalloc(size_t size)
46{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070047 void *ret;
48
49 memory_limit_check(size);
50 ret = malloc(size);
Linus Torvalds112db552008-06-22 12:19:25 -070051 if (!ret && !size)
52 ret = malloc(1);
53 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -040054 try_to_free_routine(size);
Linus Torvalds112db552008-06-22 12:19:25 -070055 ret = malloc(size);
56 if (!ret && !size)
57 ret = malloc(1);
58 if (!ret)
Matthieu Moy8bd9fd52010-08-20 17:09:51 +020059 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
60 (unsigned long)size);
Linus Torvalds112db552008-06-22 12:19:25 -070061 }
62#ifdef XMALLOC_POISON
63 memset(ret, 0xA5, size);
64#endif
65 return ret;
66}
67
Ilari Liusvaara5bf92192010-01-26 20:24:12 +020068void *xmallocz(size_t size)
69{
70 void *ret;
Jonathan Nieder1368f652010-10-10 21:59:26 -050071 if (unsigned_add_overflows(size, 1))
Ilari Liusvaara5bf92192010-01-26 20:24:12 +020072 die("Data too large to fit into virtual memory space.");
73 ret = xmalloc(size + 1);
74 ((char*)ret)[size] = 0;
75 return ret;
76}
77
Linus Torvalds112db552008-06-22 12:19:25 -070078/*
79 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
80 * "data" to the allocated memory, zero terminates the allocated memory,
81 * and returns a pointer to the allocated memory. If the allocation fails,
82 * the program dies.
83 */
84void *xmemdupz(const void *data, size_t len)
85{
Ilari Liusvaara5bf92192010-01-26 20:24:12 +020086 return memcpy(xmallocz(len), data, len);
Linus Torvalds112db552008-06-22 12:19:25 -070087}
88
89char *xstrndup(const char *str, size_t len)
90{
91 char *p = memchr(str, '\0', len);
92 return xmemdupz(str, p ? p - str : len);
93}
94
95void *xrealloc(void *ptr, size_t size)
96{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +070097 void *ret;
98
99 memory_limit_check(size);
100 ret = realloc(ptr, size);
Linus Torvalds112db552008-06-22 12:19:25 -0700101 if (!ret && !size)
102 ret = realloc(ptr, 1);
103 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -0400104 try_to_free_routine(size);
Linus Torvalds112db552008-06-22 12:19:25 -0700105 ret = realloc(ptr, size);
106 if (!ret && !size)
107 ret = realloc(ptr, 1);
108 if (!ret)
109 die("Out of memory, realloc failed");
110 }
111 return ret;
112}
113
114void *xcalloc(size_t nmemb, size_t size)
115{
Nguyễn Thái Ngọc Duyd41489a2012-03-07 17:54:16 +0700116 void *ret;
117
118 memory_limit_check(size * nmemb);
119 ret = calloc(nmemb, size);
Linus Torvalds112db552008-06-22 12:19:25 -0700120 if (!ret && (!nmemb || !size))
121 ret = calloc(1, 1);
122 if (!ret) {
Nicolas Pitrea9a74632010-03-24 16:22:34 -0400123 try_to_free_routine(nmemb * size);
Linus Torvalds112db552008-06-22 12:19:25 -0700124 ret = calloc(nmemb, size);
125 if (!ret && (!nmemb || !size))
126 ret = calloc(1, 1);
127 if (!ret)
128 die("Out of memory, calloc failed");
129 }
130 return ret;
131}
132
Linus Torvalds112db552008-06-22 12:19:25 -0700133/*
134 * xread() is the same a read(), but it automatically restarts read()
135 * operations with a recoverable error (EAGAIN and EINTR). xread()
136 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
137 */
138ssize_t xread(int fd, void *buf, size_t len)
139{
140 ssize_t nr;
141 while (1) {
142 nr = read(fd, buf, len);
143 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
144 continue;
145 return nr;
146 }
147}
148
149/*
150 * xwrite() is the same a write(), but it automatically restarts write()
151 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
152 * GUARANTEE that "len" bytes is written even if the operation is successful.
153 */
154ssize_t xwrite(int fd, const void *buf, size_t len)
155{
156 ssize_t nr;
157 while (1) {
158 nr = write(fd, buf, len);
159 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
160 continue;
161 return nr;
162 }
163}
164
Junio C Hamano559e8402008-07-20 16:13:05 -0700165ssize_t read_in_full(int fd, void *buf, size_t count)
166{
167 char *p = buf;
168 ssize_t total = 0;
169
170 while (count > 0) {
171 ssize_t loaded = xread(fd, p, count);
Jeff King56d7c272011-05-26 12:30:27 -0400172 if (loaded < 0)
173 return -1;
174 if (loaded == 0)
175 return total;
Junio C Hamano559e8402008-07-20 16:13:05 -0700176 count -= loaded;
177 p += loaded;
178 total += loaded;
179 }
180
181 return total;
182}
183
184ssize_t write_in_full(int fd, const void *buf, size_t count)
185{
186 const char *p = buf;
187 ssize_t total = 0;
188
189 while (count > 0) {
190 ssize_t written = xwrite(fd, p, count);
191 if (written < 0)
192 return -1;
193 if (!written) {
194 errno = ENOSPC;
195 return -1;
196 }
197 count -= written;
198 p += written;
199 total += written;
200 }
201
202 return total;
203}
204
Linus Torvalds112db552008-06-22 12:19:25 -0700205int xdup(int fd)
206{
207 int ret = dup(fd);
208 if (ret < 0)
Thomas Rastd824cbb2009-06-27 17:58:46 +0200209 die_errno("dup failed");
Linus Torvalds112db552008-06-22 12:19:25 -0700210 return ret;
211}
212
213FILE *xfdopen(int fd, const char *mode)
214{
215 FILE *stream = fdopen(fd, mode);
216 if (stream == NULL)
Thomas Rastd824cbb2009-06-27 17:58:46 +0200217 die_errno("Out of memory? fdopen failed");
Linus Torvalds112db552008-06-22 12:19:25 -0700218 return stream;
219}
220
221int xmkstemp(char *template)
222{
223 int fd;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100224 char origtemplate[PATH_MAX];
225 strlcpy(origtemplate, template, sizeof(origtemplate));
Linus Torvalds112db552008-06-22 12:19:25 -0700226
227 fd = mkstemp(template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100228 if (fd < 0) {
229 int saved_errno = errno;
230 const char *nonrelative_template;
231
Junio C Hamanof7be59b2012-12-18 12:51:35 -0800232 if (strlen(template) != strlen(origtemplate))
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100233 template = origtemplate;
234
Carlos Martín Nietoe2a57aa2011-03-17 12:26:46 +0100235 nonrelative_template = absolute_path(template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100236 errno = saved_errno;
237 die_errno("Unable to create temporary file '%s'",
238 nonrelative_template);
239 }
Linus Torvalds112db552008-06-22 12:19:25 -0700240 return fd;
241}
Linus Torvalds39c68542009-01-07 19:54:47 -0800242
Jonathan Nieder33f23932010-11-06 06:46:31 -0500243/* git_mkstemp() - create tmp file honoring TMPDIR variable */
244int git_mkstemp(char *path, size_t len, const char *template)
245{
246 const char *tmp;
247 size_t n;
248
249 tmp = getenv("TMPDIR");
250 if (!tmp)
251 tmp = "/tmp";
252 n = snprintf(path, len, "%s/%s", tmp, template);
253 if (len <= n) {
254 errno = ENAMETOOLONG;
255 return -1;
256 }
257 return mkstemp(path);
258}
259
260/* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
261int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
262{
263 const char *tmp;
264 size_t n;
265
266 tmp = getenv("TMPDIR");
267 if (!tmp)
268 tmp = "/tmp";
269 n = snprintf(path, len, "%s/%s", tmp, template);
270 if (len <= n) {
271 errno = ENAMETOOLONG;
272 return -1;
273 }
274 return mkstemps(path, suffix_len);
275}
276
277/* Adapted from libiberty's mkstemp.c. */
278
279#undef TMP_MAX
280#define TMP_MAX 16384
281
282int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
283{
284 static const char letters[] =
285 "abcdefghijklmnopqrstuvwxyz"
286 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
287 "0123456789";
288 static const int num_letters = 62;
289 uint64_t value;
290 struct timeval tv;
291 char *template;
292 size_t len;
293 int fd, count;
294
295 len = strlen(pattern);
296
297 if (len < 6 + suffix_len) {
298 errno = EINVAL;
299 return -1;
300 }
301
302 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
303 errno = EINVAL;
304 return -1;
305 }
306
307 /*
308 * Replace pattern's XXXXXX characters with randomness.
309 * Try TMP_MAX different filenames.
310 */
311 gettimeofday(&tv, NULL);
312 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
313 template = &pattern[len - 6 - suffix_len];
314 for (count = 0; count < TMP_MAX; ++count) {
315 uint64_t v = value;
316 /* Fill in the random bits. */
317 template[0] = letters[v % num_letters]; v /= num_letters;
318 template[1] = letters[v % num_letters]; v /= num_letters;
319 template[2] = letters[v % num_letters]; v /= num_letters;
320 template[3] = letters[v % num_letters]; v /= num_letters;
321 template[4] = letters[v % num_letters]; v /= num_letters;
322 template[5] = letters[v % num_letters]; v /= num_letters;
323
324 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
325 if (fd > 0)
326 return fd;
327 /*
328 * Fatal error (EPERM, ENOSPC etc).
329 * It doesn't make sense to loop.
330 */
331 if (errno != EEXIST)
332 break;
333 /*
334 * This is a random value. It is only necessary that
335 * the next TMP_MAX values generated by adding 7777 to
336 * VALUE are different with (module 2^32).
337 */
338 value += 7777;
339 }
340 /* We return the null string if we can't find a unique file name. */
341 pattern[0] = '\0';
342 return -1;
343}
344
345int git_mkstemp_mode(char *pattern, int mode)
346{
347 /* mkstemp is just mkstemps with no suffix */
348 return git_mkstemps_mode(pattern, 0, mode);
349}
350
351int gitmkstemps(char *pattern, int suffix_len)
352{
353 return git_mkstemps_mode(pattern, suffix_len, 0600);
354}
355
Matthieu Moyb862b612010-02-22 23:32:13 +0100356int xmkstemp_mode(char *template, int mode)
357{
358 int fd;
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100359 char origtemplate[PATH_MAX];
360 strlcpy(origtemplate, template, sizeof(origtemplate));
Matthieu Moyb862b612010-02-22 23:32:13 +0100361
362 fd = git_mkstemp_mode(template, mode);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100363 if (fd < 0) {
364 int saved_errno = errno;
365 const char *nonrelative_template;
366
367 if (!template[0])
368 template = origtemplate;
369
Carlos Martín Nietoe2a57aa2011-03-17 12:26:46 +0100370 nonrelative_template = absolute_path(template);
Arnout Engelen6cf6bb32010-12-18 22:28:00 +0100371 errno = saved_errno;
372 die_errno("Unable to create temporary file '%s'",
373 nonrelative_template);
374 }
Matthieu Moyb862b612010-02-22 23:32:13 +0100375 return fd;
376}
377
Peter Collingbourne10e13ec2010-03-26 15:25:32 +0000378static int warn_if_unremovable(const char *op, const char *file, int rc)
Alex Riesenfc71db32009-04-29 23:21:46 +0200379{
Alex Riesenfc71db32009-04-29 23:21:46 +0200380 if (rc < 0) {
381 int err = errno;
382 if (ENOENT != err) {
Peter Collingbourne10e13ec2010-03-26 15:25:32 +0000383 warning("unable to %s %s: %s",
384 op, file, strerror(errno));
Alex Riesenfc71db32009-04-29 23:21:46 +0200385 errno = err;
386 }
387 }
388 return rc;
389}
390
Peter Collingbourne10e13ec2010-03-26 15:25:32 +0000391int unlink_or_warn(const char *file)
392{
393 return warn_if_unremovable("unlink", file, unlink(file));
394}
Peter Collingbourned1723292010-03-26 15:25:33 +0000395
396int rmdir_or_warn(const char *file)
397{
398 return warn_if_unremovable("rmdir", file, rmdir(file));
399}
Peter Collingbourne80d706a2010-03-26 15:25:34 +0000400
401int remove_or_warn(unsigned int mode, const char *file)
402{
403 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
404}
Jeff King2f705872012-05-21 19:10:20 -0400405
Junio C Hamano55b38a42012-08-21 14:52:07 -0700406void warn_on_inaccessible(const char *path)
407{
408 warning(_("unable to access '%s': %s"), path, strerror(errno));
409}
410
Jeff Kingba8bd832012-08-21 02:10:59 -0400411int access_or_warn(const char *path, int mode)
412{
413 int ret = access(path, mode);
Jonathan Niedere5c52c92012-10-13 17:03:07 -0700414 if (ret && errno != ENOENT && errno != ENOTDIR)
Junio C Hamano55b38a42012-08-21 14:52:07 -0700415 warn_on_inaccessible(path);
Jeff Kingba8bd832012-08-21 02:10:59 -0400416 return ret;
417}
418
Jonathan Nieder96b9e0e2012-10-13 17:04:02 -0700419int access_or_die(const char *path, int mode)
420{
421 int ret = access(path, mode);
422 if (ret && errno != ENOENT && errno != ENOTDIR)
423 die_errno(_("unable to access '%s'"), path);
424 return ret;
425}
426
Jeff King2f705872012-05-21 19:10:20 -0400427struct passwd *xgetpwuid_self(void)
428{
429 struct passwd *pw;
430
431 errno = 0;
432 pw = getpwuid(getuid());
433 if (!pw)
434 die(_("unable to look up current user in the passwd file: %s"),
435 errno ? strerror(errno) : _("no such user"));
436 return pw;
437}