Windows Subsystem for Linux – Why It Can Run Windows *.exe Programs

windowswindows 10windows-subsystem-for-linux

I'm using the new WLS2 on Windows 10 Home. I noticed that, when I ran "npm", the "npm" from my Windows program files was executed instead of the Linux version.

When I tried to execute cmd.exe or notepad.exe from WSL2, I noticed those also work!

How is this possible? How is WSL2 able to run Windows executables?

Additionally, how can I force WSL2 to prioritize the Linux executables over the Windows ones in cases where they have the same names?

Best Answer

How is WSL2 able to run Windows executables?

The Windows executable (PE binary) is added as a binfmt_misc entry in WSL2. In simple words, binfmt_misc is a Linux kernel feature which allows arbitrary executable file formats to be recognized and passed to certain programs.

In WSL2, the init binary (from which every process is forked) register the Windows PE binary as a executable and make it executable by itself (i.e. the init). Here is a output of the PE binfmt entry:

cat /proc/sys/fs/binfmt_misc/WSLInterop
enabled
interpreter /tools/init
flags: F
offset 0
magic 4d5a

WSLInterop is just a name for the entry. The magic number 4d5a is MZ which is first two bytes of Windows PE executable. Assume this is a fingerprint with which init (the interpreter) recognizes PE binary.

Users can disable the registry with this command:

echo 0 | sudo tee /proc/sys/fs/binfmt_misc/WSLInterop

Further readings:

Related Question