On Tue Mar 5 16:46:12 2024 +0000, Marc-Aurel Zent wrote:
No idea, I assume most of the initialized memory was 0 and some of the cache got invalidated when doing the syscall compared to the memcpy case.
This is the code I used to test that (quickly thrown together), maybe it tests differently on different machines, but I get perfect consistency with it for the results above. ``` #include <windows.h> #include <cstdio>
typedef NTSTATUS(NTAPI* pNtWriteVirtualMemory)( HANDLE ProcessHandle, PVOID BaseAddress, VOID* Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten );
typedef int (*test_function)();
int main() { HMODULE ntdll = GetModuleHandleW(L"ntdll"); pNtWriteVirtualMemory NtWriteVirtualMemory = (pNtWriteVirtualMemory)GetProcAddress(ntdll, "NtWriteVirtualMemory");
void* execMemory = VirtualAlloc(NULL, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
unsigned char code[] = { // movz x0, #1, lsl #0 0x01, 0x00, 0x80, 0xD2, // ret 0xC0, 0x03, 0x5F, 0xD6 }; SIZE_T bytesWritten; ULONG bytesWritten2;
//memcpy(execMemory, code, sizeof(code)); NtWriteVirtualMemory(GetCurrentProcess(), (char*)execMemory , code , sizeof(code), &bytesWritten2); //WriteProcessMemory(GetCurrentProcess(), (char*)execMemory, code, sizeof(code), &bytesWritten);
//FlushInstructionCache(GetCurrentProcess(), execMemory, sizeof(code));
test_function func = (test_function)execMemory; int result = func(); printf("Function returned: %d\n", result);
VirtualFree(execMemory, 0, MEM_RELEASE); return 0; } ```