简体   繁体   English

如何在C程序中打印堆栈的内容?

[英]How can I print the contents of stack in C program?

I want to, as the title says, print the contents of the stack in my C program. 正如标题所说,我想在我的C程序中打印堆栈的内容。

Here are the steps I took: 以下是我采取的步骤:

  • I made a simple assembly (helper.s) file that included a function to return the address of my ebp register and a function to return the address of my esp register 我做了一个简单的汇编(helper.s)文件,其中包含一个返回我的ebp寄存器地址的函数和一个返回我的esp寄存器地址的函数

     .globl get_esp get_esp: movl %esp, %eax ret # get_ebp is defined similarly, and included in the .globl section 
  • I called the get_esp () and get_ebp () functions from my C program ( fpC = get_esp (); where fpC is an int) 我从我的C程序中调用了get_esp ()get_ebp ()函数( fpC = get_esp ();其中fpC是一个int)
  • I (successfully, I think) printed the address of my esp and ebp registers ( fprintf (stderr, "%x", fcP); ) 我(成功地,我认为)打印了我的esp和ebp寄存器的地址( fprintf (stderr, "%x", fcP);
  • I tried, and failed to, print out the contents of my esp register. 我尝试了,但未能打印出我的esp寄存器的内容。 (I tried fprintf (sderr, "%d", *fcP); and fprintf (sderr, "%x", *((int *)fcP)); , among other methods). (我尝试了fprintf (sderr, "%d", *fcP);fprintf (sderr, "%x", *((int *)fcP));以及其他方法)。 My program hits a segmentation fault at runtime when this line is processed. 处理此行时,我的程序在运行时遇到分段错误。

What am I doing wrong? 我究竟做错了什么?

EDIT: This must be accomplished by calling these assembly functions to get the stack pointers. 编辑:这必须通过调用这些汇编函数来获得堆栈指针来完成。 EDIT2: This is a homework assignment. EDIT2:这是家庭作业。

If your utilising a GNU system, you may be able to use GNU's extension to the C library for dealing backtraces, see here . 如果您使用GNU系统,您可以使用GNU的C库扩展来处理回溯,请参见此处

#include <execinfo.h>

int main(void)
{
     //call-a-lot-of-functions
}

void someReallyDeepFunction(void)
{
    int count;
    void *stack[50]; // can hold 50, adjust appropriately
    char **symbols;

    count = backtrace(stack, 50);
    symbols = backtrace_symbols(stack, count);

    for (int i = 0; i < count; i++)
        puts(symbols[i]);

    free(symbols);
}

get_esp returns esp as it is within the function. get_esp返回esp因为它在函数内。 But this isn't the same as esp in the calling function, because the call operation changes esp . 但这与调用函数中的esp ,因为调用操作会改变esp

I recommend replacing the function with a piece of inline assembly. 我建议用一个内联组件替换该功能。 This way esp won't change as you try to read it. 这样esp在你尝试阅读它时不会改变。

Also, printing to sderr wouldn't help. 此外,打印到sderr无济于事。 From my experience, stderr works much better. 根据我的经验, stderr工作得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM