Last active
December 7, 2017 15:26
-
-
Save uucidl/2360034c8ebeb0dd4fbc8022f78354e1 to your computer and use it in GitHub Desktop.
Trace in a hostile environment (snippet to use for printf debugging)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (Ghetto trace) (Trace in an hostile environment) | |
#include <stdlib.h> | |
#define UU_TRACE_BEGIN | |
#define UU_TRACE_END | |
#if defined (_WIN32) | |
extern "C" { | |
__declspec(dllimport) unsigned long __stdcall GetCurrentProcessId(void); | |
void __stdcall OutputDebugStringA(_In_opt_ char const *outputString); | |
__declspec(dllimport) int _snprintf( char* buffer, size_t buf_size, const char* format, ... ); | |
} | |
# pragma comment(lib, "Kernel32") | |
# if defined(_MSC_VER) | |
# undef UU_TRACE_BEGIN | |
# undef UU_TRACE_END | |
# define UU_TRACE_BEGIN __pragma(warning(push)) __pragma(warning(disable: 4996)) | |
# define UU_TRACE_END __pragma(warning(pop)) | |
# endif | |
#endif | |
#define UU_TRACE(...) { UU_TRACE_BEGIN \ | |
static int fpi; static char fp[4096]; \ | |
if (!fpi) { uint32_t pid=GetCurrentProcessId(); fpi=sprintf(fp, "trace-%x.txt", pid) >= 0; } \ | |
if (fpi) { FILE*y=fopen(fp, "a"); if (y) { fprintf(y, __VA_ARGS__); fputs("\n",y); fclose(y); } } \ | |
UU_TRACE_END } | |
#define UU_DEBUG(...) { UU_TRACE_BEGIN | |
char buffer[4096]; \ | |
_snprintf(buffer, sizeof buffer, __VA_ARGS__); \ | |
OutputDebugStringA(buffer); OutputDebugStringA("\n"); \ | |
UU_TRACE_END } | |
// (Ghetto trace) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (Begin): | |
#include <inttypes.h> | |
#if defined(_WIN32) | |
static uint64_t win32_now_micros() | |
{ | |
LARGE_INTEGER large_integer; | |
QueryPerformanceFrequency(&large_integer); | |
uint64_t ticks_per_second = large_integer.QuadPart; | |
QueryPerformanceCounter(&large_integer); | |
return 1000*1000*large_integer.QuadPart/ticks_per_second; | |
} | |
#endif | |
static uint64_t now_micros() | |
{ | |
return win32_now_micros(); | |
} | |
static FILE* trace_output = stdout; | |
static void trace(int indent, char const* cat, char const* pattern, ...) | |
{ | |
char buffer[4096]; | |
va_list pattern_args; | |
va_start(pattern_args, pattern); | |
int buffer_i = vsnprintf(buffer, sizeof buffer, pattern, pattern_args); | |
va_end(pattern_args); | |
if (buffer_i < 0) return; | |
uint64_t time_ms = now_micros() / 1000; | |
FILE *o = trace_output; | |
fprintf(o, "%*s" "%" PRIu64 ":%s: %s\n", indent, "", time_ms, cat, buffer), fflush(o); | |
} | |
// (End): |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment