NtAllocateVirtualMemoryEx definition - winapi

I am implementing a memory management tool by hooking into memory APIs, when i come to NtAllocateVirtualMemoryEx, i tried to find its definition on google but found nothing, however NtAllocateVirtualMemory is clearly defined at https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntallocatevirtualmemory, is there anyone knowing its details?

ZwAllocateVirtualMemoryEx defined in ntifs.h
#if (NTDDI_VERSION >= NTDDI_WIN10_RS5)
_Must_inspect_result_
_IRQL_requires_max_(PASSIVE_LEVEL)
_When_(return==0, __drv_allocatesMem(Region))
NTSYSAPI
NTSTATUS
NTAPI
ZwAllocateVirtualMemoryEx(
_In_ HANDLE ProcessHandle,
_Inout_ _At_ (*BaseAddress, _Readable_bytes_ (*RegionSize) _Writable_bytes_ (*RegionSize) _Post_readable_byte_size_ (*RegionSize)) PVOID* BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG AllocationType,
_In_ ULONG PageProtection,
_Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
_In_ ULONG ExtendedParameterCount
);
#endif
MEM_EXTENDED_PARAMETER and all api by fact have the same usage as VirtualAlloc2. the VirtualAlloc2 is only thin shell over ZwAllocateVirtualMemoryEx
interesting that VirtualAlloc2 defined in memoryapi.h under condition
#if (NTDDI_VERSION >= NTDDI_WIN10_RS4)
but ZwAllocateVirtualMemoryEx declared with condition
#if (NTDDI_VERSION >= NTDDI_WIN10_RS5)
however howminimum one of this condition is mistake - because VirtualAlloc2 call ZwAllocateVirtualMemoryEx - if VirtualAlloc2 available - ZwAllocateVirtualMemoryEx available too.
also was mistake in msdn:
Library Kernel32.lib
DLL Kernel32.dll
really VirtualAlloc2 not exported by kernel32.dll and not defined in kernel32.lib
need use mincore.lib or mmos.lib which import this api from api-ms-win-core-memory-l1-1-6.dll (resolved to kernelbase.dll now)

Related

Should calls to OututDebugString be wrapped in #ifdef DEBUG conditional blocks?

In winbase.h I see the following code, marking OutputDebugStringA/W as procedures rather than conditional macros. Does this mean it is best to wrap calls to these procedures in debug-only conditional blocks to keep production code tight, especially in tight loops?
WINBASEAPI
VOID
WINAPI
OutputDebugStringA(
__in LPCSTR lpOutputString
);
WINBASEAPI
VOID
WINAPI
OutputDebugStringW(
__in LPCWSTR lpOutputString
);
#ifdef UNICODE
#define OutputDebugString OutputDebugStringW
#else
#define OutputDebugString OutputDebugStringA
#endif // !UNICODE
Usually we do something like this:
#if defined (DEBUG) | defined (_DEBUG)
#define DebugOutput(x) OutputDebugString(x)
#else
#define DebugOutput(x)
#endif
DebugOutput will be expanded to nothing in release mode, keeping release binary clean and without #idfef/#endif everywhere in the code.
Note, that it is a good idea to also check if compiler is MSVC (_MSC_VER), so your code could be more portable

Can we use C++/Cx inside a static lib (Metro Style)

