Hi Mark,

On Thu, May 21, 2026 at 1:48 PM Mark Wielaard <[email protected]> wrote:
> On Tue, 2026-05-19 at 18:10 -0400, Aaron Merey wrote:
> > 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.
>
> Groan. You are right of course. But is this a reasonable use of -o?
> I think we should detect when input == output file and either reject it
> or (silently/warning?) treat it as if -o wasn't given (so we would do
> the mkstemp+rename dance just for input == output but not otherwise).

eu-strip, eu-unstrip and eu-elfcompress (without this patch applied)
support using -o like this and as far as I can tell it just works. So
there is a precedent for this behaviour.

>
> > 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.
>
> Maybe we can use open O_CREAT + O_EXCL ? If that succeeds, then we just
> created a new file and can write to it directly. Otherwise we do the
> mkstemp+rename dance? I think that should fix both the -o output ==
> input case and the existing file gets truncated "too early" case.

That sounds reasonable to me.

Aaron

>
> Cheers,
>
> Mark
>

Reply via email to