[PATCH] ld: Rename a file on Windows fails if target already exists

Torbjorn SVENSSON torbjorn.svensson@foss.st.com
Fri Jul 18 16:36:06 GMT 2025


Hi,

To clarify, this started to fail GCC tests with the 2.44 release on Windows.

Kind regards,
Torbjörn

On 2025-07-18 17:20, Torbjörn SVENSSON wrote:
> Ok for trunk?
> 
> @Nick: Is this something that should be considered for 2.45 branch?
> 
> --
> 
> To rename a file on Windows, the target name cannot exist. Removing file
> prior to renaming ensures this is handled.
> To remove a file on Windows, the file cannot be open. Closing the bfd
> handle ensures this is handled.
> 
> Signed-off-by: Torbjörn SVENSSON <torbjorn.svensson@foss.st.com>
> ---
>   ld/ldlang.c | 13 +++++++++++++
>   1 file changed, 13 insertions(+)
> 
> diff --git a/ld/ldlang.c b/ld/ldlang.c
> index d4b4ef2f29b..ffc3362db29 100644
> --- a/ld/ldlang.c
> +++ b/ld/ldlang.c
> @@ -10834,6 +10834,11 @@ cmdline_add_object_only_section (bfd_byte *contents, size_t size)
>         goto loser;
>       }
>   
> +  if (!bfd_close (ibfd))
> +    {
> +      einfo (_("%P%F: failed to close input\n"));
> +    }
> +
>     if (!bfd_close (obfd))
>       {
>         unlink (ofilename);
> @@ -10844,6 +10849,12 @@ cmdline_add_object_only_section (bfd_byte *contents, size_t size)
>     free (isympp);
>     free (osympp);
>   
> +  /* Must unlink to ensure rename works on Windows.  */
> +  if (unlink (output_filename) && errno != ENOENT)
> +    {
> +      einfo (_("%P%F: failed to unlink %s\n"), output_filename);
> +    }
> +
>     if (rename (ofilename, output_filename))
>       {
>         unlink (ofilename);
> @@ -10856,6 +10867,8 @@ cmdline_add_object_only_section (bfd_byte *contents, size_t size)
>   loser:
>     free (isympp);
>     free (osympp);
> +  if (ibfd)
> +    bfd_close (ibfd);
>     if (obfd)
>       bfd_close (obfd);
>     if (ofilename)



More information about the Binutils mailing list