Skip to content

Commit 38ae878

Browse files
peffgitster
authored andcommitted
read_gitfile_gently: fix use-after-free
The "dir" variable is a pointer into the "buf" array. When we hit the cleanup_return path, the first thing we do is free(buf); but one of the error messages prints "dir", which will access the memory after the free. We can fix this by reorganizing the error path a little. We act on the fatal, error-printing conditions first, as they want to access memory and do not care about freeing. Then we free any memory, and finally return. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 0179ca7 commit 38ae878

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

setup.c

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -479,19 +479,14 @@ const char *read_gitfile_gently(const char *path, int *return_error_code)
479479
path = real_path(dir);
480480

481481
cleanup_return:
482-
free(buf);
483-
484482
if (return_error_code)
485483
*return_error_code = error_code;
486-
487-
if (error_code) {
488-
if (return_error_code)
489-
return NULL;
490-
484+
else if (error_code) {
491485
switch (error_code) {
492486
case READ_GITFILE_ERR_STAT_FAILED:
493487
case READ_GITFILE_ERR_NOT_A_FILE:
494-
return NULL;
488+
/* non-fatal; follow return path */
489+
break;
495490
case READ_GITFILE_ERR_OPEN_FAILED:
496491
die_errno("Error opening '%s'", path);
497492
case READ_GITFILE_ERR_TOO_LARGE:
@@ -509,7 +504,8 @@ const char *read_gitfile_gently(const char *path, int *return_error_code)
509504
}
510505
}
511506

512-
return path;
507+
free(buf);
508+
return error_code ? NULL : path;
513509
}
514510

515511
static const char *setup_explicit_git_dir(const char *gitdirenv,

0 commit comments

Comments
 (0)