[Sanitizer] Write a slightly better implementation of GetEnv() function on Windows

llvm-svn: 177051
This commit is contained in:
Alexey Samsonov 2013-03-14 11:10:23 +00:00
parent ae9076457e
commit 83e7622df6
1 changed files with 31 additions and 12 deletions

View File

@ -111,19 +111,38 @@ void *MapFileToMemory(const char *file_name, uptr *buff_size) {
UNIMPLEMENTED();
}
static const kMaxEnvNameLength = 128;
static const kMaxEnvValueLength = 32767;
namespace {
struct EnvVariable {
char name[kMaxEnvNameLength];
char value[kMaxEnvValueLength];
};
} // namespace
static const int kEnvVariables = 5;
static EnvVariable env_vars[kEnvVariables];
static int num_env_vars;
const char *GetEnv(const char *name) {
static char env_buffer[32767] = {};
// Note: this implementation stores the result in a static buffer so we only
// allow it to be called just once.
static bool called_once = false;
if (called_once)
UNIMPLEMENTED();
called_once = true;
DWORD rv = GetEnvironmentVariableA(name, env_buffer, sizeof(env_buffer));
if (rv > 0 && rv < sizeof(env_buffer))
return env_buffer;
// Note: this implementation caches the values of the environment variables
// and limits their quantity.
for (int i = 0; i < num_env_vars; i++) {
if (0 == internal_strcmp(name, env_vars[i].name))
return env_vars[i].value;
}
CHECK_LT(num_env_vars, kEnvVariables);
DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
kMaxEnvValueLength);
if (rv > 0 && rv < kMaxEnvValueLength) {
CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
num_env_vars++;
return env_vars[num_env_vars - 1].value;
}
return 0;
}