environment: move strbuf into block to plug leak

realpath is only populated if we execute the git_work_tree_initialized block. However that block also causes us to return early, meaning we never actually release the strbuf in the case where we populated it. Therefore we move all strbuf related code into the block to guarantee that we can't leak it. LSAN output from t0095: Direct leak of 129 byte(s) in 1 object(s) allocated from: #0 0x49a9b9 in realloc ../projects/compiler-rt/lib/asan/asan_malloc_linux.cpp:164:3 #1 0x78f585 in xrealloc wrapper.c:126:8 #2 0x713ff4 in strbuf_grow strbuf.c:98:2 #3 0x713ff4 in strbuf_getcwd strbuf.c:597:3 #4 0x4f0c18 in strbuf_realpath_1 abspath.c:99:7 #5 0x5ae4a4 in set_git_work_tree environment.c:259:3 #6 0x6fdd8a in setup_discovered_git_dir setup.c:931:2 #7 0x6fdd8a in setup_git_directory_gently setup.c:1235:12 #8 0x4cb50d in get_bloom_filter_for_commit t/helper/test-bloom.c:41:2 #9 0x4cb50d in cmd__bloom t/helper/test-bloom.c:95:3 #10 0x4caa1f in cmd_main t/helper/test-tool.c:124:11 #11 0x4caded in main common-main.c:52:11 #12 0x7f0869f02349 in __libc_start_main (/lib64/libc.so.6+0x24349) SUMMARY: AddressSanitizer: 129 byte(s) leaked in 1 allocation(s). It looks like this leak has existed since realpath was first added to set_git_work_tree() in: 3d7747e318 (real_path: remove unsafe API, 2020-03-10) Signed-off-by: Andrzej Hunt <andrzej@ahunt.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Andrzej Hunt committed Jul 25, 2021 at 15:08 UTC 14c3dd817dbdb957e22ebc9f2e8d78a2f901ef7f
1 file changed +3 -4
environment.c
+3 -4
@@ -253,21 +253,20 @@ static int git_work_tree_initialized;
253 */
254 void set_git_work_tree(const char *new_work_tree)
255 {
256 - struct strbuf realpath = STRBUF_INIT;
257 -
256 if (git_work_tree_initialized) {
257 + struct strbuf realpath = STRBUF_INIT;
258 +
259 strbuf_realpath(&realpath, new_work_tree, 1);
260 new_work_tree = realpath.buf;
261 if (strcmp(new_work_tree, the_repository->worktree))
262 die("internal error: work tree has already been set\n"
263 "Current worktree: %s\nNew worktree: %s",
264 the_repository->worktree, new_work_tree);
265 + strbuf_release(&realpath);
266 return;
267 }
268 git_work_tree_initialized = 1;
269 repo_set_worktree(the_repository, new_work_tree);
269 -
270 - strbuf_release(&realpath);
270 }
271
272 const char *get_git_work_tree(void)