Merge branch 'ph/strbuf'
authorJunio C Hamano <gitster@pobox.com>
Wed, 3 Oct 2007 10:06:02 +0000 (03:06 -0700)
committerJunio C Hamano <gitster@pobox.com>
Wed, 3 Oct 2007 10:06:02 +0000 (03:06 -0700)
* ph/strbuf: (44 commits)
Make read_patch_file work on a strbuf.
strbuf_read_file enhancement, and use it.
strbuf change: be sure ->buf is never ever NULL.
double free in builtin-update-index.c
Clean up stripspace a bit, use strbuf even more.
Add strbuf_read_file().
rerere: Fix use of an empty strbuf.buf
Small cache_tree_write refactor.
Make builtin-rerere use of strbuf nicer and more efficient.
Add strbuf_cmp.
strbuf_setlen(): do not barf on setting length of an empty buffer to 0
sq_quote_argv and add_to_string rework with strbuf's.
Full rework of quote_c_style and write_name_quoted.
Rework unquote_c_style to work on a strbuf.
strbuf API additions and enhancements.
nfv?asprintf are broken without va_copy, workaround them.
Fix the expansion pattern of the pseudo-static path buffer.
builtin-for-each-ref.c::copy_name() - do not overstep the buffer.
builtin-apply.c: fix a tiny leak introduced during xmemdupz() conversion.
Use xmemdupz() in many places.
...

1  2 
builtin-apply.c
builtin-for-each-ref.c
builtin-ls-files.c
builtin-rev-list.c
cache.h
diff.c
merge-recursive.c
sha1_file.c
diff --combined builtin-apply.c
index 6777231c665044a486c16fd7fb11b53ed83a0474,4113d66b56c956a51b7327358e76dbef7f3647c9..047a60d1a43a24c3e7d086cf9f87cb36835e8495
@@@ -41,7 -41,7 +41,7 @@@ static int apply_in_reverse
  static int apply_with_reject;
  static int apply_verbosely;
  static int no_add;
 -static int show_index_info;
 +static const char *fake_ancestor;
  static int line_termination = '\n';
  static unsigned long p_context = ULONG_MAX;
  static const char apply_usage[] =
@@@ -163,15 -163,14 +163,14 @@@ static void say_patch_name(FILE *output
        fputs(pre, output);
        if (patch->old_name && patch->new_name &&
            strcmp(patch->old_name, patch->new_name)) {
-               write_name_quoted(NULL, 0, patch->old_name, 1, output);
+               quote_c_style(patch->old_name, NULL, output, 0);
                fputs(" => ", output);
-               write_name_quoted(NULL, 0, patch->new_name, 1, output);
-       }
-       else {
+               quote_c_style(patch->new_name, NULL, output, 0);
+       } else {
                const char *n = patch->new_name;
                if (!n)
                        n = patch->old_name;
-               write_name_quoted(NULL, 0, n, 1, output);
+               quote_c_style(n, NULL, output, 0);
        }
        fputs(post, output);
  }
  #define CHUNKSIZE (8192)
  #define SLOP (16)
  
- static void *read_patch_file(int fd, unsigned long *sizep)
+ static void read_patch_file(struct strbuf *sb, int fd)
  {
-       unsigned long size = 0, alloc = CHUNKSIZE;
-       void *buffer = xmalloc(alloc);
-       for (;;) {
-               ssize_t nr = alloc - size;
-               if (nr < 1024) {
-                       alloc += CHUNKSIZE;
-                       buffer = xrealloc(buffer, alloc);
-                       nr = alloc - size;
-               }
-               nr = xread(fd, (char *) buffer + size, nr);
-               if (!nr)
-                       break;
-               if (nr < 0)
-                       die("git-apply: read returned %s", strerror(errno));
-               size += nr;
-       }
-       *sizep = size;
+       if (strbuf_read(sb, fd, 0) < 0)
+               die("git-apply: read returned %s", strerror(errno));
  
        /*
         * Make sure that we have some slop in the buffer
         * so that we can do speculative "memcmp" etc, and
         * see to it that it is NUL-filled.
         */
-       if (alloc < size + SLOP)
-               buffer = xrealloc(buffer, size + SLOP);
-       memset((char *) buffer + size, 0, SLOP);
-       return buffer;
+       strbuf_grow(sb, SLOP);
+       memset(sb->buf + sb->len, 0, SLOP);
  }
  
  static unsigned long linelen(const char *buffer, unsigned long size)
@@@ -244,35 -225,33 +225,33 @@@ static char *find_name(const char *line
  {
        int len;
        const char *start = line;
-       char *name;
  
        if (*line == '"') {
+               struct strbuf name;
                /* Proposed "new-style" GNU patch/diff format; see
                 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
                 */
-               name = unquote_c_style(line, NULL);
-               if (name) {
-                       char *cp = name;
-                       while (p_value) {
+               strbuf_init(&name, 0);
+               if (!unquote_c_style(&name, line, NULL)) {
+                       char *cp;
+                       for (cp = name.buf; p_value; p_value--) {
                                cp = strchr(cp, '/');
                                if (!cp)
                                        break;
                                cp++;
-                               p_value--;
                        }
                        if (cp) {
                                /* name can later be freed, so we need
                                 * to memmove, not just return cp
                                 */
-                               memmove(name, cp, strlen(cp) + 1);
+                               strbuf_remove(&name, 0, cp - name.buf);
                                free(def);
-                               return name;
-                       }
-                       else {
-                               free(name);
-                               name = NULL;
+                               return strbuf_detach(&name, NULL);
                        }
                }
+               strbuf_release(&name);
        }
  
        for (;;) {
                int deflen = strlen(def);
                if (deflen < len && !strncmp(start, def, deflen))
                        return def;
+               free(def);
        }
  
-       name = xmalloc(len + 1);
-       memcpy(name, start, len);
-       name[len] = 0;
-       free(def);
-       return name;
+       return xmemdupz(start, len);
  }
  
  static int count_slashes(const char *cp)
@@@ -583,29 -559,30 +559,30 @@@ static const char *stop_at_slash(const 
   */
  static char *git_header_name(char *line, int llen)
  {
-       int len;
        const char *name;
        const char *second = NULL;
+       size_t len;
  
        line += strlen("diff --git ");
        llen -= strlen("diff --git ");
  
        if (*line == '"') {
                const char *cp;
-               char *first = unquote_c_style(line, &second);
-               if (!first)
-                       return NULL;
+               struct strbuf first;
+               struct strbuf sp;
+               strbuf_init(&first, 0);
+               strbuf_init(&sp, 0);
+               if (unquote_c_style(&first, line, &second))
+                       goto free_and_fail1;
  
                /* advance to the first slash */
-               cp = stop_at_slash(first, strlen(first));
-               if (!cp || cp == first) {
-                       /* we do not accept absolute paths */
-               free_first_and_fail:
-                       free(first);
-                       return NULL;
-               }
-               len = strlen(cp+1);
-               memmove(first, cp+1, len+1); /* including NUL */
+               cp = stop_at_slash(first.buf, first.len);
+               /* we do not accept absolute paths */
+               if (!cp || cp == first.buf)
+                       goto free_and_fail1;
+               strbuf_remove(&first, 0, cp + 1 - first.buf);
  
                /* second points at one past closing dq of name.
                 * find the second name.
                        second++;
  
                if (line + llen <= second)
-                       goto free_first_and_fail;
+                       goto free_and_fail1;
                if (*second == '"') {
-                       char *sp = unquote_c_style(second, NULL);
-                       if (!sp)
-                               goto free_first_and_fail;
-                       cp = stop_at_slash(sp, strlen(sp));
-                       if (!cp || cp == sp) {
-                       free_both_and_fail:
-                               free(sp);
-                               goto free_first_and_fail;
-                       }
+                       if (unquote_c_style(&sp, second, NULL))
+                               goto free_and_fail1;
+                       cp = stop_at_slash(sp.buf, sp.len);
+                       if (!cp || cp == sp.buf)
+                               goto free_and_fail1;
                        /* They must match, otherwise ignore */
-                       if (strcmp(cp+1, first))
-                               goto free_both_and_fail;
-                       free(sp);
-                       return first;
+                       if (strcmp(cp + 1, first.buf))
+                               goto free_and_fail1;
+                       strbuf_release(&sp);
+                       return strbuf_detach(&first, NULL);
                }
  
                /* unquoted second */
                cp = stop_at_slash(second, line + llen - second);
                if (!cp || cp == second)
-                       goto free_first_and_fail;
+                       goto free_and_fail1;
                cp++;
-               if (line + llen - cp != len + 1 ||
-                   memcmp(first, cp, len))
-                       goto free_first_and_fail;
-               return first;
+               if (line + llen - cp != first.len + 1 ||
+                   memcmp(first.buf, cp, first.len))
+                       goto free_and_fail1;
+               return strbuf_detach(&first, NULL);
+       free_and_fail1:
+               strbuf_release(&first);
+               strbuf_release(&sp);
+               return NULL;
        }
  
        /* unquoted first name */
        name = stop_at_slash(line, llen);
        if (!name || name == line)
                return NULL;
        name++;
  
        /* since the first name is unquoted, a dq if exists must be
         */
        for (second = name; second < line + llen; second++) {
                if (*second == '"') {
-                       const char *cp = second;
+                       struct strbuf sp;
                        const char *np;
-                       char *sp = unquote_c_style(second, NULL);
-                       if (!sp)
-                               return NULL;
-                       np = stop_at_slash(sp, strlen(sp));
-                       if (!np || np == sp) {
-                       free_second_and_fail:
-                               free(sp);
-                               return NULL;
-                       }
+                       strbuf_init(&sp, 0);
+                       if (unquote_c_style(&sp, second, NULL))
+                               goto free_and_fail2;
+                       np = stop_at_slash(sp.buf, sp.len);
+                       if (!np || np == sp.buf)
+                               goto free_and_fail2;
                        np++;
-                       len = strlen(np);
-                       if (len < cp - name &&
+                       len = sp.buf + sp.len - np;
+                       if (len < second - name &&
                            !strncmp(np, name, len) &&
                            isspace(name[len])) {
                                /* Good */
-                               memmove(sp, np, len + 1);
-                               return sp;
+                               strbuf_remove(&sp, 0, np - sp.buf);
+                               return strbuf_detach(&sp, NULL);
                        }
-                       goto free_second_and_fail;
+               free_and_fail2:
+                       strbuf_release(&sp);
+                       return NULL;
                }
        }
  
                                        break;
                        }
                        if (second[len] == '\n' && !memcmp(name, second, len)) {
-                               char *ret = xmalloc(len + 1);
-                               memcpy(ret, name, len);
-                               ret[len] = 0;
-                               return ret;
+                               return xmemdupz(name, len);
                        }
                }
        }
@@@ -1397,96 -1373,66 +1373,66 @@@ static const char minuses[]= "---------
  
  static void show_stats(struct patch *patch)
  {
-       const char *prefix = "";
-       char *name = patch->new_name;
-       char *qname = NULL;
-       int len, max, add, del, total;
-       if (!name)
-               name = patch->old_name;
+       struct strbuf qname;
+       char *cp = patch->new_name ? patch->new_name : patch->old_name;
+       int max, add, del;
  
-       if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
-               qname = xmalloc(len + 1);
-               quote_c_style(name, qname, NULL, 0);
-               name = qname;
-       }
+       strbuf_init(&qname, 0);
+       quote_c_style(cp, &qname, NULL, 0);
  
        /*
         * "scale" the filename
         */
-       len = strlen(name);
        max = max_len;
        if (max > 50)
                max = 50;
-       if (len > max) {
-               char *slash;
-               prefix = "...";
-               max -= 3;
-               name += len - max;
-               slash = strchr(name, '/');
-               if (slash)
-                       name = slash;
+       if (qname.len > max) {
+               cp = strchr(qname.buf + qname.len + 3 - max, '/');
+               if (!cp)
+                       cp = qname.buf + qname.len + 3 - max;
+               strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
+       }
+       if (patch->is_binary) {
+               printf(" %-*s |  Bin\n", max, qname.buf);
+               strbuf_release(&qname);
+               return;
        }
-       len = max;
+       printf(" %-*s |", max, qname.buf);
+       strbuf_release(&qname);
  
        /*
         * scale the add/delete
         */
-       max = max_change;
-       if (max + len > 70)
-               max = 70 - len;
+       max = max + max_change > 70 ? 70 - max : max_change;
        add = patch->lines_added;
        del = patch->lines_deleted;
-       total = add + del;
  
        if (max_change > 0) {
-               total = (total * max + max_change / 2) / max_change;
+               int total = ((add + del) * max + max_change / 2) / max_change;
                add = (add * max + max_change / 2) / max_change;
                del = total - add;
        }
-       if (patch->is_binary)
-               printf(" %s%-*s |  Bin\n", prefix, len, name);
-       else
-               printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
-                      len, name, patch->lines_added + patch->lines_deleted,
-                      add, pluses, del, minuses);
-       free(qname);
+       printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
+               add, pluses, del, minuses);
  }
  
