//////////////////////////////////////////////////
//Title    : wxc_debug.c
//Auhtor   : Liu Wei
//Desc     : wxc debug api implemetation   
//Created  : 2007-05-01
//Revision :
//
//Revision :
//
//////////////////////////////////////////////////


#include "stdio.h"
#include "assert.h"
#include "string.h"
#include "stdlib.h"
#include <execinfo.h>
#include <signal.h>

void dump(int signo)
{
     char buf[1024];
     char cmd[1024];
     FILE *fh;

     snprintf(buf, sizeof(buf), "/proc/%d/cmdline", getpid());
     if(!(fh = fopen(buf, "r")))
                exit(0);
     if(!fgets(buf, sizeof(buf), fh))
                exit(0);
     fclose(fh);
     if(buf[strlen(buf) - 1] == '\n')
                buf[strlen(buf) - 1] = '\0';
     snprintf(cmd, sizeof(cmd), "gdb %s %d", buf, getpid());
     system(cmd);

     exit(0);
}

void WxcBackTrace()
{
	int i;
	void * array[25];
    int  nSize = backtrace(array, 25);
    char ** symbols = backtrace_symbols(array, nSize);
    
    for (i = 0; i < nSize; i++)
    {
         printf("%s \n" , symbols[i]);
    }
    free(symbols);
}

typedef unsigned char  BYTE;		
		
#define WxcAssert(uVal,pStr)        \
        if(!(uVal))                 \
        {                           \
        	WxcBackTrace();         \
        }                           \
		assert( uVal && pStr );     \

void sprintf_bcd( const BYTE *pBcdBuff , int nBcdLen , char *pStrBuff , int nStrBuffSize )
{
	int i ,len = 0;
    int nChar;
    
    nChar = ( nBcdLen % 8 )* 3 + ( nBcdLen / 8 ) * 25 + 1 ;

    WxcAssert((nChar < nStrBuffSize),"sprint bcd string buffer flow");
    
    for( i = 1 ; i <= nBcdLen; i ++ )
    {
    	sprintf ( pStrBuff + len , "%02X ", pBcdBuff[i-1] );
    	len += 3;	
    	if( 0 == (i % 16) )
    	{
    		strcat ( pStrBuff , "\n");
    		len++;
    	}
    	else if( 0 == (i % 8) )
    	{
    		strcat ( pStrBuff , " ");
    		len++;
    	}
    }
	if( 0 != (len % 50) )
    {
		strcat ( pStrBuff , "\n");
	}		
}

void testdump(char *p)
{
	*p =0;
}

void main()
{
	BYTE aBCDBuff[128];
    char temp[256] ; 
	int i , j;
	char *p ;
	
	p = NULL;
	
	signal(SIGSEGV, &dump);
	
	for( i = 0 ; i < 128 ; i ++ )
	{
		if( i < 80 )
		   aBCDBuff[i] = (BYTE)(1 + i) ; 
		else
		   aBCDBuff[i] = (BYTE)(256 - i*2) ; 
	}
	
	for( j = 30 ; j < 100 ; j+=7 )
	{
	   sprintf_bcd(aBCDBuff , j , temp , 256 );
	   printf("BCD:\r\n%s\r\n", temp);
	}
	
	testdump(p);
	getchar();
}
