欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言程序调用栈:backtrace+backtrace_symbols+backtrace_symbols_fd

程序员文章站 2022-07-14 23:43:47
...

 

#ifndef __CRTL_BITS_ASSERT_H
#define __CRTL_BITS_ASSERT_H 1

#include <errno.h>
#include <string.h>

#include "crtl/bits/crtl_assert_backtrace.h"

#define CRTL_SYS_ERROR  strerror(errno)

/* backtrace */
#define crtl_assert_backtrace(fp) __crtl_assert_backtrace(fp)

/* macro */
#define crtl_assert(exp) crtl_assert_fp(stderr, exp)
#define crtl_assert_fp(fp, exp) __crtl_assert(fp, !!(exp), 0, __FILE__, __func__, __LINE__)


/* crypto API */
void __crtl_assert(FILE *fp, int exp, int switch_on_assert, const char *__file, const char *__func, const int __line);


#endif /*<__CRTL_BITS_ASSERT_H>*/



#include "crtl/crtl_assert.h"
#include "crtl/crtl_lock.h"



/* crypto API */
#define __assert_prefix     "assert."

void __crtl_assert(FILE *fp, int exp, int switch_on_assert, const char *__file, const char *__func, const int __line)
{
    if(!fp)
    {
        fp = stdout;
    }
    crtl_fd_lock(fileno(fp));
    if(!exp)
    {        
#define __ASSERT_NOTE_FMT       "Assert [File:%s %s:%d]"    
#define __ASSERT_NOTE_CONTEXT   __file, __func, __line
#define __ASSERT_NOTE_PREFIX    "\033[1;31m"
#define __ASSERT_NOTE_SUBFIX    "\033[0m"

        fprintf(fp, __ASSERT_NOTE_FMT"\n", __ASSERT_NOTE_CONTEXT);
        fprintf(fp, "%s"__ASSERT_NOTE_FMT"%s\n",__ASSERT_NOTE_PREFIX, __ASSERT_NOTE_CONTEXT,__ASSERT_NOTE_SUBFIX);
        
        crtl_assert_backtrace(fp);

        fflush(fp);
    }

    crtl_fd_unlock(fileno(fp));

    if(switch_on_assert)
        assert(exp);
    
    return ;
}


backtrace

#ifndef __CRTL_BITS_ASSERT_BACKTRACE_H
#define __CRTL_BITS_ASSERT_BACKTRACE_H 1


#include <assert.h>
#include <execinfo.h>


#include "crtl/easy/attribute.h"
#include "crtl/easy/macro.h"
#include "crtl/crtl_log.h"


#define __CRTL_BACKTRACE_SIZE 1024

/* backtrace */
static inline void _unused __crtl_assert_backtrace(FILE *fp)
{
    if(fp == NULL)
    {
        fp = stderr;
    }
 
    void *__buffer[__CRTL_BACKTRACE_SIZE];
    unsigned long size = 0;
    char **__backtrace;
    int _unused i;
    
    size = backtrace (__buffer, __CRTL_BACKTRACE_SIZE);
    __backtrace = backtrace_symbols (__buffer, size);
    
    //FILE *__fp = fopen("core.121212", "w");
    //backtrace_symbols_fd (__buffer, size, fileno(fp));
    
    backtrace_symbols_fd (__buffer, size, fileno(fp));

    free(__backtrace);
    
    return;    
}


#endif /*<__CRTL_BITS_ASSERT_BACKTRACE_H>*/

C语言程序调用栈:backtrace+backtrace_symbols+backtrace_symbols_fd

相关标签: C/C++