- static int read_old_data(struct stat *st, const char *path, char **buf_p, unsigned long *alloc_p, unsigned long *size_p)
+ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
  {
-       int fd;
-       unsigned long got;
-       unsigned long nsize;
-       char *nbuf;
-       unsigned long size = *size_p;
-       char *buf = *buf_p;
        switch (st->st_mode & S_IFMT) {
        case S_IFLNK:
-               return readlink(path, buf, size) != size;
+               strbuf_grow(buf, st->st_size);
+               if (readlink(path, buf->buf, st->st_size) != st->st_size)
+                       return -1;
+               strbuf_setlen(buf, st->st_size);
+               return 0;
        case S_IFREG:
-               fd = open(path, O_RDONLY);
-               if (fd < 0)
-                       return error("unable to open %s", path);
-               got = 0;
-               for (;;) {
-                       ssize_t ret = xread(fd, buf + got, size - got);
-                       if (ret <= 0)
-                               break;
-                       got += ret;
-               }
-               close(fd);
-               nsize = got;
-               nbuf = convert_to_git(path, buf, &nsize);
-               if (nbuf) {
-                       free(buf);
-                       *buf_p = nbuf;
-                       *alloc_p = nsize;
-                       *size_p = nsize;
-               }
-               return got != size;
+               if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
+                       return error("unable to open or read %s", path);
+               convert_to_git(path, buf->buf, buf->len, buf);
+               return 0;
        default:
                return -1;
        }
@@@ -1591,12 -1537,6 +1537,6 @@@ static void remove_last_line(const cha
        *rsize = offset + 1;
  }
  
- struct buffer_desc {
-       char *buffer;
-       unsigned long size;
-       unsigned long alloc;
- };
  static int apply_line(char *output, const char *patch, int plen)
  {
        /* plen is number of bytes to be copied from patch,
        return output + plen - buf;
  }
  
- static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, int inaccurate_eof)
+ static int apply_one_fragment(struct strbuf *buf, struct fragment *frag, int inaccurate_eof)
  {
        int match_beginning, match_end;
-       char *buf = desc->buffer;
        const char *patch = frag->patch;
        int offset, size = frag->size;
        char *old = xmalloc(size);
        lines = 0;
        pos = frag->newpos;
        for (;;) {
-               offset = find_offset(buf, desc->size,
+               offset = find_offset(buf->buf, buf->len,
                                     oldlines, oldsize, pos, &lines);
-               if (match_end && offset + oldsize != desc->size)
+               if (match_end && offset + oldsize != buf->len)
                        offset = -1;
                if (match_beginning && offset)
                        offset = -1;
                if (offset >= 0) {
-                       int diff;
-                       unsigned long size, alloc;
                        if (new_whitespace == strip_whitespace &&
-                           (desc->size - oldsize - offset == 0)) /* end of file? */
+                           (buf->len - oldsize - offset == 0)) /* end of file? */
                                newsize -= new_blank_lines_at_end;
  
-                       diff = newsize - oldsize;
-                       size = desc->size + diff;
-                       alloc = desc->alloc;
                        /* Warn if it was necessary to reduce the number
                         * of context lines.
                         */
                                        " to apply fragment at %d\n",
                                        leading, trailing, pos + lines);
  
-                       if (size > alloc) {
-                               alloc = size + 8192;
-                               desc->alloc = alloc;
-                               buf = xrealloc(buf, alloc);
-                               desc->buffer = buf;
-                       }
-                       desc->size = size;
-                       memmove(buf + offset + newsize,
-                               buf + offset + oldsize,
-                               size - offset - newsize);
-                       memcpy(buf + offset, newlines, newsize);
+                       strbuf_splice(buf, offset, oldsize, newlines, newsize);
                        offset = 0;
                        break;
                }
  
        return offset;
  }
  
- static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
+ static int apply_binary_fragment(struct strbuf *buf, struct patch *patch)
  {
-       unsigned long dst_size;
        struct fragment *fragment = patch->fragments;
-       void *data;
-       void *result;
+       unsigned long len;
+       void *dst;
  
        /* Binary patch is irreversible without the optional second hunk */
        if (apply_in_reverse) {
                                     ? patch->new_name : patch->old_name);
                fragment = fragment->next;
        }
-       data = (void*) fragment->patch;
        switch (fragment->binary_patch_method) {
        case BINARY_DELTA_DEFLATED:
-               result = patch_delta(desc->buffer, desc->size,
-                                    data,
-                                    fragment->size,
-                                    &dst_size);
-               free(desc->buffer);
-               desc->buffer = result;
-               break;
+               dst = patch_delta(buf->buf, buf->len, fragment->patch,
+                                 fragment->size, &len);
+               if (!dst)
+                       return -1;
+               /* XXX patch_delta NUL-terminates */
+               strbuf_attach(buf, dst, len, len + 1);
+               return 0;
        case BINARY_LITERAL_DEFLATED:
-               free(desc->buffer);
-               desc->buffer = data;
-               dst_size = fragment->size;
-               break;
+               strbuf_reset(buf);
+               strbuf_add(buf, fragment->patch, fragment->size);
+               return 0;
        }
-       if (!desc->buffer)
-               return -1;
-       desc->size = desc->alloc = dst_size;
-       return 0;
+       return -1;
  }
  
