Is there a way to execute a native binary from a pipe?

I don't believe this is possible. The exec(2) system call always requires a filename or absolute path (the filename is always a char*). posix_spawn also has similar requirements for a filename.

The closest you could do is pipe the output into a named pipe and try executing from the pipe. That may work, although the shell may refuse to execute any file that does not have the --x--x--x bits set. Create the pipe with mkfifo(1) and see if you can get it to work.

Another approach would be to write something that reads standard input, writes a file out to a temporay area, sets the --x bits on it, forks and execs then deletes the file. The inode and contents will remain until the program finishes executing but it won't be accessible through the file system. When the process terminates the inode will be released and storage will be returned to the free list.

EDIT: As Mat points out, the first approach won't work as the loader will attempt to demand-page in the executable, which will generate random seek traffic on the file, and this isn't possible on a pipe. This leaves some sort of approach like the second.


A solution using memfd syscall: https://github.com/abbat/elfexec

It creates a named file descriptor in memory which could be used in exec. A pseudo-code:

#include <linux/memfd.h>
...
int memfd = syscall(SYS_memfd_create, "someName", 0);
...
write(memfd,... elf-content...);
...
fexecve(memfd, argv, environ);

You could try tcc, which will compile and execute a program in one step, without writing any intermediate files. It's not gcc, which may be a problem for you, but it is spectacularly fast, so it may even bet better than gcc for your purposes.