Kris Wang

Debug Tips List

Leave a Comment
工作環境不夠強大時,還是需要蒐集一些debug小技巧. 索性開篇文章來持續紀錄吧

[Print call stack at runtime]
For Linux:
http://man7.org/linux/man-pages/man3/backtrace.3.html
#define SIZE 100

int j, nptrs;
void *buffer[100];
char **strings;

nptrs = backtrace(buffer, SIZE);
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
   perror("backtrace_symbols");
   exit(EXIT_FAILURE);
}

for (j = 0; j < nptrs; j++)
   printf("%s\n", strings[j]);

free(strings);
For WinCE:
http://msdn.microsoft.com/en-us/library/ms885641.aspx
static const int kMaxFrames = 15;
CallSnapshot lpFrames[kMaxFrames];

DWORD dwCnt = GetThreadCallStack(GetCurrentThread(), kMaxFrames, lpFrames, 0, 0);

for(int i = 0; i < dwCnt; i++) {
   NKDbgPrintfW(TEXT("[%02d] Return Address: 0x%08X\n"), i + 1, lpFrames[i].dwReturnAddr);


[Log function's enter/exit]
class FunctionLogger
{
    public:
    FunctionLogger(char* name, void* pointer);
    ~FunctionLogger();
    private:
    char* functionName;
    void* pointerAddr;
};
FunctionLogger::FunctionLogger(char* name, void* pointer)
:functionName(name),pointerAddr(pointer)
{
    printf("Function Enter %s this=%d\n", functionName, pointerAddr);
}

FunctionLogger::~FunctionLogger()
{
    printf("Function Leave %s this=%d\n", functionName, pointerAddr);
}

#define LogEnterAndLeave(pointer) FunctionLogger funcLogger(__FUNCTION__, pointer)

void fired()
{
    LogEnterAndLeave(this);
    ...........
}

[How to print virtual function pointer address before runnuing it]
class TimerBase {
...
private:
virtual void fired() = 0;
..
}
typedef void (*functionPtr)();

void ThreadTimers::sharedTimerFiredInternal()
{
...
int *vptr = *(int**)&timer;
int *vtable = (int *)*vptr;
functionPtr fp = (functionPtr)vtable[1]; // offset 1 is the “fired()” function offset in Timer class virtual function table
printf("ThreadTimers::sharedTimerFiredInternal call fired function:%p\n",fp);

timer->fired();

printf("ThreadTimers::sharedTimerFiredInternal fired function finish\n");
...
}

0 意見:

張貼留言