Skip to content

Instantly share code, notes, and snippets.

@RadAd
Created May 2, 2018 03:20
Show Gist options
  • Save RadAd/26fc12e06b113c7369b3a5cb91035257 to your computer and use it in GitHub Desktop.
Save RadAd/26fc12e06b113c7369b3a5cb91035257 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
FILE* stddbg = NULL;
FILE* wstddbg = NULL;
static DWORD WINAPI OutputDebugStringAProc(_In_ LPVOID lpParameter)
{
HANDLE hFile = (HANDLE) lpParameter;
CHAR buf[1024];
DWORD read = 0;
while (ReadFile(hFile, buf, (ARRAYSIZE(buf) - 1) * sizeof(buf[0]), &read, NULL))
{
buf[read / sizeof(buf[0])] = '\0';
OutputDebugStringA(buf);
}
CloseHandle(hFile);
return 0;
}
static DWORD WINAPI OutputDebugStringWProc(_In_ LPVOID lpParameter)
{
HANDLE hFile = (HANDLE) lpParameter;
WCHAR buf[1024];
DWORD read = 0;
while (ReadFile(hFile, buf, (ARRAYSIZE(buf) - 1) * sizeof(buf[0]), &read, NULL))
{
buf[read / sizeof(buf[0])] = L'\0';
OutputDebugStringW(buf);
}
CloseHandle(hFile);
return 0;
}
FILE* fhopen(_In_ HANDLE FileHandle, _In_z_ char const* Mode)
{
int Flags = 0;
for (char const* ModeIt = Mode; *ModeIt != '\0'; ++ModeIt)
{
switch (*ModeIt)
{
case 'a': Flags |= _O_WRONLY | _O_APPEND; break;
case 'r': Flags |= _O_RDONLY; break;
case 'w': Flags |= _O_WRONLY; break;
case '+': Flags &= ~(_O_RDONLY | _O_WRONLY); Flags |= _O_RDWR; break;
case 'b': Flags |= _O_BINARY; break;
case 't': Flags |= _O_TEXT; break;
}
}
int d = _open_osfhandle((intptr_t) FileHandle, Flags);
return _fdopen(d, Mode);
}
FILE* opendbg(LPTHREAD_START_ROUTINE lpOutputProc)
{
HANDLE hRead = INVALID_HANDLE_VALUE;
HANDLE hWrite = INVALID_HANDLE_VALUE;
CreatePipe(&hRead, &hWrite, NULL, 0);
HANDLE hThread = CreateThread(NULL, 0, lpOutputProc, hRead, 0, NULL);
FILE* f = fhopen(hWrite, "w");
setvbuf(f, NULL, _IONBF, 0);
return f;
}
int initstddbg(void)
{
if (stddbg == NULL)
stddbg = opendbg(OutputDebugStringAProc);
if (wstddbg == NULL)
wstddbg = opendbg(OutputDebugStringWProc);
return 0;
}
#ifdef STDDBG_TEST
int main()
{
initstddbg();
fprintf(stddbg, "stddbg\n");
fwprintf(wstddbg, L"wstddbg\n");
Sleep(10000);
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment