HyperDbg Debugger
Loading...
Searching...
No Matches
platform-lib-calls.c File Reference

User mode Cross platform APIs for platofrm dependend library calls. More...

#include "pch.h"

Functions

INT PlatformVsnprintf (char *Buffer, SIZE_T BufferSize, const char *Format, va_list ArgList)
 Platform independent wrapper for vsprintf_s / vsnprintf.
char * PlatformStrDup (const char *Str)
 Platform independent wrapper for _strdup / strdup.
VOID PlatformZeroMemory (PVOID Buffer, SIZE_T Size)
 Platform independent wrapper for RtlZeroMemory / memset.
BOOLEAN PlatformQueryPerformanceFrequency (LARGE_INTEGER *Frequency)
 Platform independent wrapper for QueryPerformanceFrequency.
BOOLEAN PlatformQueryPerformanceCounter (LARGE_INTEGER *Count)
 Platform independent wrapper for QueryPerformanceCounter.
INT PlatformSprintf (char *Buffer, SIZE_T BufferSize, const char *Format,...)
 Platform independent wrapper for sprintf_s / snprintf.
UINT32 PlatformGetCurrentThreadId (VOID)
 Platform independent wrapper for GetCurrentThreadId / gettid.
UINT32 PlatformGetCurrentProcessorNumber (VOID)
 Platform independent wrapper for GetCurrentProcessorNumber / sched_getcpu.
UINT32 PlatformGetCurrentProcessId (VOID)
 Platform independent wrapper for GetCurrentProcessId / getpid.
CHARPlatformGetCurrentProcessName (VOID)
 Platform independent wrapper to get the current process name.
HANDLE PlatformCreateEvent (BOOLEAN ManualReset, BOOLEAN InitialState)
 Platform independent wrapper for CreateEvent.
BOOLEAN PlatformSetEvent (HANDLE EventHandle)
 Platform independent wrapper for SetEvent.
BOOLEAN PlatformResetEvent (HANDLE EventHandle)
 Platform independent wrapper for ResetEvent.
DWORD PlatformWaitForSingleObject (HANDLE Handle, DWORD TimeoutMilliseconds)
 Platform independent wrapper for WaitForSingleObject.
BOOLEAN PlatformCloseHandle (HANDLE Handle)
 Platform independent wrapper for CloseHandle.
DWORD PlatformGetLastError (VOID)
 Platform independent wrapper for GetLastError.
BOOLEAN PlatformWriteConsole (const VOID *Buffer, DWORD NumberOfBytes)
 Platform independent wrapper to write raw bytes to the console.
HANDLE PlatformOpenFileForWriting (const WCHAR *Path)
 Platform independent wrapper to create/open a file for writing.
BOOLEAN PlatformWriteFile (HANDLE FileHandle, const VOID *Buffer, DWORD NumberOfBytes)
 Platform independent wrapper to write a buffer to an open file.
BOOLEAN PlatformCloseFile (HANDLE FileHandle)
 Platform independent wrapper to close a file opened by PlatformOpenFileForWriting.
VOID * PlatformMapFileReadOnly (const WCHAR *Path, PSIZE_T OutFileSize, PHANDLE OutFileHandle)
 Platform independent wrapper to map an entire file read-only into memory.
BOOLEAN PlatformReadFileAtOffset (HANDLE FileHandle, UINT64 Offset, VOID *Buffer, DWORD NumberOfBytes, LPDWORD BytesRead)
 Platform independent wrapper for a positioned (seek + read) file read.
VOID PlatformUnmapFile (VOID *BaseAddress, SIZE_T FileSize, HANDLE FileHandle)
 Platform independent wrapper to release a mapping from PlatformMapFileReadOnly.

Detailed Description

User mode Cross platform APIs for platofrm dependend library calls.

Author
Max Raulea (max.r.nosp@m.aule.nosp@m.a@gma.nosp@m.il.c.nosp@m.om)
Version
0.19
Date
2026-06-01

Function Documentation

◆ PlatformCloseFile()

BOOLEAN PlatformCloseFile ( HANDLE FileHandle)

