Fix memory corruption when .gitignore does not end by \n
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>
Nguyễn Thái Ngọc Duy committed
Jan 20, 2010 at 21:09 UTC
45d76f17182278d4c1de37b3eed60beb3b2f21ab
1 file changed
+13
-3
dir.c
+13
-3
@@ -242,6 +242,14 @@ int add_excludes_from_file_to_list(const char *fname,
242
if (!check_index ||
243
(buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
244
return -1;
245
+ if (size == 0) {
246
+ free(buf);
247
+ return 0;
248
+ }
249
+ if (buf[size-1] != '\n') {
250
+ buf = xrealloc(buf, size+1);
251
+ buf[size++] = '\n';
252
+ }
253
}
254
else {
255
size = xsize_t(st.st_size);
@@ -249,19 +257,21 @@ int add_excludes_from_file_to_list(const char *fname,
257
close(fd);
258
return 0;
259
}
252
- buf = xmalloc(size);
260
+ buf = xmalloc(size+1);
261
if (read_in_full(fd, buf, size) != size) {
262
+ free(buf);
263
close(fd);
264
return -1;
265
}
266
+ buf[size++] = '\n';
267
close(fd);
268
}
269
270
if (buf_p)
271
*buf_p = buf;
272
entry = buf;
263
- for (i = 0; i <= size; i++) {
264
- if (i == size || buf[i] == '\n') {
273
+ for (i = 0; i < size; i++) {
274
+ if (buf[i] == '\n') {
275
if (entry != buf + i && entry[0] != '#') {
276
buf[i - (i && buf[i-1] == '\r')] = 0;
277
add_exclude(entry, base, baselen, which);