Skip to content

Commit

Permalink
Fix memory corruption when .gitignore does not end by \n
Browse files Browse the repository at this point in the history
Commit b5041c5 (Avoid writing to buffer in add_excludes_from_file_1())
tried not to append '\n' at the end because the next commit
may return a buffer that does not have extra space for that.

Unfortunately it left this assignment in the loop:

  buf[i - (i && buf[i-1] == '\r')] = 0;

that can corrupt memory if "buf" is not '\n' terminated. But even if
it does not corrupt memory, the last line would not be
NULL-terminated, leading to errors later inside add_exclude().

This patch fixes it by reverting the faulty commit and make
sure "buf" is always \n terminated.

While at it, free unused memory properly.

Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Loading branch information
Nguyễn Thái Ngọc Duy authored and Junio C Hamano committed Jan 21, 2010
1 parent 19c61a5 commit 45d76f1
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions dir.c
Original file line number Diff line number Diff line change
Expand Up @@ -242,26 +242,36 @@ int add_excludes_from_file_to_list(const char *fname,
if (!check_index ||
(buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
return -1;
if (size == 0) {
free(buf);
return 0;
}
if (buf[size-1] != '\n') {
buf = xrealloc(buf, size+1);
buf[size++] = '\n';
}
}
else {
size = xsize_t(st.st_size);
if (size == 0) {
close(fd);
return 0;
}
buf = xmalloc(size);
buf = xmalloc(size+1);
if (read_in_full(fd, buf, size) != size) {
free(buf);
close(fd);
return -1;
}
buf[size++] = '\n';
close(fd);
}

if (buf_p)
*buf_p = buf;
entry = buf;
for (i = 0; i <= size; i++) {
if (i == size || buf[i] == '\n') {
for (i = 0; i < size; i++) {
if (buf[i] == '\n') {
if (entry != buf + i && entry[0] != '#') {
buf[i - (i && buf[i-1] == '\r')] = 0;
add_exclude(entry, base, baselen, which);
Expand Down

0 comments on commit 45d76f1

Please sign in to comment.