Platform independent wrapper to close a file opened by PlatformOpenFileForWriting.

Parameters
FileHandlehandle to close
Returns
BOOLEAN TRUE on success
441{
442#if defined(_WIN32)
443 return (BOOLEAN)CloseHandle(FileHandle);
444#elif defined(__linux__)
445 return (BOOLEAN)(fclose((FILE *)FileHandle) == 0);
446#else
447# error "Unsupported platform"
448#endif
449}
PHANDLE FileHandle
Definition SyscallFootprints.h:133
UCHAR BOOLEAN
Definition BasicTypes.h:35

◆ PlatformCloseHandle()

BOOLEAN PlatformCloseHandle ( HANDLE Handle)

Platform independent wrapper for CloseHandle.

335{
336#if defined(_WIN32)
337 return (BOOLEAN)CloseHandle(Handle);
338#elif defined(__linux__)
339 (void)Handle; // TODO: free the underlying cond/eventfd or close the fd
340 return TRUE;
341#else
342# error "Unsupported platform"
343#endif
344}
#define TRUE
Definition BasicTypes.h:114

◆ PlatformCreateEvent()

HANDLE PlatformCreateEvent ( BOOLEAN ManualReset,
BOOLEAN InitialState )

Platform independent wrapper for CreateEvent.

Parameters
ManualResetTRUE for a manual-reset event, FALSE for auto-reset
InitialStateTRUE if the event starts signaled
Returns
HANDLE to the event, or NULL on failure
258{
259#if defined(_WIN32)
260 return CreateEvent(NULL, ManualReset, InitialState, NULL);
261#elif defined(__linux__)
262 //
263 // TODO: back this with a pthread mutex+cond (or eventfd) when the Linux
264 // kernel-debugger transport is implemented. For now return a dummy
265 // non-NULL handle so existing NULL-checks treat creation as success.
266 //
267 (void)ManualReset;
268 (void)InitialState;
269 return (HANDLE)(uintptr_t)1;
270#else
271# error "Unsupported platform"
272#endif
273}

◆ PlatformGetCurrentProcessId()

UINT32 PlatformGetCurrentProcessId ( VOID )

Platform independent wrapper for GetCurrentProcessId / getpid.

Returns
UINT32 PID of the calling process
186{
187#if defined(_WIN32)
188 return (UINT32)GetCurrentProcessId();
189#elif defined(__linux__)
190 return (UINT32)getpid();
191#else
192# error "Unsupported platform"
193#endif
194}
unsigned int UINT32
Definition BasicTypes.h:54

◆ PlatformGetCurrentProcessName()

CHAR * PlatformGetCurrentProcessName ( VOID )

Platform independent wrapper to get the current process name.

Returns
CHAR* pointer to a static buffer holding the process name, or NULL on failure
203{
204 static CHAR ProcessNameBuf[MAX_PATH] = {0};
205
206#if defined(_WIN32)
207 //
208 // Use base kernel32 only (no psapi/shlwapi) so this compiles in every
209 // project that builds platform-lib-calls.c (e.g. script-engine, which has
210 // a minimal include set). GetModuleFileNameA(NULL, ...) returns the full
211 // path of the current process image.
212 //
213 if (GetModuleFileNameA(NULL, ProcessNameBuf, MAX_PATH) == 0)
214 {
215 return NULL;
216 }
217
218 //
219 // Return the basename (strip the directory part)
220 //
221 char * LastSeparator = strrchr(ProcessNameBuf, '\\');
222 if (LastSeparator)
223 {
224 return LastSeparator + 1;
225 }
226
227 return ProcessNameBuf;
228
229#elif defined(__linux__)
230 FILE * f = fopen("/proc/self/comm", "r");
231 if (f)
232 {
233 if (fgets(ProcessNameBuf, sizeof(ProcessNameBuf), f))
234 {
235 size_t Len = strlen(ProcessNameBuf);
236 if (Len > 0 && ProcessNameBuf[Len - 1] == '\n')
237 ProcessNameBuf[Len - 1] = '\0';
238 }
239 fclose(f);
240 return ProcessNameBuf;
241 }
242 return NULL;
243
244#else
245# error "Unsupported platform"
246#endif
247}
char CHAR
Definition BasicTypes.h:33
NULL()
Definition test-case-generator.py:530
f
Definition test-case-generator.py:581