I am trying to port a native sdk to windows RT and to help me I would like to implement missing functions to emulate registry access, so I have created a Static Library (File->New->Project...->Static Library (Metro Style apps) and I have declared the function like that :
// WinRT stuff
#include <windows.storage.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Storage;
using namespace ABI::Windows::Foundation;
LSTATUS
APIENTRY
RegOpenKeyExW(
_In_ HKEY hKey,
_In_opt_ LPCWSTR lpSubKey,
_In_opt_ DWORD ulOptions,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
LSTATUS ret = ERROR_SUCCESS;
if (hKey == NULL)
return ERROR_INVALID_HANDLE;
if (phkResult == NULL)
return ERROR_INVALID_PARAMETER;
ABI::Windows::Storage::ApplicationDataContainer^ localSettings =
ApplicationData::Current->LocalSettings;
...
}
However when I try to compile I get this error :
1>c:\users\joe\documents\visual studio 2012\projects\lib1\lib1\oal.cpp(275):
error C3699: '^' : cannot use this indirection on type
'ABI::Windows::Storage::ApplicationDataContainer'
I have checked and Consume Windows Runtime Extension (/ZW) is enabled (it's by default) so I am wondering if it's possible to use C++/CX inside a static lib?
If you're using the ABI prefix on your types, then you're referring to the low level C++ type. THe low level types are intended to be used with WRL and cannot use the C++/CX extensions like the ^ operator.
Use ComPtr localSettings instead.
Ok someone told me to add In Librarian->General->Additional Dependecies : %(AdditionalDependencies) and I have removed the ABI:: namespace. Now it works ;-)

ZwQuerySystemInformation / NtQuerySystemInformation - System Information Class 5

For 32-bit Windows, following declaration of _SYSTEM_PROCESSES structure ( System Information Class 5 ) with ZwQuerySystemInformation works fine for my purpose to construct process tree.
typedef struct _SYSTEM_PROCESSES
{ // System Information Class 5
ULONG NextEntryDelta;
ULONG ThreadCount;
ULONG Reserved1[6];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ProcessName;
ULONG BasePriority;
ULONG ProcessId;
ULONG InheritedFromProcessId;
ULONG HandleCount;
ULONG Reserved2[2];
} SYSTEM_PROCESSES, * PSYSTEM_PROCESSES;
On the other hand, it doesn't function well in 64-bit Windows. If I declare the ProcessId as ULONG64, then the data for ProcessId comes right. Is the datatype defined for above structure is right for Windows-64?
For some weird reason, process and thread id's are 64bit in the kernel and 32bit in the documented windows api on x64
If you look at SYSTEM_PROCESS_INFORMATION # ntinternals you see that they have declared the PID's as HANDLE (pointer sized)

How can I get HINSTANCE from a DLL?

I have created a DLL in VC++ as Win32 project
DLLMAIN function is
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
Now I need HINSTANCE of the DLL , that need to be passed to Win32 functions.
Are HMODULE and HINSTANCE same?
How can I get HINSTANCE?
An excerpt from the book Windows Via C/C++ [1]
Note As it turns out, HMODULEs and HINSTANCEs are exactly the same thing. If the documentation for a function indicates that an HMODULE is required, you can pass an HINSTANCE and vice versa. There are two data types because in 16-bit Windows HMODULEs and HINSTANCEs identified different things
[1] Richter, Jeffery and Nasarre, Christophe, Windows Via C/C++, 5th ed, Redmond: Microsoft Press 2008, pp. 74
Microsoft linker specific
#include "windows.h"
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#pragma warning(disable: 4047)
HINSTANCE hInstance = (HINSTANCE)&__ImageBase;
#pragma warning(default: 4047)
I think that these are the same. If you want HINSTANCE of the running process (exe), you should use
GetModuleHandle(NULL);
Calling GetModuleHandle(NULL) from a dll will return the Hinstanc of the EXE that started the DLL; to get the Hinstance for the curently running dll try this tip:
http://www.dotnet247.com/247reference/msgs/13/65259.aspx
DllMain function as it's described in MSDN:
BOOL WINAPI DllMain(
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
);
http://msdn.microsoft.com/en-us/library/ms682583%28v=vs.85%29.aspx
Each DLL has at least a header file, say MyDll.h and a corresponding implementation file MyDll.cpp. Open the header file and add
extern HMODULE hDllModule;//or whatever name you like
Now open the MyDll.cpp file. There is a function DLLMAIN. Add before it HMODULE hDllModule; and insert hDllModuleDll = hModule; before return true;. Your code will look like this:
HMODULE hDllModuleDll;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hDllModuleDll = hModule;
return TRUE;
}
In functions like ::GetModuleFileNameW(hModule, PathFile, MAX_PATH); that require a HMODULE of the DLL you can pass the global variable hDllModule.
To complement the other answers, for the sake of completness.
The actual signature of DllMain has an HINSTANCE parameter, instead of a HMODULE parameter. The Visual Studio DLL template generates the signature with HMODULE since at least Visual Studio 2008 however, but I believe this to be a minor bug more than anything. VC6 generated the code with HANDLE (even though both HINSTANCE and HMODULE exist). The reason that doesn't cause problems is because HINSTANCE and HMODULE are now exactly the same thing. Unfortunately I was unable to find an ancient enough version of the MSDN documetnation that could have confirmed this.
So the answer is: You get your HINSTANCE as an argument to your DllMain.
Personally I sort of like the distinction between HMODULE and HINSTANCE because it appeals to me as being good code hygiene. It's a bit like using const. But then, a new question arises: Given your HINSTANCE, how do you get your HMODULE in the "hygienic" way?
The windowsx.h header defines GetInstanceModule, which is now a macro that just casts the HINSTANCE to HMODULE. It only exists for code compatibility, along with a bunch of very similar macros.

