Search code examples
macosexecsystem-callsdarwin

fexecve equivalent on macOS


I use fexecve(3) on Linux to execute a binary held in a memfd.

Is there an equivalent for macOS? I've tried execve("/dev/fd/%d", [], []), but it failed with EACCES. Copying the file from that path /dev/fd/%d to a new temporary file and exec'ing that does work.

Is there a way to do this without creating the temporary file?


Solution

  • There is no officially supported way to do this for arbitrary file handles. There are hacks, used primarily by malware, to achieve the effect using NSCreateObjectFileImageFromMemory and lying about the type of the file, but without the hacks, it's limited to bundle files, it's not usable for arbitrary executables.

    So, if you're using bundle files, you can do it with some documented support, but if you're not using bundle files, and you're trying to write portable, production-quality code, there's no sane way to do this (the hacks used to run arbitrary code being brittle, relying on undocumented behaviors).