From 8bc69c6b80ed42888327331b1567cecf7225ea7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20A=C3=9Fhauer?= Date: Sat, 25 Jul 2026 11:16:57 +0200 Subject: [PATCH 1/2] worktree: don't read out of bounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `worktree_basename` tries to read from memory before the passed `path` string, if `path` is empty (or only consists of directory separators). That results in unexpected nonsense data being returned to the caller, which can lead to issues, such as `git worktree add ""` recursively deleting the current working directory, including `.git`. Stop reading out of bounds in these cases to avoid that behaviour. This leads to `git worktree add ""` consistently exiting with the message `BUG: How come '' becomes empty after sanitization?`, which is still undesirable, but at least it doesn't result in data loss anymore. This fixes https://github.com/git-for-windows/git/issues/6346 Signed-off-by: Matthias Aßhauer --- builtin/worktree.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/builtin/worktree.c b/builtin/worktree.c index 4bc7b4f6e7199a..d8188035dbb06c 100644 --- a/builtin/worktree.c +++ b/builtin/worktree.c @@ -297,17 +297,21 @@ static void remove_junk_on_signal(int signo) static const char *worktree_basename(const char *path, int *olen) { const char *name; - int len; + int len, len2; - len = strlen(path); + len2 = len = strlen(path); while (len && is_dir_sep(path[len - 1])) len--; - for (name = path + len - 1; name > path; name--) - if (is_dir_sep(*name)) { - name++; - break; - } + if(len) { + for (name = path + len - 1; name > path; name--) + if (is_dir_sep(*name)) { + name++; + break; + } + } + else + name = path + len2; *olen = len; return name; From ec682d75f3a7848dc36f82cf36bbdff6fd283e2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20A=C3=9Fhauer?= Date: Sat, 25 Jul 2026 11:31:52 +0200 Subject: [PATCH 2/2] worktree: reject empty string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `git worktree add ""` errors out with the message `BUG: How come '' becomes empty after sanitization?`, but not due to a bug in the sanitization code. An empty string should remain empty during sanitization. Instead reject the argument as invalid user input, if it's already empty before sanitization. Signed-off-by: Matthias Aßhauer --- builtin/worktree.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/builtin/worktree.c b/builtin/worktree.c index d8188035dbb06c..113dbf98d3a145 100644 --- a/builtin/worktree.c +++ b/builtin/worktree.c @@ -496,6 +496,8 @@ static int add_worktree(const char *path, const char *refname, die(_("invalid reference: %s"), refname); name = worktree_basename(path, &len); + if (!len) + die(_("the empty string is not a valid worktree")); strbuf_add(&sb, name, path + len - name); sanitize_refname_component(sb.buf, &sb_name); if (!sb_name.len)