Is anyone familiar with the undocumented ObReferenceObjectByName windows kernel function?

I read a very fascinating article that was about programming drivers using the wdk, and one of the functions it used is called ObReferenceObjectByName. This function has given me lots of headaches. The first bad thing is that it's not documented by microsoft. The second thing, is that the language used in the article was C++, and I want to keep my code in plain ol' C. I know that most of the time this shouldn't be a problem, but I haven't - for the life of me - been able to figure out how to include this function.
The code in the article goes something like:
extern "C"{
#include <ntifs.h>
NTSYSAPI NTSTATUS NTAPI ObReferenceObjectByName(PUNICODE_STRING ObjectName,
ULONG Attributes,
PACCESS_STATE AccessState,
ACCESS_MASK DesiredAccess,
POBJECT_TYPE ObjectType,
KPROCESSOR_MODE AccessMode,
PVOID ParseContext OPTIONAL,
PVOID* Object);
}
I've been trying to replicate this for hours. I tried declaring it without the 'extern' keyword, I tried changing the calling convention, I tried changing the includes... I always end up with the error "unresolved external symbol...".
I'm absolutely stumped, so if anyone could offer some advice, I'd be grateful. Thanks.
You wouldn't be reading http://www.codeproject.com/KB/recipes/keystroke-hook.aspx and trying to create your own Keyboard Logger would you?
Anyways, instead of using this, call ZwCreateFile then ObReferenceObjectByHandle instead.
Here is a test C code compiled and built with no problems:
#include <ntddk.h>
NTSYSAPI NTSTATUS NTAPI ObReferenceObjectByName(
PUNICODE_STRING ObjectName,
ULONG Attributes,
PACCESS_STATE AccessState,
ACCESS_MASK DesiredAccess,
POBJECT_TYPE ObjectType,
KPROCESSOR_MODE AccessMode,
PVOID ParseContext OPTIONAL,
PVOID* Object
);
NTSTATUS DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath
)
{
ObReferenceObjectByName(0, 0, 0, 0, 0, 0, 0, 0);
return STATUS_SUCCESS;
}
I don't know this API, but I can give you a trick that might help you diagnose the problem.
at a command prompt that has MSVC tools in the path
link /dump /exports ???.dll
where ???.dll is the dll were you expect this function to be. This will give you a complete list of exported symbol names and will tell you two things. 1) is the symbol there? and 2) is it being decorated the same as your attempted prototype.
For 32 bit kernel, you should expect this to be called _ObReferenceObjectByName#64,

Resources