I found out that if I execute a Windows native program (PE) from WSL2, accessing a POSIX path magically works.
For example, I can access /dev/random if I execute my program from WSL bash, but if I execute the same program from CMD (command-prompt), I cannot.
I must understand the mechanism which allows this! :)
The test program is fairly simple:
#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
printf("%p\n", fopen("/dev/urandom", "r"));
return 0;
}
If I execute this from inside the WSL instance, it succeeds opening the device.
If I execute this via CMD, however, it fails.
When I look at API mon, I can see that the open("/dev/urandom", "r") is converted to CreateFileA("\\wsl.localhost\Ubuntu\dev\urandom", ...).
First question: What component is doing this conversion?
If I replace the fopen with CreateFile it fails... so it must be something in the stdio functions.
Second question: How does it know what WSL instance is the parent?
I saw no API query, no environment to give me a hint. The only abnormality I can see is the opening \\wsl.localhost\Ubuntu\tmp during process startup.
Third question: Does this survive nested within process tree?
When I execute cmd.exe from inside WSL, then execute my test program, it fails.
However, I wrote my own native Windows program that executes my test program and the test program succeeds, so this behavior does survive process tree.
Can anyone explain the mechanism that allows this magic to work? What API? What component is doing the transition? Where is the context stored? How is it queried? How does it knows what distro to lookup?
I tried to ask this at Microsoft discussion[1] and got no response, so I am hopping someone here may be able to provide a hint.