CreateProcess won't eliminate duplicated variables from the environment block in lpEnvironment parameter

Applies to: Windows Server 2008 R2 StandardWindows Server 2008 StandardWindows Vista Ultimate More

Summary


An application calls CreateProcess and passes an environment block as its lpEnvironment parameter.

If we have two definitions for the same variable but with different values in that block, we may expect that the child process gets the last value we set in the block when it queries for the variable. Instead, Windows returns the first value.

More Information


This behavior is by design in Windows. 

With current design, CreateProcess won't remove any duplicated variables from the buffer that we pass as its lpEnvironment parameter. It will just set that buffer as the environment block for the new process.

CreateProcess Function
http://msdn.microsoft.com/en-us/library/ms682425(v=vs.85).aspx

lpEnvironment [in, optional]

A pointer to the environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.
An environment block consists of a null-terminated block of null-terminated strings.
 “

When the child process has been created and wants to access those variables, it may use GetEnvironmentStrings or GetEnvironmentVariable APIs.

Environment Variables
http://msdn.microsoft.com/en-us/library/ms682653(v=vs.85).aspx 

GetEnvironmentStrings will just return a pointer to the environment block buffer of the process, which would be the same as the buffer that we passed to CreateProcess.

GetEnvironmentVariable will look for the variable that we want within the buffer that we passed to CreateProcess with a very simple algorithm: it will go over the buffer from left to right, and when it finds the variable name we want, it will return its value. GetEnvironmentVariable won’t care if there are other variables with the same name after that one in the buffer.

Summing up, with current design it is the responsibility of the application that calls CreateProcess to eliminate duplicated variables from the environment block buffer.