Check if a file is a valid Linux executable

Godot Version

4.4.1

Question

I am making a software launcher for Windows and Linux, and for some checks I want to see if the files alleged location is pointed to an executable.

Luckily for windows this is as easy as location.get_extension() == "exe", but for Linux as I have found out they use file metadata to determine if a file is executable or not.

Is there a way to easily check this in Godot? Originally I was just going to load the file and check the respective bytes but seemingly its more complex then that; so does Godot have a method for doing this / is there an easy way to check this?

Thanks.

Even on windows that check isn’t guaranteed, as anyone can change the extension of a file to be anything else they wish.

What you really need to do is check for “magic numbers” that are present in the file.

For windows:

0x4d, 0x5a. This is the "magic number" of an EXE file. The first byte of the file is 0x4d and the second is 0x5a.
Source: https://www.delorie.com/djgpp/doc/exe/

For linux, the easiest way to do this is to use the build-in command called file

I believe you can open a file to read it with GDScript easily, so you can check the first and second byte on windows, and on linux, I believe the OS.execute can be used on linux to execute a linux terminal command, see:

Could’ve also just Googled it. But sure.

3 Likes

Linux uses the ELF file format, which has the magic numbers: 0x7f ‘E’ ‘L’ ‘F’. See Executable and Linkable Format - Wikipedia.

2 Likes

I wasn’t entirely sure if the OP also wanted to include bash scripts, as they’re technically executables too, so using the file command, they can check themselves and determine what files they want to mark as executable and which ones they don’t.

The file command is indeed more versatile if OP doesn’t want to maintain his own file type detection.

From what I have heard when asking / searching about this Linux does not require these header bits to be set like Windows does for a file to be executable, unless I am mistaken?

What is executable in Linux is ultimately up to the kernel, and when configuring your kernel you can actually set/change that if you really want to.

Personally, I’d probably OS.execute_with_pipe("file", [exec_name], false) to determine if something is executable from Godot.

1 Like

I suppose there are clever ways to fool every foolproof system, but you can generally rely on an ELF file to be executable. As others have pointed out, the file command can be used for this purpose. It does a lot of gruntwork so you don’t have to.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.