Skip to content

Instantly share code, notes, and snippets.

@tom-seddon
Created March 15, 2013 16:19
Show Gist options
  • Save tom-seddon/5171093 to your computer and use it in GitHub Desktop.
Save tom-seddon/5171093 to your computer and use it in GitHub Desktop.
backtrace/backtrace_symbols for Win32.
#ifdef _MSC_VER
struct Frame
{
struct Frame *caller;
void *ret;
};
int backtrace(void **array,int size)
{
struct Frame *frame;
void *stack_start,*stack_end;
int i,n;
__asm
{
mov frame,ebp;
mov eax,dword ptr fs:[8];
mov stack_start,eax;
mov eax,dword ptr fs:[4];
mov stack_end,eax;
}
frame=frame->caller;
// number actually written - perhaps want to skip a certain number?
n=0;
for(i=0;i<size;++i)
{
if((void *)frame<stack_start||(void *)frame>=stack_end)
break;
array[n++]=frame->ret;
frame=frame->caller;
}
return n;
}
#endif//_MSC_VER
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
static int g_symInitialised;
static int g_symInitWorked;
char **backtrace_symbols(void *const *array,int size)
{
int i,symbols_size;
char **symbols;
if(!g_symInitialised)
{
g_symInitWorked=SymInitialize(GetCurrentProcess(),0,TRUE);
g_symInitialised=1;
}
symbols_size=size*sizeof(char *);
symbols=(char **)malloc(symbols_size);
if(!symbols)
return NULL;
for(i=0;i<size;++i)
symbols[i]=NULL;
for(i=0;i<size;++i)
{
// don't much care if the expansion is any longer than this...
char line[1000],**new_symbols;
if(!g_symInitWorked)
{
hex_only:;
_snprintf(line,sizeof line,"0x%p",array[i]);
}
else
{
IMAGEHLP_LINE64 ihl;
DWORD dwDisp;
ihl.SizeOfStruct=sizeof ihl;
if(!SymGetLineFromAddr64(GetCurrentProcess(),(DWORD64)array[i],&dwDisp,&ihl))
goto hex_only;
_snprintf(line,sizeof line,"%s(%lu)",ihl.FileName,ihl.LineNumber);
}
line[sizeof line-1]=0;
size_t line_len=strlen(line);
new_symbols=(char **)realloc(symbols,symbols_size+line_len+1);//+1 for '\x0'
if(!new_symbols)
break;
memcpy((char *)new_symbols+symbols_size,line,line_len+1);
new_symbols[i]=(char *)symbols_size;
symbols=new_symbols;
symbols_size+=line_len+1;
}
for(i=0;i<size;++i)
symbols[i]=(char *)symbols+(int)symbols[i];
return symbols;
}
#endif//_MSC_VER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment