效果图:
通过读源码win10驱动下实现3环的GetEnvironmentVariable
NTSTATUS NTAPI
RtlQueryEnvironmentVariable_U(PWSTR Environment,
PCUNICODE_STRING Name,
PUNICODE_STRING Value)
{
NTSTATUS Status;
PWSTR wcs;
UNICODE_STRING var;
PWSTR val;
BOOLEAN SysEnvUsed = FALSE;
DbgPrint("RtlQueryEnvironmentVariable_U Environment %p Variable %wZ Value %p\n",
Environment, Name, Value);
if (Environment == NULL)
{
MPPEB Peb = RtlGetCurrentPeb();
if (Peb) {
//RtlAcquirePebLock();
Environment = Peb->ProcessParameters->Environment;
SysEnvUsed = TRUE;
}
}
if (Environment == NULL)
{
//if (SysEnvUsed)
//RtlReleasePebLock();
return(STATUS_VARIABLE_NOT_FOUND);
}
Value->Length = 0;
wcs = Environment;
DbgPrint("Starting search at :%p\n", wcs);
while (*wcs)
{
var.Buffer = wcs++;
wcs = wcschr(wcs, L'=');
if (wcs == NULL)
{
wcs = var.Buffer + wcslen(var.Buffer);
DbgPrint("Search at :%S\n", wcs);
}
if (*wcs)
{
var.Length = var.MaximumLength = (USHORT)(wcs - var.Buffer) * sizeof(WCHAR);
val = ++wcs;
wcs += wcslen(wcs);
DbgPrint("Search at :%S\n", wcs);
if (RtlEqualUnicodeString(&var, Name, TRUE))
{
Value->Length = (USHORT)(wcs - val) * sizeof(WCHAR);
if (Value->Length <= Value->MaximumLength)
{
memcpy(Value->Buffer, val,
min(Value->Length + sizeof(WCHAR), Value->MaximumLength));
DbgPrint("Value %S\n", val);
DbgPrint("Return STATUS_SUCCESS\n");
Status = STATUS_SUCCESS;
}
else
{
DbgPrint("Return STATUS_BUFFER_TOO_SMALL\n");
Status = STATUS_BUFFER_TOO_SMALL;
}
//if (SysEnvUsed)
//RtlReleasePebLock();
return(Status);
}
}
wcs++;
}
/*if (SysEnvUsed)
RtlReleasePebLock();
*/
DbgPrint("Return STATUS_VARIABLE_NOT_FOUND: %wZ\n", Name);
return(STATUS_VARIABLE_NOT_FOUND);
}
//获取环境变量
DWORD My_Get_Environment_Variable(IN LPCWSTR lpName,
IN LPWSTR lpBuffer,
IN DWORD nSize) {
UNICODE_STRING VarName, VarValue;
NTSTATUS Status;
USHORT UniSize;
if (nSize <= (UNICODE_STRING_MAX_CHARS - 1))
{
if (nSize)
{
UniSize = (USHORT)nSize * sizeof(WCHAR) - sizeof(UNICODE_NULL);
}
else
{
UniSize = 0;
}
}
else
{
UniSize = UNICODE_STRING_MAX_BYTES - sizeof(UNICODE_NULL);
}
Status = RtlInitUnicodeStringEx(&VarName, lpName);
if (!NT_SUCCESS(Status))
{
BaseSetLastNTError(Status);
return 0;
}
RtlInitEmptyUnicodeString(&VarValue, lpBuffer, UniSize);
Status = RtlQueryEnvironmentVariable_U(NULL, &VarName, &VarValue);
if (!NT_SUCCESS(Status))
{
DbgPrint("RtlQueryEnvironmentVariable_U----------- %S\n", VarValue);
if (Status == STATUS_BUFFER_TOO_SMALL)
{
return (VarValue.Length / sizeof(WCHAR)) + sizeof(ANSI_NULL);
}
BaseSetLastNTError(Status);
return 0;
}
lpBuffer[VarValue.Length / sizeof(WCHAR)] = UNICODE_NULL;
return (VarValue.Length / sizeof(WCHAR));
}
用法:
wchar_t buffer[256];
wchar_t pwcDevNameBuf = NULL;
DWORD code = My_Get_Environment_Variable(L"TEMP", buffer, 256);
DbgPrint("buffer----------- %S\n", buffer);
©著作权归作者所有:来自51CTO博客作者土匪猿的原创作品,如需转载,请注明出处,否则将追究法律责任
共同学习,写下你的评论
评论加载中...
作者其他优质文章