From 778b07f73cddd3784acb01dfa5a730656ccd66fb Mon Sep 17 00:00:00 2001 From: Jann Horn Date: Fri, 21 Jun 2013 14:17:28 +0200 Subject: [PATCH 1/1] slurp_fd: add flag for creating 8-nullbytes-padded buffers --- io.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/io.c b/io.c index a7696f9..6c70b97 100644 --- a/io.c +++ b/io.c @@ -66,6 +66,7 @@ PUBLIC_FN ssize_t write_nointr(int fd, void *buf, size_t count, int *last_res) { // this and can specify len_out as NULL. PUBLIC_CONST JH_SLURP_NO_STAT 1 PUBLIC_CONST JH_SLURP_REALLOC 2 /* realloc result block if it saves RAM */ +PUBLIC_CONST JH_SLURP_8BYTE_PAD 4 /* pad buffer with eight nullbytes, not one */ PUBLIC_FN char *slurp_fd(int fd, size_t *len_out, int flags) { int errno_; @@ -74,6 +75,8 @@ PUBLIC_FN char *slurp_fd(int fd, size_t *len_out, int flags) { size_t size_guess = 1023; bool trusted_guess = false; /* can we rely on the guess? */ + int padlen = (flags&JH_SLURP_8BYTE_PAD)?8:1; + // If we can determine the exact size, we don't have to guess. So try // to determine the exact size. if (!(flags&JH_SLURP_NO_STAT)) { @@ -90,7 +93,7 @@ PUBLIC_FN char *slurp_fd(int fd, size_t *len_out, int flags) { int done = 0; while (1) { - buf = realloc(buf, size_guess+1); + buf = realloc(buf, size_guess+padlen); if (buf == NULL) return NULL; int last_res; ssize_t read_res = read_nointr(fd, buf+done, size_guess-done, &last_res); @@ -98,12 +101,16 @@ PUBLIC_FN char *slurp_fd(int fd, size_t *len_out, int flags) { done += read_res; if (last_res == 0 || trusted_guess) { // out - buf[done] = '\0'; + if (padlen == 1) { + buf[done] = '\0'; + } else { + *(uint64_t*)(buf+done) = 0; + } if (done != size_guess && (flags&JH_SLURP_REALLOC)) { // Well, it'd be weird if shrinking could fail... but meh, I can't find // an explicit statement about this being disallowed, so try staying on // the safe side. - char *buf_ = realloc(buf, done+1); + char *buf_ = realloc(buf, done+padlen); if (buf_) buf = buf_; } if (len_out) *len_out = done; -- 2.20.1