Why is the value of the ProgramFiles environment variable replaced with that of ProgramFiles(x86)?

Jan. 23, 2012

Why is the value of the %ProgramFiles% environment variable replaced with the value of %ProgramFiles(x86)% when accessing it from a 32-bit program launched in a 64-bit operating system?

When a 32-bit application launched in a 64-bit Windows addresses the system environment variables %ProgramFiles% or %commonprogramfiles%, the WoW64 subsystem replaces the values of these variables with the values of the variables %ProgramFiles(x86)% and "%commonprogramfiles(x86)%. Thus, for instance, %ProgramFiles% will be opened as "C:\Program Files (x86)" when addressing from a 32-bit program.

This behavior is determined by the register redirection system that provides backward compatibility of 32-bit software with 64-bit operating systems. The 32-bit environment is emulated for 32-bit programs even despite the fact that the data they are addressing is located in a different place.

To avoid such a redirection in a 32-bit program, you should use the %programfiles% or %COMMONPROGRAMFILES% (i.e. with reverse case) environment variables or the KEY_WOW64_64KEY flag when accessing the corresponding register nodes.

To completely disable the file system redirection mechanism in the given thread, you may use the functions Wow64DisableWow64FsRedirection / Wow64RevertWow64FsRedirection but using them usually causes issues with implicit calls and delayed library loading. Developers rarely have complete control over the whole input-output process in the area between Wow64DisableWow64FsRedirection and Wow64RevertWow64FsRedirection and if code is implicitly loaded at the moment when the redirection mechanism is disabled, a 32-bit application will most probably fail to get the necessary version of the library. Alexey Pahunov, one of the WoW64 developers, advises to use this pair of functions only to wrap the call of the CreateFile function.