◆ PlatformGetCurrentProcessorNumber()

UINT32 PlatformGetCurrentProcessorNumber ( VOID )

Platform independent wrapper for GetCurrentProcessorNumber / sched_getcpu.

Returns
UINT32 logical processor index the calling thread is running on
169{
170#if defined(_WIN32)
171 return (UINT32)GetCurrentProcessorNumber();
172#elif defined(__linux__)
173 return (UINT32)sched_getcpu();
174#else
175# error "Unsupported platform"
176#endif
177}

◆ PlatformGetCurrentThreadId()

UINT32 PlatformGetCurrentThreadId ( VOID )

Platform independent wrapper for GetCurrentThreadId / gettid.

Returns
UINT32 thread ID of the calling thread
152{
153#if defined(_WIN32)
154 return (UINT32)GetCurrentThreadId();
155#elif defined(__linux__)
156 return (UINT32)syscall(SYS_gettid);
157#else
158# error "Unsupported platform"
159#endif
160}

◆ PlatformGetLastError()

DWORD PlatformGetLastError ( VOID )

Platform independent wrapper for GetLastError.

351{
352#if defined(_WIN32)
353 return GetLastError();
354#elif defined(__linux__)
355 return (DWORD)errno;
356#else
357# error "Unsupported platform"
358#endif
359}
unsigned long DWORD
Definition BasicTypes.h:38

◆ PlatformMapFileReadOnly()

VOID * PlatformMapFileReadOnly ( const WCHAR * Path,
PSIZE_T OutFileSize,
PHANDLE OutFileHandle )

Platform independent wrapper to map an entire file read-only into memory.

The returned pointer stays valid until released with PlatformUnmapFile; the underlying file/descriptor is closed before returning (the mapping outlives it on both platforms).