- static int apply_binary(struct buffer_desc *desc, struct patch *patch)
+ static int apply_binary(struct strbuf *buf, struct patch *patch)
  {
        const char *name = patch->old_name ? patch->old_name : patch->new_name;
        unsigned char sha1[20];
                /* See if the old one matches what the patch
                 * applies to.
                 */
-               hash_sha1_file(desc->buffer, desc->size, blob_type, sha1);
+               hash_sha1_file(buf->buf, buf->len, blob_type, sha1);
                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
                        return error("the patch applies to '%s' (%s), "
                                     "which does not match the "
        }
        else {
                /* Otherwise, the old one must be empty. */
-               if (desc->size)
+               if (buf->len)
                        return error("the patch applies to an empty "
                                     "'%s' but it is not empty", name);
        }
  
        get_sha1_hex(patch->new_sha1_prefix, sha1);
        if (is_null_sha1(sha1)) {
-               free(desc->buffer);
-               desc->alloc = desc->size = 0;
-               desc->buffer = NULL;
+               strbuf_release(buf);
                return 0; /* deletion patch */
        }
  
                /* We already have the postimage */
                enum object_type type;
                unsigned long size;
+               char *result;
  
-               free(desc->buffer);
-               desc->buffer = read_sha1_file(sha1, &type, &size);
-               if (!desc->buffer)
+               result = read_sha1_file(sha1, &type, &size);
+               if (!result)
                        return error("the necessary postimage %s for "
                                     "'%s' cannot be read",
                                     patch->new_sha1_prefix, name);
-               desc->alloc = desc->size = size;
-       }
-       else {
-               /* We have verified desc matches the preimage;
+               /* XXX read_sha1_file NUL-terminates */
+               strbuf_attach(buf, result, size, size + 1);
+       else {
+               /* We have verified buf matches the preimage;
                 * apply the patch data to it, which is stored
                 * in the patch->fragments->{patch,size}.
                 */
-               if (apply_binary_fragment(desc, patch))
+               if (apply_binary_fragment(buf, patch))
                        return error("binary patch does not apply to '%s'",
                                     name);
  
                /* verify that the result matches */
-               hash_sha1_file(desc->buffer, desc->size, blob_type, sha1);
+               hash_sha1_file(buf->buf, buf->len, blob_type, sha1);
                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
-                       return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1));
+                       return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
+                               name, patch->new_sha1_prefix, sha1_to_hex(sha1));
        }
  
        return 0;
  }
  
