Re: Strangeness when binary executable overwritten by text -- bug or feature?
- Date: Wed, 31 Oct 2018 10:42:51 -0400
- From: Greg Wooledge <wooledg@xxxxxxxxxxx>
- Subject: Re: Strangeness when binary executable overwritten by text -- bug or feature?
On Wed, Oct 31, 2018 at 05:27:58PM +0300, Reco wrote:
> A (mis)feature. Any executable text file without defined shebang is a
> shell script.
Not quite. An attempt to execute a file that doesn't have a valid magic
number in the first few bytes triggers an ENOEXEC from the execve(2) call.
If this attempt was made by a C program, then that's that. You handle
the error however you choose to handle it.
However, it the attempt to execute the file was done by a shell, then
the shell will typically catch the ENOEXEC and then make a second attempt.
The exact mechanism for this secondary attempt depends on the shell.
Bash reads the first hundred bytes or so looking for NUL bytes. If it
sees a NUL byte, it decides the file is *not* a script, and you get
"Exec format error" printed on stderr. If there are no NUL bytes, then
bash launches a child bash process to read the file as a script.
Other shells may launch a copy of themselves, or they may choose to
launch /bin/sh or sh instead, or they may print an error. GNU's find
-exec launches sh, but I'm uncertain whether that's a GNUism, or a de
facto standard practice.
> In this case - a syntactically invalid shell script.
> So it can be executed, but the child shell will exit immediately.
If there's a syntax error, you'd expect to see a message. It's possible
that the "script" simply does nothing (e.g. it runs "exit" or "exec true"
or something similar before any commands that would produce output or
There's really no way to be more precise without a copy of the file's
content for analysis, and some knowledge of how and in what environment
the OP attempted to execute it. And we all know that these things will
not be provided.