@matheusbsbs / matheus-bagliano / commits / b11b7e13f4
Fork 0

Add generic 'strbuf_readlink()' helper function

It was already what 'git apply' did in read_old_data(), just export it as a real function, and make it be more generic. In particular, this handles the case of the lstat() st_size data not matching the readlink() return value properly (which apparently happens at least on NTFS under Linux). But as a result of this you could also use the new function without even knowing how big the link is going to be, and it will allocate an appropriately sized buffer. So we pass in the st_size of the link as just a hint, rather than a fixed requirement. Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Linus Torvalds committed Dec 17, 2008 at 09:36 UTC b11b7e13f48ee283738e21fea9f775cd40ca0562
3 files changed +30 -4
builtin-apply.c
+2 -4
@@ -1559,10 +1559,8 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1559 {
1560 switch (st->st_mode & S_IFMT) {
1561 case S_IFLNK:
1562 - strbuf_grow(buf, st->st_size);
1563 - if (readlink(path, buf->buf, st->st_size) != st->st_size)
1564 - return -1;
1565 - strbuf_setlen(buf, st->st_size);
1562 + if (strbuf_readlink(buf, path, st->st_size) < 0)
1563 + return error("unable to read symlink %s", path);
1564 return 0;
1565 case S_IFREG:
1566 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
strbuf.c
+27
@@ -288,6 +288,33 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
288 return sb->len - oldlen;
289 }
290
291 +#define STRBUF_MAXLINK (2*PATH_MAX)
292 +
293 +int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
294 +{
295 + if (hint < 32)
296 + hint = 32;
297 +
298 + while (hint < STRBUF_MAXLINK) {
299 + int len;
300 +
301 + strbuf_grow(sb, hint);
302 + len = readlink(path, sb->buf, hint);
303 + if (len < 0) {
304 + if (errno != ERANGE)
305 + break;
306 + } else if (len < hint) {
307 + strbuf_setlen(sb, len);
308 + return 0;
309 + }
310 +
311 + /* .. the buffer was too small - try again */
312 + hint *= 2;
313 + }
314 + strbuf_release(sb);
315 + return -1;
316 +}
317 +
318 int strbuf_getline(struct strbuf *sb, FILE *fp, int term)
319 {
320 int ch;
strbuf.h
+1
@@ -124,6 +124,7 @@ extern size_t strbuf_fread(struct strbuf *, size_t, FILE *);
124 /* XXX: if read fails, any partial read is undone */
125 extern ssize_t strbuf_read(struct strbuf *, int fd, size_t hint);
126 extern int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint);
127 +extern int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint);
128
129 extern int strbuf_getline(struct strbuf *, FILE *, int);
130