Skip to content

Commit 1fb2b63

Browse files
peffgitster
authored andcommitted
set_git_dir: handle feeding gitdir to itself
Ideally we'd free the existing gitdir field before assigning the new one, to avoid a memory leak. But we can't do so safely because some callers do the equivalent of: set_git_dir(get_git_dir()); We can detect that case as a noop, but there are even more complicated cases like: set_git_dir(remove_leading_path(worktree, get_git_dir()); where we really do need to do some work, but the original string must remain valid. Rather than put the burden on callers to make a copy of the string (only to free it later, since we'll make a copy of it ourselves), let's solve the problem inside set_git_dir(). We can make a copy of the pointer for the old gitdir, and then avoid freeing it until after we've made our new copy. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent f9b7573 commit 1fb2b63

File tree

2 files changed

+3
-12
lines changed

2 files changed

+3
-12
lines changed

repository.c

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,12 @@ static void repo_setup_env(struct repository *repo)
5656
void repo_set_gitdir(struct repository *repo, const char *path)
5757
{
5858
const char *gitfile = read_gitfile(path);
59+
char *old_gitdir = repo->gitdir;
5960

60-
/*
61-
* NEEDSWORK: Eventually we want to be able to free gitdir and the rest
62-
* of the environment before reinitializing it again, but we have some
63-
* crazy code paths where we try to set gitdir with the current gitdir
64-
* and we don't want to free gitdir before copying the passed in value.
65-
*/
6661
repo->gitdir = xstrdup(gitfile ? gitfile : path);
67-
6862
repo_setup_env(repo);
63+
64+
free(old_gitdir);
6965
}
7066

7167
/*

setup.c

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -399,11 +399,6 @@ void setup_work_tree(void)
399399
if (getenv(GIT_WORK_TREE_ENVIRONMENT))
400400
setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
401401

402-
/*
403-
* NEEDSWORK: this call can essentially be set_git_dir(get_git_dir())
404-
* which can cause some problems when trying to free the old value of
405-
* gitdir.
406-
*/
407402
set_git_dir(remove_leading_path(git_dir, work_tree));
408403
initialized = 1;
409404
}

0 commit comments

Comments
 (0)