wrapper.c: add xpread() similar to xread()
It is a common mistake to call read(2)/pread(2) and forget to anticipate that they may return error with EAGAIN/EINTR when the system call is interrupted. We have xread() helper to relieve callers of read(2) from having to worry about it; add xpread() helper to do the same for pread(2). Update the caller in the builtin/index-pack.c and the mmap emulation in compat/. Signed-off-by: Yiannis Marangos <yiannis.marangos@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Yiannis Marangos committed
Apr 10, 2014 at 21:54 UTC
9aa91af0361e3c32fde5f8388dee963838308cd6
4 files changed
+21
-4
builtin/index-pack.c
+1
-1
@@ -542,7 +542,7 @@ static void *unpack_data(struct object_entry *obj,
542
543
do {
544
ssize_t n = (len < 64*1024) ? len : 64*1024;
545
- n = pread(pack_fd, inbuf, n, from);
545
+ n = xpread(pack_fd, inbuf, n, from);
546
if (n < 0)
547
die_errno(_("cannot pread pack file"));
548
if (!n)
compat/mmap.c
+1
-3
@@ -14,7 +14,7 @@ void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t of
14
}
15
16
while (n < length) {
17
- ssize_t count = pread(fd, (char *)start + n, length - n, offset + n);
17
+ ssize_t count = xpread(fd, (char *)start + n, length - n, offset + n);
18
19
if (count == 0) {
20
memset((char *)start+n, 0, length-n);
@@ -22,8 +22,6 @@ void *git_mmap(void *start, size_t length, int prot, int flags, int fd, off_t of
22
}
23
24
if (count < 0) {
25
- if (errno == EAGAIN || errno == EINTR)
26
- continue;
25
free(start);
26
errno = EACCES;
27
return MAP_FAILED;
git-compat-util.h
+1
@@ -534,6 +534,7 @@ extern void *xcalloc(size_t nmemb, size_t size);
534
extern void *xmmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);
535
extern ssize_t xread(int fd, void *buf, size_t len);
536
extern ssize_t xwrite(int fd, const void *buf, size_t len);
537
+extern ssize_t xpread(int fd, void *buf, size_t len, off_t offset);
538
extern int xdup(int fd);
539
extern FILE *xfdopen(int fd, const char *mode);
540
extern int xmkstemp(char *template);
wrapper.c
+18
@@ -174,6 +174,24 @@ ssize_t xwrite(int fd, const void *buf, size_t len)
174
}
175
}
176
177
+/*
178
+ * xpread() is the same as pread(), but it automatically restarts pread()
179
+ * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
180
+ * NOT GUARANTEE that "len" bytes is read even if the data is available.
181
+ */
182
+ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
183
+{
184
+ ssize_t nr;
185
+ if (len > MAX_IO_SIZE)
186
+ len = MAX_IO_SIZE;
187
+ while (1) {
188
+ nr = pread(fd, buf, len, offset);
189
+ if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
190
+ continue;
191
+ return nr;
192
+ }
193
+}
194
+
195
ssize_t read_in_full(int fd, void *buf, size_t count)
196
{
197
char *p = buf;