Skip to content

Commit 45d76f1

Browse files
pcloudsgitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 19c61a5 commit 45d76f1

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

dir.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -242,26 +242,36 @@ int add_excludes_from_file_to_list(const char *fname,
242242
if (!check_index ||
243243
(buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
244244
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+
}
245253
}
246254
else {
247255
size = xsize_t(st.st_size);
248256
if (size == 0) {
249257
close(fd);
250258
return 0;
251259
}
252-
buf = xmalloc(size);
260+
buf = xmalloc(size+1);
253261
if (read_in_full(fd, buf, size) != size) {
262+
free(buf);
254263
close(fd);
255264
return -1;
256265
}
266+
buf[size++] = '\n';
257267
close(fd);
258268
}
259269

260270
if (buf_p)
261271
*buf_p = buf;
262272
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') {
265275
if (entry != buf + i && entry[0] != '#') {
266276
buf[i - (i && buf[i-1] == '\r')] = 0;
267277
add_exclude(entry, base, baselen, which);

0 commit comments

Comments
 (0)