0

Is there a way to test whether a file, if I mark it as executable with chmod +x file and run it with ./file will cause the operating system to execute it (or at least attempt to execute it), without actually executing it?

So far I have:

  1. On Mac and Linux (or other Unix), test whether the first two bytes are #!.
  2. On Linux, test whether the first four bytes are 0x7f454c46 (ELF magic number) and the e_type (offset 0x10) is ET_EXEC (0x0002).
  3. On Mac, check if the file is Mach-O and filetype is MH_EXECUTE. (Mach-O format is a bit more complicated and I haven't figured out the exact magic number(s) and offset for filetype yet.)
  4. ...other executable formats?

Is there a way to do this more easily and correctly?

Jesse
  • 6,725
  • 5
  • 40
  • 45
  • 2
    Under Linux, when correctly configured (e.g. using the binfmt mechanism), just about anything could potentially be executable. This sounds like an [XY problem](http://xyproblem.info/); what is your goal here? – larsks Dec 05 '19 at 14:51
  • I have a *huge* tree of files many of which have the executable bit set when they shouldn't, and many of which don't have the executable bit set when they should. I think this is because a lot of the files were copied to/from filesystems without executable bits. So I want all the files that could theoretically be executed to be executable and all the ones that couldn't to not be executable. It's not perfect but it's the closest I can get to being correct without manually going through every single file. – Jesse Dec 05 '19 at 15:09
  • @larsks Is there a way to ask the kernel whether a given file would be accepted by its current binfmt configuration? – Jesse Dec 05 '19 at 17:17
  • 1
    `man file` and running `file ...` can help here a bit. – 0andriy Dec 05 '19 at 18:26
  • 2
    Possible duplicate of [Check if a file is executable](https://stackoverflow.com/q/10319652/608639) – jww Dec 06 '19 at 07:08

0 Answers0