set_git_dir: handle feeding gitdir to itself
authorJeff King <peff@peff.net>
Tue, 5 Sep 2017 13:05:01 +0000 (09:05 -0400)
committerJunio C Hamano <gitster@pobox.com>
Wed, 6 Sep 2017 09:06:26 +0000 (18:06 +0900)
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 <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
repository.c
setup.c
index 52f1821c6b4c871c86699add1cc88956424173ea..97c732bd48ca8776203ae0936fe8ee61bb330ad9 100644 (file)
@@ -56,16 +56,12 @@ static void repo_setup_env(struct repository *repo)
 void repo_set_gitdir(struct repository *repo, const char *path)
 {
        const char *gitfile = read_gitfile(path);
+       char *old_gitdir = repo->gitdir;
 
-       /*
-        * NEEDSWORK: Eventually we want to be able to free gitdir and the rest
-        * of the environment before reinitializing it again, but we have some
-        * crazy code paths where we try to set gitdir with the current gitdir
-        * and we don't want to free gitdir before copying the passed in value.
-        */
        repo->gitdir = xstrdup(gitfile ? gitfile : path);
-
        repo_setup_env(repo);
+
+       free(old_gitdir);
 }
 
 /*
diff --git a/setup.c b/setup.c
index 23950173fc01268320d2e23c36ef80a1b1231a5e..6d8380acd2b66ee7d8206639d4b03933afb1816e 100644 (file)
--- a/setup.c
+++ b/setup.c
@@ -399,11 +399,6 @@ void setup_work_tree(void)
        if (getenv(GIT_WORK_TREE_ENVIRONMENT))
                setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
 
-       /*
-        * NEEDSWORK: this call can essentially be set_git_dir(get_git_dir())
-        * which can cause some problems when trying to free the old value of
-        * gitdir.
-        */
        set_git_dir(remove_leading_path(git_dir, work_tree));
        initialized = 1;
 }