git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH v2 3/4] t/helper/test-delta: close fd if fstat() fails after open()

From
Eric Sunshine <sunshine@sunshineco.com>
Date
Jul 22, 2025, 08:36 UTC
Message-ID
<CAPig+cT1hzz4_7JqesqFmgYdpsNezurcsF9XF1ep8KzvgMUc2Q@mail.gmail.com>
In-Reply-To
<20250722081219.1086866-4-lhywkd22@gmail.com>
On Tue, Jul 22, 2025 at 4:12 AM Hoyoung Lee <lhywkd22@gmail.com> wrote:
Show 14 quoted lines
> If open() succeeds but fstat() fails, the file descriptor is not
> closed, causing a resource leak. This patch adds a close(fd) call
> in the failure path after fstat() to ensure proper resource cleanup.
>
> Signed-off-by: Hoyoung Lee <lhywkd22@gmail.com>
> ---
> diff --git a/t/helper/test-delta.c b/t/helper/test-delta.c
> @@ -31,6 +31,7 @@ int cmd__delta(int argc, const char **argv)
>         fd = open(argv[2], O_RDONLY);
>         if (fd < 0 || fstat(fd, &st)) {
>                 perror(argv[2]);
> +               close(fd);
>                 return 1;
>         }

One condition under which this block is entered is if `fd` is less than 0, which means close() is now being called with a negative file descriptor, which seems quite suspect. I'd think you would want to either restructure it into two `if` statements:

    if (fd < 0) {
        ...
        return 1;
    }
    if (fstat(fd, ...)) {
        ...
        return 1;
    }
or at least protect the call to close():
    if (fd < 0 || fstat(fd, ...)) {
        ...
        if (fd >= 0)
            close(fd);
        return 1;
    }

I think the separate `if` statements are probably a bit easier to reason about, but it is of course subjective.

Previous: Hoyoung LeeNext: Jeff King
Message 6 of 12 in “Fix resource leaks in various helpers and builtin commands”
  1. 0/4 Fix resource leaks in various helpers and builtin commandsHoyoung Lee, Jul 22, 2025
  2. 1/4 t/helper/test-truncate: close file descriptor after truncationHoyoung Lee, Jul 22, 2025
  3. 2/4 builtin/archive: close file descriptor on dup2() failureHoyoung Lee, Jul 22, 2025
  4. Jeff KingJul 22, 2025
  5. 3/4 t/helper/test-delta: close fd if fstat() fails after open()Hoyoung Lee, Jul 22, 2025
  6. Eric SunshineJul 22, 2025
  7. Jeff KingJul 22, 2025
  8. 4/4 t/helper/test-delta: close fd if fstat() fails after second open()Hoyoung Lee, Jul 22, 2025
  9. Jeff KingJul 22, 2025
  10. Jeff KingJul 22, 2025
  11. Junio C HamanoJul 22, 2025
  12. Jeff KingJul 22, 2025

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.