- static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
+ static int apply_fragments(struct strbuf *buf, struct patch *patch)
  {
        struct fragment *frag = patch->fragments;
        const char *name = patch->old_name ? patch->old_name : patch->new_name;
  
        if (patch->is_binary)
-               return apply_binary(desc, patch);
+               return apply_binary(buf, patch);
  
        while (frag) {
-               if (apply_one_fragment(desc, frag, patch->inaccurate_eof)) {
+               if (apply_one_fragment(buf, frag, patch->inaccurate_eof)) {
                        error("patch failed: %s:%ld", name, frag->oldpos);
                        if (!apply_with_reject)
                                return -1;
        return 0;
  }
  
- static int read_file_or_gitlink(struct cache_entry *ce, char **buf_p,
-                               unsigned long *size_p)
+ static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
  {
        if (!ce)
                return 0;
  
        if (S_ISGITLINK(ntohl(ce->ce_mode))) {
-               *buf_p = xmalloc(100);
-               *size_p = snprintf(*buf_p, 100,
-                       "Subproject commit %s\n", sha1_to_hex(ce->sha1));
+               strbuf_grow(buf, 100);
+               strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
        } else {
                enum object_type type;
-               *buf_p = read_sha1_file(ce->sha1, &type, size_p);
-               if (!*buf_p)
+               unsigned long sz;
+               char *result;
+               result = read_sha1_file(ce->sha1, &type, &sz);
+               if (!result)
                        return -1;
+               /* XXX read_sha1_file NUL-terminates */
+               strbuf_attach(buf, result, sz, sz + 1);
        }
        return 0;
  }
  
  static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
  {
-       char *buf;
-       unsigned long size, alloc;
-       struct buffer_desc desc;
+       struct strbuf buf;
  
-       size = 0;
-       alloc = 0;
-       buf = NULL;
+       strbuf_init(&buf, 0);
        if (cached) {
-               if (read_file_or_gitlink(ce, &buf, &size))
+               if (read_file_or_gitlink(ce, &buf))
                        return error("read of %s failed", patch->old_name);
-               alloc = size;
        } else if (patch->old_name) {
                if (S_ISGITLINK(patch->old_mode)) {
-                       if (ce)
-                               read_file_or_gitlink(ce, &buf, &size);
-                       else {
+                       if (ce) {
+                               read_file_or_gitlink(ce, &buf);
+                       else {
                                /*
                                 * There is no way to apply subproject
                                 * patch without looking at the index.
                                 */
                                patch->fragments = NULL;
-                               size = 0;
                        }
-               }
-               else {
-                       size = xsize_t(st->st_size);
-                       alloc = size + 8192;
-                       buf = xmalloc(alloc);
-                       if (read_old_data(st, patch->old_name,
-                                         &buf, &alloc, &size))
-                               return error("read of %s failed",
-                                            patch->old_name);
+               } else {
+                       if (read_old_data(st, patch->old_name, &buf))
+                               return error("read of %s failed", patch->old_name);
                }
        }
  
-       desc.size = size;
-       desc.alloc = alloc;
-       desc.buffer = buf;
-       if (apply_fragments(&desc, patch) < 0)
+       if (apply_fragments(&buf, patch) < 0)
                return -1; /* note with --reject this succeeds. */
-       /* NUL terminate the result */
-       if (desc.alloc <= desc.size)
-               desc.buffer = xrealloc(desc.buffer, desc.size + 1);
-       desc.buffer[desc.size] = 0;
-       patch->result = desc.buffer;
-       patch->resultsize = desc.size;
+       patch->result = strbuf_detach(&buf, &patch->resultsize);
  
        if (0 < patch->is_delete && patch->resultsize)
                return error("removal patch leaves file contents");
@@@ -2248,12 -2142,9 +2142,12 @@@ static int get_current_sha1(const char 
        return 0;
  }
  
 -static void show_index_list(struct patch *list)
 +/* Build an index that contains the just the files needed for a 3way merge */
 +static void build_fake_ancestor(struct patch *list, const char *filename)
  {
        struct patch *patch;
 +      struct index_state result = { 0 };
 +      int fd;
  
        /* Once we start supporting the reverse patch, it may be
         * worth showing the new sha1 prefix, but until then...
        for (patch = list; patch; patch = patch->next) {
                const unsigned char *sha1_ptr;
                unsigned char sha1[20];
 +              struct cache_entry *ce;
                const char *name;
  
                name = patch->old_name ? patch->old_name : patch->new_name;
                if (0 < patch->is_new)
 -                      sha1_ptr = null_sha1;
 +                      continue;
                else if (get_sha1(patch->old_sha1_prefix, sha1))
                        /* git diff has no index line for mode/type changes */
                        if (!patch->lines_added && !patch->lines_deleted) {
                else
                        sha1_ptr = sha1;
  
 -              printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
 -              if (line_termination && quote_c_style(name, NULL, NULL, 0))
 -                      quote_c_style(name, NULL, stdout, 0);
 -              else
 -                      fputs(name, stdout);
 -              putchar(line_termination);
 +              ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
 +              if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
 +                      die ("Could not add %s to temporary index", name);
        }
 +
 +      fd = open(filename, O_WRONLY | O_CREAT, 0666);
 +      if (fd < 0 || write_index(&result, fd) || close(fd))
 +              die ("Could not write temporary index to %s", filename);
 +
 +      discard_index(&result);
  }
  
  static void stat_patch_list(struct patch *patch)
@@@ -2315,13 -2202,8 +2209,8 @@@ static void numstat_patch_list(struct p
                if (patch->is_binary)
                        printf("-\t-\t");
                else
-                       printf("%d\t%d\t",
-                              patch->lines_added, patch->lines_deleted);
-               if (line_termination && quote_c_style(name, NULL, NULL, 0))
-                       quote_c_style(name, NULL, stdout, 0);
-               else
-                       fputs(name, stdout);
-               putchar(line_termination);
+                       printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
+               write_name_quoted(name, stdout, line_termination);
        }
  }
  
@@@ -2486,7 -2368,7 +2375,7 @@@ static void add_index_file(const char *
  static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
  {
        int fd;
-       char *nbuf;
+       struct strbuf nbuf;
  
        if (S_ISGITLINK(mode)) {
                struct stat st;
        if (fd < 0)
                return -1;
  
-       nbuf = convert_to_working_tree(path, buf, &size);
-       if (nbuf)
-               buf = nbuf;
-       while (size) {
-               int written = xwrite(fd, buf, size);
-               if (written < 0)
-                       die("writing file %s: %s", path, strerror(errno));
-               if (!written)
-                       die("out of space writing file %s", path);
-               buf += written;
-               size -= written;
+       strbuf_init(&nbuf, 0);
+       if (convert_to_working_tree(path, buf, size, &nbuf)) {
+               size = nbuf.len;
+               buf  = nbuf.buf;
        }
+       write_or_die(fd, buf, size);
+       strbuf_release(&nbuf);
        if (close(fd) < 0)
                die("closing file %s: %s", path, strerror(errno));
-       if (nbuf)
-               free(nbuf);
        return 0;
  }
  
@@@ -2754,22 -2629,22 +2636,22 @@@ static void prefix_patches(struct patc
  
  static int apply_patch(int fd, const char *filename, int inaccurate_eof)
  {
-       unsigned long offset, size;
-       char *buffer = read_patch_file(fd, &size);
+       size_t offset;
+       struct strbuf buf;
        struct patch *list = NULL, **listp = &list;
        int skipped_patch = 0;
  
+       strbuf_init(&buf, 0);
        patch_input_file = filename;
-       if (!buffer)
-               return -1;
+       read_patch_file(&buf, fd);
        offset = 0;
-       while (size > 0) {
+       while (offset < buf.len) {
                struct patch *patch;
                int nr;
  
                patch = xcalloc(1, sizeof(*patch));
                patch->inaccurate_eof = inaccurate_eof;
-               nr = parse_chunk(buffer + offset, size, patch);
+               nr = parse_chunk(buf.buf + offset, buf.len, patch);
                if (nr < 0)
                        break;
                if (apply_in_reverse)
                        skipped_patch++;
                }
                offset += nr;
-               size -= nr;
        }
  
        if (whitespace_error && (new_whitespace == error_on_whitespace))
        if (apply && write_out_results(list, skipped_patch))
                exit(1);
  
 -      if (show_index_info)
 -              show_index_list(list);
 +      if (fake_ancestor)
 +              build_fake_ancestor(list, fake_ancestor);
  
        if (diffstat)
                stat_patch_list(list);
        if (summary)
                summary_patch_list(list);
  
-       free(buffer);
+       strbuf_release(&buf);
        return 0;
  }
  
@@@ -2919,11 -2793,9 +2800,11 @@@ int cmd_apply(int argc, const char **ar
                        apply = 1;
                        continue;
                }
 -              if (!strcmp(arg, "--index-info")) {
 +              if (!strcmp(arg, "--build-fake-ancestor")) {
                        apply = 0;
 -                      show_index_info = 1;
 +                      if (++i >= argc)
 +                              die ("need a filename");
 +                      fake_ancestor = argv[i];
                        continue;
                }
                if (!strcmp(arg, "-z")) {
diff --combined builtin-for-each-ref.c
index 5dbf3e59f297b1849c1289b7cc7980bddf1852f7,e868a4b6d7f2fe59437ccab12ea7a9b16f4a2163..c74ef2800c839a5537707c5c64aa55acb2a9efad
@@@ -43,7 -43,7 +43,7 @@@ static struct 
        { "objectsize", FIELD_ULONG },
        { "objectname" },
        { "tree" },
 -      { "parent" }, /* NEEDSWORK: how to address 2nd and later parents? */
 +      { "parent" },
        { "numparent", FIELD_ULONG },
        { "object" },
        { "type" },
@@@ -87,7 -87,6 +87,6 @@@ static int used_atom_cnt, sort_atom_lim
  static int parse_atom(const char *atom, const char *ep)
  {
        const char *sp;
-       char *n;
        int i, at;
  
        sp = atom;
        /* Is the atom a valid one? */
        for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
                int len = strlen(valid_atom[i].name);
 -              if (len == ep - sp && !memcmp(valid_atom[i].name, sp, len))
 +              /*
 +               * If the atom name has a colon, strip it and everything after
 +               * it off - it specifies the format for this entry, and
 +               * shouldn't be used for checking against the valid_atom
 +               * table.
 +               */
 +              const char *formatp = strchr(sp, ':');
 +              if (!formatp || ep < formatp)
 +                      formatp = ep;
 +              if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
                        break;
        }
  
                             (sizeof *used_atom) * used_atom_cnt);
        used_atom_type = xrealloc(used_atom_type,
                                  (sizeof(*used_atom_type) * used_atom_cnt));
-       n = xmalloc(ep - atom + 1);
-       memcpy(n, atom, ep - atom);
-       n[ep-atom] = 0;
-       used_atom[at] = n;
+       used_atom[at] = xmemdupz(atom, ep - atom);
        used_atom_type[at] = valid_atom[i].cmp_type;
        return at;
  }
@@@ -271,26 -258,24 +267,26 @@@ static void grab_commit_values(struct a
                }
                if (!strcmp(name, "numparent")) {
                        char *s = xmalloc(40);
 +                      v->ul = num_parents(commit);
                        sprintf(s, "%lu", v->ul);
                        v->s = s;
 -                      v->ul = num_parents(commit);
                }
                else if (!strcmp(name, "parent")) {
                        int num = num_parents(commit);
                        int i;
                        struct commit_list *parents;
 -                      char *s = xmalloc(42 * num);
 +                      char *s = xmalloc(41 * num + 1);
                        v->s = s;
                        for (i = 0, parents = commit->parents;
                             parents;
 -                           parents = parents->next, i = i + 42) {
 +                           parents = parents->next, i = i + 41) {
                                struct commit *parent = parents->item;
                                strcpy(s+i, sha1_to_hex(parent->object.sha1));
                                if (parents->next)
                                        s[i+40] = ' ';
                        }
 +                      if (!i)
 +                              *s = '\0';
                }
        }
  }
@@@ -316,68 -301,36 +312,50 @@@ static const char *find_wholine(const c
  static const char *copy_line(const char *buf)
  {
        const char *eol = strchr(buf, '\n');
-       char *line;
-       int len;
        if (!eol)
                return "";
-       len = eol - buf;
-       line = xmalloc(len + 1);
-       memcpy(line, buf, len);
-       line[len] = 0;
-       return line;
+       return xmemdupz(buf, eol - buf);
  }
  
  static const char *copy_name(const char *buf)
  {
-       const char *eol = strchr(buf, '\n');
-       const char *eoname = strstr(buf, " <");
-       char *line;
-       int len;
-       if (!(eoname && eol && eoname < eol))
-               return "";
-       len = eoname - buf;
-       line = xmalloc(len + 1);
-       memcpy(line, buf, len);
-       line[len] = 0;
-       return line;
+       const char *cp;
+       for (cp = buf; *cp && *cp != '\n'; cp++) {
+               if (!strncmp(cp, " <", 2))
+                       return xmemdupz(buf, cp - buf);
+       }
+       return "";
  }
  
  static const char *copy_email(const char *buf)
  {
        const char *email = strchr(buf, '<');
        const char *eoemail = strchr(email, '>');
-       char *line;
-       int len;
        if (!email || !eoemail)
                return "";
-       eoemail++;
-       len = eoemail - email;
-       line = xmalloc(len + 1);
-       memcpy(line, email, len);
-       line[len] = 0;
-       return line;
+       return xmemdupz(email, eoemail + 1 - email);
  }
  
 -static void grab_date(const char *buf, struct atom_value *v)
 +static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
  {
        const char *eoemail = strstr(buf, "> ");
        char *zone;
        unsigned long timestamp;
        long tz;
 +      enum date_mode date_mode = DATE_NORMAL;
 +      const char *formatp;
 +
 +      /*
 +       * We got here because atomname ends in "date" or "date<something>";
 +       * it's not possible that <something> is not ":<format>" because
 +       * parse_atom() wouldn't have allowed it, so we can assume that no
 +       * ":" means no format is specified, and use the default.
 +       */
 +      formatp = strchr(atomname, ':');
 +      if (formatp != NULL) {
 +              formatp++;
 +              date_mode = parse_date_format(formatp);
 +      }
  
        if (!eoemail)
                goto bad;
        tz = strtol(zone, NULL, 10);
        if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
                goto bad;
 -      v->s = xstrdup(show_date(timestamp, tz, 0));
 +      v->s = xstrdup(show_date(timestamp, tz, date_mode));
        v->ul = timestamp;
        return;
   bad:
@@@ -414,7 -367,7 +392,7 @@@ static void grab_person(const char *who
                if (name[wholen] != 0 &&
                    strcmp(name + wholen, "name") &&
                    strcmp(name + wholen, "email") &&
 -                  strcmp(name + wholen, "date"))
 +                  prefixcmp(name + wholen, "date"))
                        continue;
                if (!wholine)
                        wholine = find_wholine(who, wholen, buf, sz);
                        v->s = copy_name(wholine);
                else if (!strcmp(name + wholen, "email"))
                        v->s = copy_email(wholine);
 -              else if (!strcmp(name + wholen, "date"))
 -                      grab_date(wholine, v);
 +              else if (!prefixcmp(name + wholen, "date"))
 +                      grab_date(wholine, v, name);
        }
  
        /* For a tag or a commit object, if "creator" or "creatordate" is
                if (deref)
                        name++;
  
 -              if (!strcmp(name, "creatordate"))
 -                      grab_date(wholine, v);
 +              if (!prefixcmp(name, "creatordate"))
 +                      grab_date(wholine, v, name);
                else if (!strcmp(name, "creator"))
                        v->s = copy_line(wholine);
        }
diff --combined builtin-ls-files.c
index 171d449048d304b043ed33776fab4bf95434e30a,2e6f43bb9743d6938e9568d2467cff86901fa31f..b70da1863b221386a073ec8b7138cf0d91f52159
@@@ -84,8 -84,7 +84,7 @@@ static void show_dir_entry(const char *
                return;
  
        fputs(tag, stdout);
-       write_name_quoted("", 0, ent->name + offset, line_terminator, stdout);
-       putchar(line_terminator);
+       write_name_quoted(ent->name + offset, stdout, line_terminator);
  }
  
  static void show_other_files(struct dir_struct *dir)
@@@ -208,21 -207,15 +207,15 @@@ static void show_ce_entry(const char *t
  
        if (!show_stage) {
                fputs(tag, stdout);
-               write_name_quoted("", 0, ce->name + offset,
-                                 line_terminator, stdout);
-               putchar(line_terminator);
-       }
-       else {
+       } else {
                printf("%s%06o %s %d\t",
                       tag,
                       ntohl(ce->ce_mode),
                       abbrev ? find_unique_abbrev(ce->sha1,abbrev)
                                : sha1_to_hex(ce->sha1),
                       ce_stage(ce));
-               write_name_quoted("", 0, ce->name + offset,
-                                 line_terminator, stdout);
-               putchar(line_terminator);
        }
+       write_name_quoted(ce->name + offset, stdout, line_terminator);
  }
  
  static void show_files(struct dir_struct *dir, const char *prefix)
@@@ -280,8 -273,7 +273,8 @@@ static void prune_cache(const char *pre
  
        if (pos < 0)
                pos = -pos-1;
 -      active_cache += pos;
 +      memmove(active_cache, active_cache + pos,
 +              (active_nr - pos) * sizeof(struct cache_entry *));
        active_nr -= pos;
        first = 0;
        last = active_nr;
  static const char *verify_pathspec(const char *prefix)
  {
        const char **p, *n, *prev;
-       char *real_prefix;
        unsigned long max;
  
        prev = NULL;
        if (prefix_offset > max || memcmp(prev, prefix, prefix_offset))
                die("git-ls-files: cannot generate relative filenames containing '..'");
  
-       real_prefix = NULL;
        prefix_len = max;
-       if (max) {
-               real_prefix = xmalloc(max + 1);
-               memcpy(real_prefix, prev, max);
-               real_prefix[max] = 0;
-       }
-       return real_prefix;
+       return max ? xmemdupz(prev, max) : NULL;
  }
  
  /*
diff --combined builtin-rev-list.c
index 38946339999e4e136b898b8f314e27d22ec1decb,43b88fae298bc21a55d3dd83d2b31019fd431d02..414b2f32b293c9d6d7ca2a821f903de64ea8ea21
@@@ -80,13 -80,12 +80,12 @@@ static void show_commit(struct commit *
                putchar('\n');
  
        if (revs.verbose_header) {
-               char *buf = NULL;
-               unsigned long buflen = 0;
-               pretty_print_commit(revs.commit_format, commit, ~0,
-                                   &buf, &buflen,
-                                   revs.abbrev, NULL, NULL, revs.date_mode);
-               printf("%s%c", buf, hdr_termination);
-               free(buf);
+               struct strbuf buf;
+               strbuf_init(&buf, 0);
+               pretty_print_commit(revs.commit_format, commit,
+                                       &buf, revs.abbrev, NULL, NULL, revs.date_mode);
+               printf("%s%c", buf.buf, hdr_termination);
+               strbuf_release(&buf);
        }
        maybe_flush_or_die(stdout, "stdout");
        if (commit->parents) {
@@@ -436,10 -435,10 +435,10 @@@ static struct commit_list *find_bisecti
        /* Do the real work of finding bisection commit. */
        best = do_find_bisection(list, nr, weights);
  
 -      if (best)
 +      if (best) {
                best->next = NULL;
 -
 -      *reaches = weight(best);
 +              *reaches = weight(best);
 +      }
        free(weights);
  
        return best;
diff --combined cache.h
index 6a49e3049b659536ae4263cfff7190173f2c7ade,916ee5155bc0cb8f35c81f1c2809bb30162ebb83..e0abcd697ce54853bbf4545d20a4ae88a95b533a
+++ b/cache.h
@@@ -2,6 -2,7 +2,7 @@@
  #define CACHE_H
  
  #include "git-compat-util.h"
+ #include "strbuf.h"
  
  #include SHA1_HEADER
  #include <zlib.h>
@@@ -270,7 -271,6 +271,6 @@@ extern int ie_match_stat(struct index_s
  extern int ie_modified(struct index_state *, struct cache_entry *, struct stat *, int);
  extern int ce_path_match(const struct cache_entry *ce, const char **pathspec);
  extern int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, enum object_type type, const char *path);
- extern int read_fd(int fd, char **return_buf, unsigned long *return_size);
  extern int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object);
  extern int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object);
  extern void fill_stat_cache_info(struct cache_entry *ce, struct stat *st);
@@@ -432,7 -432,6 +432,7 @@@ const char *show_date(unsigned long tim
  int parse_date(const char *date, char *buf, int bufsize);
  void datestamp(char *buf, int bufsize);
  unsigned long approxidate(const char *);
 +enum date_mode parse_date_format(const char *format);
  
  extern const char *git_author_info(int);
  extern const char *git_committer_info(int);
@@@ -531,7 -530,6 +531,7 @@@ extern void *unpack_entry(struct packed
  extern unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep);
  extern unsigned long get_size_from_delta(struct packed_git *, struct pack_window **, off_t);
  extern const char *packed_object_info_detail(struct packed_git *, off_t, unsigned long *, unsigned long *, unsigned int *, unsigned char *);
 +extern int matches_pack_name(struct packed_git *p, const char *name);
  
  /* Dumb servers support */
  extern int update_server_info(int);
@@@ -587,14 -585,13 +587,13 @@@ extern void *alloc_object_node(void)
  extern void alloc_report(void);
  
  /* trace.c */
- extern int nfasprintf(char **str, const char *fmt, ...);
- extern int nfvasprintf(char **str, const char *fmt, va_list va);
  extern void trace_printf(const char *format, ...);
  extern void trace_argv_printf(const char **argv, int count, const char *format, ...);
  
  /* convert.c */
- extern char *convert_to_git(const char *path, const char *src, unsigned long *sizep);
- extern char *convert_to_working_tree(const char *path, const char *src, unsigned long *sizep);
+ /* returns 1 if *dst was used */
+ extern int convert_to_git(const char *path, const char *src, size_t len, struct strbuf *dst);
+ extern int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst);
  
  /* diff.c */
  extern int diff_auto_refresh_index;
diff --combined diff.c
index 71b340c5368fb287ce7d7b242aa51436ed5dda93,ab575191d11801f023655fe6cf718bfa5fa04c9b..6648e015213913e693b4450230a5a0896a21f7a0
--- 1/diff.c
--- 2/diff.c
+++ b/diff.c
@@@ -83,13 -83,8 +83,8 @@@ static int parse_lldiff_command(const c
                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
                        break;
        if (!drv) {
-               char *namebuf;
                drv = xcalloc(1, sizeof(struct ll_diff_driver));
-               namebuf = xmalloc(namelen + 1);
-               memcpy(namebuf, name, namelen);
-               namebuf[namelen] = 0;
-               drv->name = namebuf;
-               drv->next = NULL;
+               drv->name = xmemdupz(name, namelen);
                if (!user_diff_tail)
                        user_diff_tail = &user_diff;
                *user_diff_tail = drv;
@@@ -126,12 -121,8 +121,8 @@@ static int parse_funcname_pattern(cons
                if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
                        break;
        if (!pp) {
-               char *namebuf;
                pp = xcalloc(1, sizeof(*pp));
-               namebuf = xmalloc(namelen + 1);
-               memcpy(namebuf, name, namelen);
-               namebuf[namelen] = 0;
-               pp->name = namebuf;
+               pp->name = xmemdupz(name, namelen);
                pp->next = funcname_pattern_list;
                funcname_pattern_list = pp;
        }
@@@ -190,44 -181,23 +181,23 @@@ int git_diff_ui_config(const char *var
        return git_default_config(var, value);
  }
  
- static char *quote_one(const char *str)
- {
-       int needlen;
-       char *xp;
-       if (!str)
-               return NULL;
-       needlen = quote_c_style(str, NULL, NULL, 0);
-       if (!needlen)
-               return xstrdup(str);
-       xp = xmalloc(needlen + 1);
-       quote_c_style(str, xp, NULL, 0);
-       return xp;
- }
  static char *quote_two(const char *one, const char *two)
  {
        int need_one = quote_c_style(one, NULL, NULL, 1);
        int need_two = quote_c_style(two, NULL, NULL, 1);
-       char *xp;
+       struct strbuf res;
  
+       strbuf_init(&res, 0);
        if (need_one + need_two) {
-               if (!need_one) need_one = strlen(one);
-               if (!need_two) need_one = strlen(two);
-               xp = xmalloc(need_one + need_two + 3);
-               xp[0] = '"';
-               quote_c_style(one, xp + 1, NULL, 1);
-               quote_c_style(two, xp + need_one + 1, NULL, 1);
-               strcpy(xp + need_one + need_two + 1, "\"");
-               return xp;
+               strbuf_addch(&res, '"');
+               quote_c_style(one, &res, NULL, 1);
+               quote_c_style(two, &res, NULL, 1);
+               strbuf_addch(&res, '"');
+       } else {
+               strbuf_addstr(&res, one);
+               strbuf_addstr(&res, two);
        }
-       need_one = strlen(one);
-       need_two = strlen(two);
-       xp = xmalloc(need_one + need_two + 1);
-       strcpy(xp, one);
-       strcpy(xp + need_one, two);
-       return xp;
+       return strbuf_detach(&res, NULL);
  }
  
  static const char *external_diff(void)
@@@ -679,27 -649,20 +649,20 @@@ static char *pprint_rename(const char *
  {
        const char *old = a;
        const char *new = b;
-       char *name = NULL;
+       struct strbuf name;
        int pfx_length, sfx_length;
        int len_a = strlen(a);
        int len_b = strlen(b);
+       int a_midlen, b_midlen;
        int qlen_a = quote_c_style(a, NULL, NULL, 0);
        int qlen_b = quote_c_style(b, NULL, NULL, 0);
  
+       strbuf_init(&name, 0);
        if (qlen_a || qlen_b) {
-               if (qlen_a) len_a = qlen_a;
-               if (qlen_b) len_b = qlen_b;
-               name = xmalloc( len_a + len_b + 5 );
-               if (qlen_a)
-                       quote_c_style(a, name, NULL, 0);
-               else
-                       memcpy(name, a, len_a);
-               memcpy(name + len_a, " => ", 4);
-               if (qlen_b)
-                       quote_c_style(b, name + len_a + 4, NULL, 0);
-               else
-                       memcpy(name + len_a + 4, b, len_b + 1);
-               return name;
+               quote_c_style(a, &name, NULL, 0);
+               strbuf_addstr(&name, " => ");
+               quote_c_style(b, &name, NULL, 0);
+               return strbuf_detach(&name, NULL);
        }
  
        /* Find common prefix */
         * pfx{sfx-a => sfx-b}
         * name-a => name-b
         */
+       a_midlen = len_a - pfx_length - sfx_length;
+       b_midlen = len_b - pfx_length - sfx_length;
+       if (a_midlen < 0)
+               a_midlen = 0;
+       if (b_midlen < 0)
+               b_midlen = 0;
+       strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
        if (pfx_length + sfx_length) {
-               int a_midlen = len_a - pfx_length - sfx_length;
-               int b_midlen = len_b - pfx_length - sfx_length;
-               if (a_midlen < 0) a_midlen = 0;
-               if (b_midlen < 0) b_midlen = 0;
-               name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
-               sprintf(name, "%.*s{%.*s => %.*s}%s",
-                       pfx_length, a,
-                       a_midlen, a + pfx_length,
-                       b_midlen, b + pfx_length,
-                       a + len_a - sfx_length);
+               strbuf_add(&name, a, pfx_length);
+               strbuf_addch(&name, '{');
        }
-       else {
-               name = xmalloc(len_a + len_b + 5);
-               sprintf(name, "%s => %s", a, b);
+       strbuf_add(&name, a + pfx_length, a_midlen);
+       strbuf_addstr(&name, " => ");
+       strbuf_add(&name, b + pfx_length, b_midlen);
+       if (pfx_length + sfx_length) {
+               strbuf_addch(&name, '}');
+               strbuf_add(&name, a + len_a - sfx_length, sfx_length);
        }
-       return name;
+       return strbuf_detach(&name, NULL);
  }
  
  struct diffstat_t {
@@@ -858,12 -823,13 +823,13 @@@ static void show_stats(struct diffstat_
                int change = file->added + file->deleted;
  
                if (!file->is_renamed) {  /* renames are already quoted by pprint_rename */
-                       len = quote_c_style(file->name, NULL, NULL, 0);
-                       if (len) {
-                               char *qname = xmalloc(len + 1);
-                               quote_c_style(file->name, qname, NULL, 0);
+                       struct strbuf buf;
+                       strbuf_init(&buf, 0);
+                       if (quote_c_style(file->name, &buf, NULL, 0)) {
                                free(file->name);
-                               file->name = qname;
+                               file->name = strbuf_detach(&buf, NULL);
+                       } else {
+                               strbuf_release(&buf);
                        }
                }
  
@@@ -1001,12 -967,12 +967,12 @@@ static void show_numstat(struct diffsta
                        printf("-\t-\t");
                else
                        printf("%d\t%d\t", file->added, file->deleted);
-               if (options->line_termination && !file->is_renamed &&
-                   quote_c_style(file->name, NULL, NULL, 0))
-                       quote_c_style(file->name, NULL, stdout, 0);
-               else
+               if (!file->is_renamed) {
+                       write_name_quoted(file->name, stdout, options->line_termination);
+               } else {
                        fputs(file->name, stdout);
-               putchar(options->line_termination);
+                       putchar(options->line_termination);
+               }
        }
  }
  
@@@ -1545,26 -1511,15 +1511,15 @@@ static int reuse_worktree_file(const ch
  
  static int populate_from_stdin(struct diff_filespec *s)
  {
- #define INCREMENT 1024
-       char *buf;
-       unsigned long size;
-       ssize_t got;
-       size = 0;
-       buf = NULL;
-       while (1) {
-               buf = xrealloc(buf, size + INCREMENT);
-               got = xread(0, buf + size, INCREMENT);
-               if (!got)
-                       break; /* EOF */
-               if (got < 0)
-                       return error("error while reading from stdin %s",
+       struct strbuf buf;
+       strbuf_init(&buf, 0);
+       if (strbuf_read(&buf, 0, 0) < 0)
+               return error("error while reading from stdin %s",
                                     strerror(errno));
-               size += got;
-       }
        s->should_munmap = 0;
-       s->data = buf;
-       s->size = size;
+       s->data = strbuf_detach(&buf, &s->size);
        s->should_free = 1;
        return 0;
  }
@@@ -1609,10 -1564,9 +1564,9 @@@ int diff_populate_filespec(struct diff_
  
        if (!s->sha1_valid ||
            reuse_worktree_file(s->path, s->sha1, 0)) {
+               struct strbuf buf;
                struct stat st;
                int fd;
-               char *buf;
-               unsigned long size;
  
                if (!strcmp(s->path, "-"))
                        return populate_from_stdin(s);
                /*
                 * Convert from working tree format to canonical git format
                 */
-               size = s->size;
-               buf = convert_to_git(s->path, s->data, &size);
-               if (buf) {
+               strbuf_init(&buf, 0);
+               if (convert_to_git(s->path, s->data, s->size, &buf)) {
                        munmap(s->data, s->size);
                        s->should_munmap = 0;
-                       s->data = buf;
-                       s->size = size;
+                       s->data = strbuf_detach(&buf, &s->size);
                        s->should_free = 1;
                }
        }
        return 0;
  }
  
 -void diff_free_filespec_data(struct diff_filespec *s)
 +void diff_free_filespec_blob(struct diff_filespec *s)
  {
        if (s->should_free)
                free(s->data);
                s->should_free = s->should_munmap = 0;
                s->data = NULL;
        }
 +}
 +
 +void diff_free_filespec_data(struct diff_filespec *s)
 +{
 +      diff_free_filespec_blob(s);
        free(s->cnt_data);
        s->cnt_data = NULL;
  }
@@@ -1967,50 -1914,46 +1919,46 @@@ static int similarity_index(struct diff
  static void run_diff(struct diff_filepair *p, struct diff_options *o)
  {
        const char *pgm = external_diff();
-       char msg[PATH_MAX*2+300], *xfrm_msg;
-       struct diff_filespec *one;
-       struct diff_filespec *two;
+       struct strbuf msg;
+       char *xfrm_msg;
+       struct diff_filespec *one = p->one;
+       struct diff_filespec *two = p->two;
        const char *name;
        const char *other;
-       char *name_munged, *other_munged;
        int complete_rewrite = 0;
-       int len;
  
        if (DIFF_PAIR_UNMERGED(p)) {
-               /* unmerged */
                run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
                return;
        }
  
-       name = p->one->path;
+       name  = p->one->path;
        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
-       name_munged = quote_one(name);
-       other_munged = quote_one(other);
-       one = p->one; two = p->two;
        diff_fill_sha1_info(one);
        diff_fill_sha1_info(two);
  
-       len = 0;
+       strbuf_init(&msg, PATH_MAX * 2 + 300);
        switch (p->status) {
        case DIFF_STATUS_COPIED:
-               len += snprintf(msg + len, sizeof(msg) - len,
-                               "similarity index %d%%\n"
-                               "copy from %s\n"
-                               "copy to %s\n",
-                               similarity_index(p), name_munged, other_munged);
+               strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
+               strbuf_addstr(&msg, "\ncopy from ");
+               quote_c_style(name, &msg, NULL, 0);
+               strbuf_addstr(&msg, "\ncopy to ");
+               quote_c_style(other, &msg, NULL, 0);
+               strbuf_addch(&msg, '\n');
                break;
        case DIFF_STATUS_RENAMED:
-               len += snprintf(msg + len, sizeof(msg) - len,
-                               "similarity index %d%%\n"
-                               "rename from %s\n"
-                               "rename to %s\n",
-                               similarity_index(p), name_munged, other_munged);
+               strbuf_addf(&msg, "similarity index %d%%", similarity_index(p));
+               strbuf_addstr(&msg, "\nrename from ");
+               quote_c_style(name, &msg, NULL, 0);
+               strbuf_addstr(&msg, "\nrename to ");
+               quote_c_style(other, &msg, NULL, 0);
+               strbuf_addch(&msg, '\n');
                break;
        case DIFF_STATUS_MODIFIED:
                if (p->score) {
-                       len += snprintf(msg + len, sizeof(msg) - len,
-                                       "dissimilarity index %d%%\n",
+                       strbuf_addf(&msg, "dissimilarity index %d%%\n",
                                        similarity_index(p));
                        complete_rewrite = 1;
                        break;
                            (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
                                abbrev = 40;
                }
-               len += snprintf(msg + len, sizeof(msg) - len,
-                               "index %.*s..%.*s",
+               strbuf_addf(&msg, "index %.*s..%.*s",
                                abbrev, sha1_to_hex(one->sha1),
                                abbrev, sha1_to_hex(two->sha1));
                if (one->mode == two->mode)
-                       len += snprintf(msg + len, sizeof(msg) - len,
-                                       " %06o", one->mode);
-               len += snprintf(msg + len, sizeof(msg) - len, "\n");
+                       strbuf_addf(&msg, " %06o", one->mode);
+               strbuf_addch(&msg, '\n');
        }
  
-       if (len)
-               msg[--len] = 0;
-       xfrm_msg = len ? msg : NULL;
+       if (msg.len)
+               strbuf_setlen(&msg, msg.len - 1);
+       xfrm_msg = msg.len ? msg.buf : NULL;
  
        if (!pgm &&
            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
                run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
                             complete_rewrite);
  
-       free(name_munged);
-       free(other_munged);
+       strbuf_release(&msg);
  }
  
  static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
@@@ -2518,72 -2458,30 +2463,30 @@@ const char *diff_unique_abbrev(const un
        return sha1_to_hex(sha1);
  }
  
- static void diff_flush_raw(struct diff_filepair *p,
-                          struct diff_options *options)
+ static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
  {
-       int two_paths;
-       char status[10];
-       int abbrev = options->abbrev;
-       const char *path_one, *path_two;
-       int inter_name_termination = '\t';
-       int line_termination = options->line_termination;
-       if (!line_termination)
-               inter_name_termination = 0;
+       int line_termination = opt->line_termination;
+       int inter_name_termination = line_termination ? '\t' : '\0';
  
-       path_one = p->one->path;
-       path_two = p->two->path;
-       if (line_termination) {
-               path_one = quote_one(path_one);
-               path_two = quote_one(path_two);
+       if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
+               printf(":%06o %06o %s ", p->one->mode, p->two->mode,
+                      diff_unique_abbrev(p->one->sha1, opt->abbrev));
+               printf("%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
        }
-       if (p->score)
-               sprintf(status, "%c%03d", p->status, similarity_index(p));
-       else {
-               status[0] = p->status;
-               status[1] = 0;
-       }
-       switch (p->status) {
-       case DIFF_STATUS_COPIED:
-       case DIFF_STATUS_RENAMED:
-               two_paths = 1;
-               break;
-       case DIFF_STATUS_ADDED:
-       case DIFF_STATUS_DELETED:
-               two_paths = 0;
-               break;
-       default:
-               two_paths = 0;
-               break;
-       }
-       if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
-               printf(":%06o %06o %s ",
-                      p->one->mode, p->two->mode,
-                      diff_unique_abbrev(p->one->sha1, abbrev));
-               printf("%s ",
-                      diff_unique_abbrev(p->two->sha1, abbrev));
+       if (p->score) {
+               printf("%c%03d%c", p->status, similarity_index(p),
+                          inter_name_termination);
+       } else {
+               printf("%c%c", p->status, inter_name_termination);
        }
-       printf("%s%c%s", status, inter_name_termination,
-                       two_paths || p->one->mode ?  path_one : path_two);
-       if (two_paths)
-               printf("%c%s", inter_name_termination, path_two);
-       putchar(line_termination);
-       if (path_one != p->one->path)
-               free((void*)path_one);
-       if (path_two != p->two->path)
-               free((void*)path_two);
- }
- static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
- {
-       char *path = p->two->path;
  
-       if (opt->line_termination)
-               path = quote_one(p->two->path);
-       printf("%s%c", path, opt->line_termination);
-       if (p->two->path != path)
-               free(path);
+       if (p->status == DIFF_STATUS_COPIED || p->status == DIFF_STATUS_RENAMED) {
+               write_name_quoted(p->one->path, stdout, inter_name_termination);
+               write_name_quoted(p->two->path, stdout, line_termination);
+       } else {
+               const char *path = p->one->mode ? p->one->path : p->two->path;
+               write_name_quoted(path, stdout, line_termination);
+       }
  }
  
  int diff_unmodified_pair(struct diff_filepair *p)
         * let transformers to produce diff_filepairs any way they want,
         * and filter and clean them up here before producing the output.
         */
-       struct diff_filespec *one, *two;
+       struct diff_filespec *one = p->one, *two = p->two;
  
        if (DIFF_PAIR_UNMERGED(p))
                return 0; /* unmerged is interesting */
  
-       one = p->one;
-       two = p->two;
        /* deletion, addition, mode or type change
         * and rename are all interesting.
         */
@@@ -2789,32 -2684,27 +2689,27 @@@ static void flush_one_pair(struct diff_
        else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
                diff_flush_raw(p, opt);
        else if (fmt & DIFF_FORMAT_NAME)
-               diff_flush_name(p, opt);
+               write_name_quoted(p->two->path, stdout, opt->line_termination);
  }
  
  static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
  {
-       char *name = quote_one(fs->path);
        if (fs->mode)
-               printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
+               printf(" %s mode %06o ", newdelete, fs->mode);
        else
-               printf(" %s %s\n", newdelete, name);
-       free(name);
+               printf(" %s ", newdelete);
+       write_name_quoted(fs->path, stdout, '\n');
  }
  
  
  static void show_mode_change(struct diff_filepair *p, int show_name)
  {
        if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
+               printf(" mode change %06o => %06o%c", p->one->mode, p->two->mode,
+                       show_name ? ' ' : '\n');
                if (show_name) {
-                       char *name = quote_one(p->two->path);
-                       printf(" mode change %06o => %06o %s\n",
-                              p->one->mode, p->two->mode, name);
-                       free(name);
+                       write_name_quoted(p->two->path, stdout, '\n');
                }
-               else
-                       printf(" mode change %06o => %06o\n",
-                              p->one->mode, p->two->mode);
        }
  }
  
@@@ -2844,12 -2734,11 +2739,11 @@@ static void diff_summary(struct diff_fi
                break;
        default:
                if (p->score) {
-                       char *name = quote_one(p->two->path);
-                       printf(" rewrite %s (%d%%)\n", name,
-                              similarity_index(p));
-                       free(name);
-                       show_mode_change(p, 0);
-               } else  show_mode_change(p, 1);
+                       puts(" rewrite ");
+                       write_name_quoted(p->two->path, stdout, ' ');
+                       printf("(%d%%)\n", similarity_index(p));
+               }
+               show_mode_change(p, !p->score);
                break;
        }
  }
@@@ -2863,14 -2752,14 +2757,14 @@@ struct patch_id_t 
  static int remove_space(char *line, int len)
  {
        int i;
-         char *dst = line;
-         unsigned char c;
+       char *dst = line;
+       unsigned char c;
  
-         for (i = 0; i < len; i++)
-                 if (!isspace((c = line[i])))
-                         *dst++ = c;
+       for (i = 0; i < len; i++)
+               if (!isspace((c = line[i])))
+                       *dst++ = c;
  
-         return dst - line;
+       return dst - line;
  }
  
  static void patch_id_consume(void *priv, char *line, unsigned long len)
diff --combined merge-recursive.c
index 97dcf9bf02d8f382ba63cfeef9d6dcb792c62f76,86767e6e8a37ce7874aa80b789cfef780fa9b136..4a5c77c3b632a9c0636848b933ef5395b01b7103
@@@ -85,64 -85,58 +85,59 @@@ struct stage_dat
        unsigned processed:1;
  };
  
- struct output_buffer
- {
-       struct output_buffer *next;
-       char *str;
- };
  static struct path_list current_file_set = {NULL, 0, 0, 1};
  static struct path_list current_directory_set = {NULL, 0, 0, 1};
  
  static int call_depth = 0;
  static int verbosity = 2;
 +static int rename_limit = -1;
  static int buffer_output = 1;
- static struct output_buffer *output_list, *output_end;
+ static struct strbuf obuf = STRBUF_INIT;
  
- static int show (int v)
+ static int show(int v)
  {
        return (!call_depth && verbosity >= v) || verbosity >= 5;
  }
  
- static void output(int v, const char *fmt, ...)
+ static void flush_output(void)
  {
-       va_list args;
-       va_start(args, fmt);
-       if (buffer_output && show(v)) {
-               struct output_buffer *b = xmalloc(sizeof(*b));
-               nfvasprintf(&b->str, fmt, args);
-               b->next = NULL;
-               if (output_end)
-                       output_end->next = b;
-               else
-                       output_list = b;
-               output_end = b;
-       } else if (show(v)) {
-               int i;
-               for (i = call_depth; i--;)
-                       fputs("  ", stdout);
-               vfprintf(stdout, fmt, args);
-               fputc('\n', stdout);
+       if (obuf.len) {
+               fputs(obuf.buf, stdout);
+               strbuf_reset(&obuf);
        }
-       va_end(args);
  }
  
- static void flush_output(void)
+ static void output(int v, const char *fmt, ...)
  {
-       struct output_buffer *b, *n;
-       for (b = output_list; b; b = n) {
-               int i;
-               for (i = call_depth; i--;)
-                       fputs("  ", stdout);
-               fputs(b->str, stdout);
-               fputc('\n', stdout);
-               n = b->next;
-               free(b->str);
-               free(b);
+       int len;
+       va_list ap;
+       if (!show(v))
+               return;
+       strbuf_grow(&obuf, call_depth * 2 + 2);
+       memset(obuf.buf + obuf.len, ' ', call_depth * 2);
+       strbuf_setlen(&obuf, obuf.len + call_depth * 2);
+       va_start(ap, fmt);
+       len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
+       va_end(ap);
+       if (len < 0)
+               len = 0;
+       if (len >= strbuf_avail(&obuf)) {
+               strbuf_grow(&obuf, len + 2);
+               va_start(ap, fmt);
+               len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
+               va_end(ap);
+               if (len >= strbuf_avail(&obuf)) {
+                       die("this should not happen, your snprintf is broken");
+               }
        }
-       output_list = NULL;
-       output_end = NULL;
+       strbuf_setlen(&obuf, obuf.len + len);
+       strbuf_add(&obuf, "\n", 1);
+       if (!buffer_output)
+               flush_output();
  }
  
  static void output_commit_title(struct commit *commit)
@@@ -373,7 -367,6 +368,7 @@@ static struct path_list *get_renames(st
        diff_setup(&opts);
        opts.recursive = 1;
        opts.detect_rename = DIFF_DETECT_RENAME;
 +      opts.rename_limit = rename_limit;
        opts.output_format = DIFF_FORMAT_NO_OUTPUT;
        if (diff_setup_done(&opts) < 0)
                die("diff setup failed");
@@@ -434,19 -427,15 +429,15 @@@ static int update_stages(const char *pa
  
  static int remove_path(const char *name)
  {
-       int ret, len;
+       int ret;
        char *slash, *dirs;
  
        ret = unlink(name);
        if (ret)
                return ret;
-       len = strlen(name);
-       dirs = xmalloc(len+1);
-       memcpy(dirs, name, len);
-       dirs[len] = '\0';
+       dirs = xstrdup(name);
        while ((slash = strrchr(name, '/'))) {
                *slash = '\0';
-               len = slash - name;
                if (rmdir(name) != 0)
                        break;
        }
@@@ -580,9 -569,7 +571,7 @@@ static void update_file_flags(const uns
                        flush_buffer(fd, buf, size);
                        close(fd);
                } else if (S_ISLNK(mode)) {
-                       char *lnk = xmalloc(size + 1);
-                       memcpy(lnk, buf, size);
-                       lnk[size] = '\0';
+                       char *lnk = xmemdupz(buf, size);
                        mkdir_p(path, 0777);
                        unlink(path);
                        symlink(lnk, path);
@@@ -874,14 -861,9 +863,9 @@@ static int read_merge_config(const cha
                if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
                        break;
        if (!fn) {
-               char *namebuf;
                fn = xcalloc(1, sizeof(struct ll_merge_driver));
-               namebuf = xmalloc(namelen + 1);
-               memcpy(namebuf, name, namelen);
-               namebuf[namelen] = 0;
-               fn->name = namebuf;
+               fn->name = xmemdupz(name, namelen);
                fn->fn = ll_ext_merge;
-               fn->next = NULL;
                *ll_user_merge_tail = fn;
                ll_user_merge_tail = &(fn->next);
        }
@@@ -1695,10 -1677,6 +1679,10 @@@ static int merge_config(const char *var
                verbosity = git_config_int(var, value);
                return 0;
        }
 +      if (!strcasecmp(var, "diff.renamelimit")) {
 +              rename_limit = git_config_int(var, value);
 +              return 0;
 +      }
        return git_default_config(var, value);
  }
  
diff --combined sha1_file.c
index 5801c3e71b43d80f7d65b21b100775b23455f533,753742a47cad1b27dc0d52ce7097cf106e4a40be..83a06a7aed84715db191b703e529d3501df0a8f2
@@@ -1491,11 -1491,8 +1491,8 @@@ found_cache_entry
                ent->lru.next->prev = ent->lru.prev;
                ent->lru.prev->next = ent->lru.next;
                delta_base_cached -= ent->size;
-       }
-       else {
-               ret = xmalloc(ent->size + 1);
-               memcpy(ret, ent->data, ent->size);
-               ((char *)ret)[ent->size] = 0;
+       } else {
+               ret = xmemdupz(ent->data, ent->size);
        }
        *type = ent->type;
        *base_size = ent->size;
@@@ -1684,22 -1681,22 +1681,22 @@@ off_t find_pack_entry_one(const unsigne
        return 0;
  }
  
 -static int matches_pack_name(struct packed_git *p, const char *ig)
 +int matches_pack_name(struct packed_git *p, const char *name)
  {
        const char *last_c, *c;
  
 -      if (!strcmp(p->pack_name, ig))
 -              return 0;
 +      if (!strcmp(p->pack_name, name))
 +              return 1;
  
        for (c = p->pack_name, last_c = c; *c;)
                if (*c == '/')
                        last_c = ++c;
                else
                        ++c;
 -      if (!strcmp(last_c, ig))
 -              return 0;
 +      if (!strcmp(last_c, name))
 +              return 1;
  
 -      return 1;
 +      return 0;
  }
  
  static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
                if (ignore_packed) {
                        const char **ig;
                        for (ig = ignore_packed; *ig; ig++)
 -                              if (!matches_pack_name(p, *ig))
 +                              if (matches_pack_name(p, *ig))
                                        break;
                        if (*ig)
                                goto next;
@@@ -1872,12 -1869,9 +1869,9 @@@ void *read_sha1_file(const unsigned cha
  
        co = find_cached_object(sha1);
        if (co) {
-               buf = xmalloc(co->size + 1);
-               memcpy(buf, co->buf, co->size);
-               ((char*)buf)[co->size] = 0;
                *type = co->type;
                *size = co->size;
-               return buf;
+               return xmemdupz(co->buf, co->size);
        }
  
        buf = read_packed_sha1(sha1, type, size);
@@@ -2302,68 -2296,25 +2296,25 @@@ int has_sha1_file(const unsigned char *
        return find_sha1_file(sha1, &st) ? 1 : 0;
  }
  
- /*
-  * reads from fd as long as possible into a supplied buffer of size bytes.
-  * If necessary the buffer's size is increased using realloc()
-  *
-  * returns 0 if anything went fine and -1 otherwise
-  *
-  * The buffer is always NUL-terminated, not including it in returned size.
-  *
-  * NOTE: both buf and size may change, but even when -1 is returned
-  * you still have to free() it yourself.
-  */
- int read_fd(int fd, char **return_buf, unsigned long *return_size)
- {
-       char *buf = *return_buf;
-       unsigned long size = *return_size;
-       ssize_t iret;
-       unsigned long off = 0;
-       if (!buf || size <= 1) {
-               size = 1024;
-               buf = xrealloc(buf, size);
-       }
-       do {
-               iret = xread(fd, buf + off, (size - 1) - off);
-               if (iret > 0) {
-                       off += iret;
-                       if (off == size - 1) {
-                               size = alloc_nr(size);
-                               buf = xrealloc(buf, size);
-                       }
-               }
-       } while (iret > 0);
-       buf[off] = '\0';
-       *return_buf = buf;
-       *return_size = off;
-       if (iret < 0)
-               return -1;
-       return 0;
- }
  int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
  {
-       unsigned long size = 4096;
-       char *buf = xmalloc(size);
+       struct strbuf buf;
        int ret;
  
-       if (read_fd(fd, &buf, &size)) {
-               free(buf);
+       strbuf_init(&buf, 0);
+       if (strbuf_read(&buf, fd, 4096) < 0) {
+               strbuf_release(&buf);
                return -1;
        }
  
        if (!type)
                type = blob_type;
        if (write_object)
-               ret = write_sha1_file(buf, size, type, sha1);
+               ret = write_sha1_file(buf.buf, buf.len, type, sha1);
        else
-               ret = hash_sha1_file(buf, size, type, sha1);
-       free(buf);
+               ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
+       strbuf_release(&buf);
        return ret;
  }
  
@@@ -2385,12 -2336,11 +2336,11 @@@ int index_fd(unsigned char *sha1, int f
         * Convert blobs to git internal format
         */
        if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
-               unsigned long nsize = size;
-               char *nbuf = convert_to_git(path, buf, &nsize);
-               if (nbuf) {
+               struct strbuf nbuf;
+               strbuf_init(&nbuf, 0);
+               if (convert_to_git(path, buf, size, &nbuf)) {
                        munmap(buf, size);
-                       size = nsize;
-                       buf = nbuf;
+                       buf = strbuf_detach(&nbuf, &size);
                        re_allocated = 1;
                }
        }