Hi Mark,

On Mon, May 18, 2026 at 2:27 PM Mark Wielaard <[email protected]> wrote:
>
> With -o elfcompress opens the output file with O_WRONLY and O_CREAT.
> If the output file already existed then without O_TRUNC the file is
> written from the start, but keeps all existing data. That means the
> file might contain extra data if the (compressed) ELF file is shorter
> than the existing file. Make sure to add O_TRUNC.
>
>         * src/elfcompress.c (process_file): Add O_TRUNC to open call.
>
> Signed-off-by: Mark Wielaard <[email protected]>

This patch introduces a regression for `eu-elfcompress -o foo foo`
(input file is also the output file) where foo is now always deleted.
O_TRUNC zero-truncates foo and then tries to read from it.  This fails
and causes foo to be unlinked during error cleanup. elfcompress does
use mkstemp+rename, which would prevent this bug, but they're only
used when -o is absent.

We should extend the mkstemp+rename case to fix this.  We apply this
for -o only when the input and output files match or we can apply it
unconditionally for -o.  I think it should be unconditional because it
also prevents a preexisting output file (in this case distinct from
the input file) from being zero-truncated and deleted if
eu-elfcompress encounters an error.

Aaron

> ---
>  src/elfcompress.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/src/elfcompress.c b/src/elfcompress.c
> index 25ebd1be5c62..789bcb383786 100644
> --- a/src/elfcompress.c
> +++ b/src/elfcompress.c
> @@ -616,7 +616,7 @@ process_file (const char *fname)
>    else
>      {
>        fnew = xstrdup (foutput);
> -      fdnew = open (fnew, O_WRONLY | O_CREAT, st.st_mode & ALLPERMS);
> +      fdnew = open (fnew, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode & 
> ALLPERMS);
>      }
>
>    if (fdnew < 0)
> --
> 2.53.0
>

Reply via email to