Parameters
Pathwide path of the file to map
OutFileSizeoutput — size of the file in bytes (0 on failure)
Returns
VOID* base address of the mapped file, or NULL on failure
464{
465#if defined(_WIN32)
466 HANDLE FileHandle;
467 HANDLE MapObjectHandle;
468 VOID * BaseAddr;
469 LARGE_INTEGER FileSize;
470
471 *OutFileSize = 0;
472 *OutFileHandle = INVALID_HANDLE_VALUE;
473
474 FileHandle = CreateFileW(Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
475 if (FileHandle == INVALID_HANDLE_VALUE)
476 {
477 return NULL;
478 }
479
480 if (!GetFileSizeEx(FileHandle, &FileSize))
481 {
482 CloseHandle(FileHandle);
483 return NULL;
484 }
485
486 MapObjectHandle = CreateFileMapping(FileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
487 if (MapObjectHandle == NULL)
488 {
489 CloseHandle(FileHandle);
490 return NULL;
491 }
492
493 BaseAddr = MapViewOfFile(MapObjectHandle, FILE_MAP_READ, 0, 0, 0);
494
495 //
496 // The view stays valid after the mapping object handle is closed. The file
497 // handle is kept open and handed back so the caller can still issue raw
498 // reads (PlatformReadFileAtOffset); it is closed by PlatformUnmapFile.
499 //
500 CloseHandle(MapObjectHandle);
501
502 if (BaseAddr == NULL)
503 {
504 CloseHandle(FileHandle);
505 return NULL;
506 }
507
508 *OutFileSize = (SIZE_T)FileSize.QuadPart;
509 *OutFileHandle = FileHandle;
510 return BaseAddr;
511#elif defined(__linux__)
512 //
513 // TODO (linux): implement the real mapping. Expected contract:
514 // 1. Narrow the 4-byte wchar_t 'Path' to a UTF-8 char* (the project still
515 // lacks a wchar_t->UTF-8 helper; the same one is needed by
516 // PlatformOpenFileForWriting for the dump.cpp write path).
517 // 2. fd = open(narrowed_path, O_RDONLY); // fail -> NULL
518 // 3. fstat(fd, &st) to get the file size.
519 // 4. base = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
520 // 5. *OutFileHandle = (HANDLE)(intptr_t)fd; // keep fd open for raw reads
521 // 6. *OutFileSize = st.st_size; return base; (return NULL on any failure)
522 // PlatformUnmapFile must then munmap(base, size) and close the fd — which is
523 // why both the size and the handle are passed back in on unmap. The raw-read
524 // path (PlatformReadFileAtOffset) would pread() from that same fd.
525 //
526 // Until implemented, fail the map so PE-parser callers print "could not open
527 // the file" and bail out cleanly instead of dereferencing a bogus pointer.
528 //
529 (void)Path;
530 *OutFileSize = 0;
531 *OutFileHandle = INVALID_HANDLE_VALUE;
532 return NULL;
533#else
534# error "Unsupported platform"
535#endif
536}

◆ PlatformOpenFileForWriting()

HANDLE PlatformOpenFileForWriting ( const WCHAR * Path)

Platform independent wrapper to create/open a file for writing.

Parameters
Pathwide path of the file to create (truncated if it exists)
Returns
HANDLE to the opened file, or INVALID_HANDLE_VALUE on failure
393{
394#if defined(_WIN32)
395 return CreateFileW(Path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
396#elif defined(__linux__)
397 //
398 // TODO: handle this later. The path arrives as a std::wstring (4-byte
399 // wchar_t on Linux) and must be narrowed to a UTF-8 char* before it
400 // can be handed to fopen. Until that conversion is wired up, fail the
401 // open so callers (e.g. dump.cpp) bail out cleanly instead of writing
402 // to a bogus handle.
403 //
404 (void)Path;
405 return INVALID_HANDLE_VALUE;
406#else
407# error "Unsupported platform"
408#endif
409}

◆ PlatformQueryPerformanceCounter()

BOOLEAN PlatformQueryPerformanceCounter ( LARGE_INTEGER * Count)

Platform independent wrapper for QueryPerformanceCounter.

Parameters
Countoutput — current tick count
Returns
BOOLEAN TRUE on success
107{
108#if defined(_WIN32)
109 return (BOOLEAN)QueryPerformanceCounter((LARGE_INTEGER *)Count);
110#elif defined(__linux__)
111 struct timespec Ts;
112 clock_gettime(CLOCK_MONOTONIC, &Ts);
113 Count->QuadPart = (INT64)Ts.tv_sec * 1000000000LL + Ts.tv_nsec;
114 return TRUE;
115#else
116# error "Unsupported platform"
117#endif
118}

◆ PlatformQueryPerformanceFrequency()

BOOLEAN PlatformQueryPerformanceFrequency ( LARGE_INTEGER * Frequency)

Platform independent wrapper for QueryPerformanceFrequency.

Parameters
Frequencyoutput — ticks per second
Returns
BOOLEAN TRUE on success
88{
89#if defined(_WIN32)
90 return (BOOLEAN)QueryPerformanceFrequency((LARGE_INTEGER *)Frequency);
91#elif defined(__linux__)
92 Frequency->QuadPart = 1000000000LL; // clock_gettime gives nanosecond resolution
93 return TRUE;
94#else
95# error "Unsupported platform"
96#endif
97}

◆ PlatformReadFileAtOffset()

BOOLEAN PlatformReadFileAtOffset ( HANDLE FileHandle,
UINT64 Offset,
VOID * Buffer,
DWORD NumberOfBytes,
LPDWORD BytesRead )

Platform independent wrapper for a positioned (seek + read) file read.

Parameters
FileHandlehandle handed back by PlatformMapFileReadOnly
Offsetbyte offset to read from (absolute, from start of file)
Bufferdestination buffer
NumberOfBytesnumber of bytes to read
BytesReadoutput — number of bytes actually read
Returns
BOOLEAN TRUE on success
550{
551#if defined(_WIN32)
552 LARGE_INTEGER Distance;
553 Distance.QuadPart = (LONGLONG)Offset;
554
555 if (!SetFilePointerEx(FileHandle, Distance, NULL, FILE_BEGIN))
556 {
557 return FALSE;
558 }
559
560 return (BOOLEAN)ReadFile(FileHandle, Buffer, NumberOfBytes, BytesRead, NULL);
561#elif defined(__linux__)
562 //
563 // TODO (linux): pread((int)(intptr_t)FileHandle, Buffer, NumberOfBytes, Offset)
564 // once PlatformMapFileReadOnly wraps a real fd. Unreached today
565 // because the map returns NULL on Linux, so callers bail first.
566 //
567 (void)FileHandle;
568 (void)Offset;
569 (void)Buffer;
570 (void)NumberOfBytes;
571 if (BytesRead != NULL)
572 {
573 *BytesRead = 0;
574 }
575 return FALSE;
576#else
577# error "Unsupported platform"
578#endif
579}
POOL_TYPE SIZE_T NumberOfBytes
Definition Hooks.h:88
#define FALSE
Definition BasicTypes.h:113

◆ PlatformResetEvent()

BOOLEAN PlatformResetEvent ( HANDLE EventHandle)

Platform independent wrapper for ResetEvent.

296{
297#if defined(_WIN32)
298 return (BOOLEAN)ResetEvent(EventHandle);
299#elif defined(__linux__)
300 (void)EventHandle; // TODO: clear the underlying cond/eventfd
301 return TRUE;
302#else
303# error "Unsupported platform"
304#endif
305}

◆ PlatformSetEvent()

BOOLEAN PlatformSetEvent ( HANDLE EventHandle)

Platform independent wrapper for SetEvent.

280{
281#if defined(_WIN32)
282 return (BOOLEAN)SetEvent(EventHandle);
283#elif defined(__linux__)
284 (void)EventHandle; // TODO: signal the underlying cond/eventfd
285 return TRUE;
286#else
287# error "Unsupported platform"
288#endif
289}

◆ PlatformSprintf()

INT PlatformSprintf ( char * Buffer,
SIZE_T BufferSize,
const char * Format,
... )

Platform independent wrapper for sprintf_s / snprintf.

Parameters
Bufferoutput buffer
BufferSizesize of the output buffer
Formatformat string
Returns
INT number of characters written, or -1 on error
130{
131 va_list Args;
132 va_start(Args, Format);
133 INT Result;
134#if defined(_WIN32)
135 Result = vsprintf_s(Buffer, BufferSize, Format, Args);
136#elif defined(__linux__)
137 Result = vsnprintf(Buffer, BufferSize, Format, Args);
138#else
139# error "Unsupported platform"
140#endif
141 va_end(Args);
142 return Result;
143}
int INT
Definition BasicTypes.h:43

◆ PlatformStrDup()

char * PlatformStrDup ( const char * Str)

Platform independent wrapper for _strdup / strdup.

Parameters
Strstring to duplicate
Returns
char * pointer to the duplicated string, or NULL on failure
52{
53#if defined(_WIN32)
54 return _strdup(Str);
55#elif defined(__linux__)
56 return strdup(Str);
57#else
58# error "Unsupported platform"
59#endif
60}

◆ PlatformUnmapFile()

VOID PlatformUnmapFile ( VOID * BaseAddress,
SIZE_T FileSize,
HANDLE FileHandle )

Platform independent wrapper to release a mapping from PlatformMapFileReadOnly.

Parameters
BaseAddressbase address returned by PlatformMapFileReadOnly
FileSizesize that was reported by PlatformMapFileReadOnly (needed by munmap)
FileHandlefile handle handed back by PlatformMapFileReadOnly
590{
591#if defined(_WIN32)
592 (void)FileSize; // not needed by UnmapViewOfFile
593 if (BaseAddress != NULL)
594 {
595 UnmapViewOfFile(BaseAddress);
596 }
597 if (FileHandle != INVALID_HANDLE_VALUE)
598 {
599 CloseHandle(FileHandle);
600 }
601#elif defined(__linux__)
602 //
603 // TODO (linux): munmap(BaseAddress, FileSize) and close the fd behind
604 // FileHandle once PlatformMapFileReadOnly is implemented.
605 // No-op for now since the map always returns NULL.
606 //
607 (void)BaseAddress;
608 (void)FileSize;
609 (void)FileHandle;
610#else
611# error "Unsupported platform"
612#endif
613}

◆ PlatformVsnprintf()

INT PlatformVsnprintf ( char * Buffer,
SIZE_T BufferSize,
const char * Format,
va_list ArgList )

Platform independent wrapper for vsprintf_s / vsnprintf.

Parameters
Bufferoutput buffer
BufferSizesize of the output buffer
Formatformat string
ArgListvariadic argument list
Returns
INT number of characters written, or -1 on error
34{
35#if defined(_WIN32)
36 return vsprintf_s(Buffer, BufferSize, Format, ArgList);
37#elif defined(__linux__)
38 return vsnprintf(Buffer, BufferSize, Format, ArgList);
39#else
40# error "Unsupported platform"
41#endif
42}

◆ PlatformWaitForSingleObject()

DWORD PlatformWaitForSingleObject ( HANDLE Handle,
DWORD TimeoutMilliseconds )

Platform independent wrapper for WaitForSingleObject.

Returns
0 (WAIT_OBJECT_0) on success
314{
315#if defined(_WIN32)
316 return WaitForSingleObject(Handle, TimeoutMilliseconds);
317#elif defined(__linux__)
318 //
319 // TODO: wait on the underlying cond/eventfd. For now return immediately as
320 // success — no real transport exists yet to wait on.
321 //
322 (void)Handle;
323 (void)TimeoutMilliseconds;
324 return 0;
325#else
326# error "Unsupported platform"
327#endif
328}

◆ PlatformWriteConsole()

BOOLEAN PlatformWriteConsole ( const VOID * Buffer,
DWORD NumberOfBytes )

Platform independent wrapper to write raw bytes to the console.

Used to emit pre-encoded UTF-8 byte sequences (e.g. box-drawing characters) directly to standard output. On Windows this goes through WriteConsoleA so the console code page is bypassed; on Linux the terminal is UTF-8 native so the bytes are written as-is.

Parameters
Bufferpointer to the bytes to write
NumberOfBytesnumber of bytes to write
Returns
BOOLEAN TRUE on success
375{
376#if defined(_WIN32)
377 return (BOOLEAN)WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), Buffer, NumberOfBytes, NULL, NULL);
378#elif defined(__linux__)
379 return (BOOLEAN)(fwrite(Buffer, 1, NumberOfBytes, stdout) == NumberOfBytes);
380#else
381# error "Unsupported platform"
382#endif
383}

◆ PlatformWriteFile()

BOOLEAN PlatformWriteFile ( HANDLE FileHandle,
const VOID * Buffer,
DWORD NumberOfBytes )

Platform independent wrapper to write a buffer to an open file.

Parameters
FileHandlehandle returned by PlatformOpenFileForWriting
Bufferpointer to the bytes to write
NumberOfBytesnumber of bytes to write
Returns
BOOLEAN TRUE on success
421{
422#if defined(_WIN32)
423 DWORD BytesWritten;
424 return (BOOLEAN)WriteFile(FileHandle, Buffer, NumberOfBytes, &BytesWritten, NULL);
425#elif defined(__linux__)
426 return (BOOLEAN)(fwrite(Buffer, 1, NumberOfBytes, (FILE *)FileHandle) == NumberOfBytes);
427#else
428# error "Unsupported platform"
429#endif
430}

◆ PlatformZeroMemory()

VOID PlatformZeroMemory ( PVOID Buffer,
SIZE_T Size )

Platform independent wrapper for RtlZeroMemory / memset.

Zeros a memory block.

Parameters
Bufferpointer to the memory region to zero
Sizenumber of bytes to zero
DestinationMemory address.
SizeNumber of bytes.
70{
71#if defined(_WIN32)
72 RtlZeroMemory(Buffer, Size);
73#elif defined(__linux__)
74 memset(Buffer, 0, Size);
75#else
76# error "Unsupported platform"
77#endif
78}