[PATCH v2 4/7] packfile: fix open file descriptor counter when fstat(3p) fails
- From
Patrick Steinhardt <ps@pks.im>
- Date
- Dec 2, 2026, 13:19 UTC
- Message-ID
- <20261202-pks-packfile-global-statistics-v2-4-bb8be4aa552d@pks.im>
- In-Reply-To
- <20261202-pks-packfile-global-statistics-v2-0-bb8be4aa552d@pks.im>
We keep a counter file descriptors held open for packfiles so that we can close packfiles when we are at the verge of exceeding the maximum number of open file descriptors.
This counter is incremented when we open a packfile, but our accounting is slightly off: we open the pack and then immediately fstat(3p) it, but we only increment the counter in case both of these actions succeed. So in the case where the fstat(3p) fails, we won't increment the counter even though we have already opened the pack. But a subsequent call to `packfile_close_fd()` will decrement the counter again, and consequently the counter may now underflow.
This scenario feels rather unlikely, as we can expect that fstat(3p) will succeed when we were able to open the file. But it's a bug anyway, so let's fix it by incrementing the counter before calling fstat(3p).
Reported-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Patrick Steinhardt <ps@pks.im> --- packfile.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/packfile.c b/packfile.c index 9b03258311f..accfd230670 100644 --- a/packfile.c +++ b/packfile.c @@ -509,12 +509,17 @@ static int packfile_open_pack(struct packed_git *p) ; /* nothing */ p->pack_fd = git_open(p->pack_name); - if (p->pack_fd < 0 || fstat(p->pack_fd, &st)) { + if (p->pack_fd < 0) { ret = -1; goto out; } pack_open_fds++; + if (fstat(p->pack_fd, &st)) { + ret = -1; + goto out; + } + /* If we created the struct before we had the pack we lack size. */ if (!p->pack_size) { if (!S_ISREG(st.st_mode)) {
-- 2.98.0.rc0.245.g55e557da3a.dirty