repository: free fields before overwriting them

It's possible that the repository data may be initialized twice (e.g., after doing a chdir() to the top of the worktree we may have to adjust a relative git_dir path). We should free() any existing fields before assigning to them to avoid leaks. This should be safe, as the fields are set based on the environment or on other strings like the gitdir or commondir. That makes it impossible that we are feeding an alias to the just-freed string. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Sep 5, 2017 at 09:04 UTC f9b7573f6b0039d298de826e22c636db79b9c919
2 files changed +7 -1
environment.c
+3 -1
@@ -97,7 +97,7 @@ int ignore_untracked_cache_config;
97 /* This is set by setup_git_dir_gently() and/or git_default_config() */
98 char *git_work_tree_cfg;
99
100 -static const char *namespace;
100 +static char *namespace;
101
102 static const char *super_prefix;
103
@@ -152,8 +152,10 @@ void setup_git_env(void)
152 if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT))
153 check_replace_refs = 0;
154 replace_ref_base = getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT);
155 + free(git_replace_ref_base);
156 git_replace_ref_base = xstrdup(replace_ref_base ? replace_ref_base
157 : "refs/replace/");
158 + free(namespace);
159 namespace = expand_namespace(getenv(GIT_NAMESPACE_ENVIRONMENT));
160 shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT);
161 if (shallow_file)
repository.c
+4
@@ -40,11 +40,15 @@ static void repo_setup_env(struct repository *repo)
40
41 repo->different_commondir = find_common_dir(&sb, repo->gitdir,
42 !repo->ignore_env);
43 + free(repo->commondir);
44 repo->commondir = strbuf_detach(&sb, NULL);
45 + free(repo->objectdir);
46 repo->objectdir = git_path_from_env(DB_ENVIRONMENT, repo->commondir,
47 "objects", !repo->ignore_env);
48 + free(repo->graft_file);
49 repo->graft_file = git_path_from_env(GRAFT_ENVIRONMENT, repo->commondir,
50 "info/grafts", !repo->ignore_env);
51 + free(repo->index_file);
52 repo->index_file = git_path_from_env(INDEX_ENVIRONMENT, repo->gitdir,
53 "index", !repo->ignore_env);
54 }