Linux/Linux System Programming

dump_stack()함수

Hans_S_92 2022. 11. 20. 23:22
dump_stack() 함수

커널에서 지원하는 dump_stack() 함수를 호출하면 콜 스택을 커널 로그로 볼 수 있다.

사용법은 커널 로그로 콜 스택을 보고 싶은 코드에 dump_stack() 를 추가하기만 하면 된다.

#include <linux/kernel.h>

 

위의 헤더 파일을 추가해서 사용한다.

dump_stack() 함수의 선언부는 다음과 같다.

asmlinkage __visible void dump_stack(void);

매개변수와 반환값이 모두 void이다. 즉, 커널 소스코드의 어디든 사용이 가능하다.

 

dump_stack()함수로 커널 로그에서 콜 스택 호출하기

kernel/fork.c 파일 수정.

라즈비안의 커널을 빌드와 설치 후 재부팅합니다. 

 

dump_stack() 함수 실행 확인

[28.785596] cpu 번호, pid 번호, comm 프로세스 이름.을 나타냅니다. 

로그 순서는 아래에서 위로 읽습니다. sys_clone -> _do_fork -> dump_stack -> show_stack -> unwind_backtarce 등으로 읽습니다. 

_do_fork에서 dump_stack() 함수를 추가하였기에 sys_clone 이후 _do_fork가 실행된다고 확인할 수 있을 것입니다. 

 

dump_stack() 함수 원형

함수 원형이 어디있을 지 궁금해서 linux 폴더에서 grep으로 함수 원형을 찾아보았다.

./linux/lib/dump_stack.c

// SPDX-License-Identifier: GPL-2.0
/*
 * Provide a default dump_stack() function for architectures
 * which don't implement their own.
 */

#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/sched/debug.h>
#include <linux/smp.h>
#include <linux/atomic.h>
#include <linux/kexec.h>
#include <linux/utsname.h>

static char dump_stack_arch_desc_str[128];

/**
 * dump_stack_set_arch_desc - set arch-specific str to show with task dumps
 * @fmt: printf-style format string
 * @...: arguments for the format string
 *
 * The configured string will be printed right after utsname during task
 * dumps.  Usually used to add arch-specific system identifiers.  If an
 * arch wants to make use of such an ID string, it should initialize this
 * as soon as possible during boot.
 */
void __init dump_stack_set_arch_desc(const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
          fmt, args);
    va_end(args);
}

/**
 * dump_stack_print_info - print generic debug info for dump_stack()
 * @log_lvl: log level
 *
 * Arch-specific dump_stack() implementations can use this function to
 * print out the same debug information as the generic dump_stack().
 */
void dump_stack_print_info(const char *log_lvl)
{
    printk("%sCPU: %d PID: %d Comm: %.20s %s%s %s %.*s\n",
           log_lvl, raw_smp_processor_id(), current->pid, current->comm,
           kexec_crash_loaded() ? "Kdump: loaded " : "",
           print_tainted(),
           init_utsname()->release,
           (int)strcspn(init_utsname()->version, " "),
           init_utsname()->version);

    if (dump_stack_arch_desc_str[0] != '\0')
        printk("%sHardware name: %s\n",
               log_lvl, dump_stack_arch_desc_str);

    print_worker_info(log_lvl, current);
}

/**
 * show_regs_print_info - print generic debug info for show_regs()
 * @log_lvl: log level
 *
 * show_regs() implementations can use this function to print out generic
 * debug information.
 */
void show_regs_print_info(const char *log_lvl)
{
    dump_stack_print_info(log_lvl);
}

static void __dump_stack(void)
{
    dump_stack_print_info(KERN_DEFAULT);
    show_stack(NULL, NULL);
}

/**
 * dump_stack - dump the current task information and its stack trace
 *
 * Architectures can override this implementation by implementing its own.
 */
#ifdef CONFIG_SMP
static atomic_t dump_lock = ATOMIC_INIT(-1);

asmlinkage __visible void dump_stack(void)
{
    unsigned long flags;
    int was_locked;
    int old;
    int cpu;
    
    
    /*
     * Permit this cpu to perform nested stack dumps while serialising
     * against other CPUs
     */
retry:
    local_irq_save(flags);
    cpu = smp_processor_id();
    old = atomic_cmpxchg(&dump_lock, -1, cpu);
    if (old == -1) {
        was_locked = 0;
    } else if (old == cpu) {
        was_locked = 1;
    } else {
        local_irq_restore(flags);
        /*
         * Wait for the lock to release before jumping to
         * atomic_cmpxchg() in order to mitigate the thundering herd
         * problem.
         */
        do { cpu_relax(); } while (atomic_read(&dump_lock) != -1);
        goto retry;
    }

    __dump_stack();

    if (!was_locked)
        atomic_set(&dump_lock, -1);

    local_irq_restore(flags);
}
#else
asmlinkage __visible void dump_stack(void)
{
    __dump_stack();
}
#endif
EXPORT_SYMBOL(dump_stack);

찾아보면 포인터들을 어디서 가지고 오는 지 봐야하겠지만, 결과적으로 printk의 연속이다. 

 

dump_stack() 함수 주의할 점
  • printk가 많기 때문에 단순히 printk를 입력하는 것보다 많은 비용 소모한다. 따라서 printk의 문제점을 그대로 가지고 있다.
  • 커널 코드에 dump_stack()함수를 추가하고 커널 빌드 & 설치 해야 확인할 수 있다.

 

'Linux > Linux System Programming' 카테고리의 다른 글

프로세스는 뭘까? - 정의  (0) 2022.12.08
ftrace란?  (0) 2022.11.24
커널 디버깅 - printk  (0) 2022.11.20
커널 로그 확인 방법  (0) 2022.11.20
파일 입출력  (0) 2022.04.19