gpt4 book ai didi

c - 使用 GCC 生成可读程序集?

转载 作者:太空狗 更新时间:2023-10-29 16:13:44 25 4
gpt4 key购买 nike

我想知道如何使用 GCC在我的 C 源文件上转储机器代码的助记符版本,这样我就可以看到我的代码被编译成什么。您可以使用 Java 执行此操作,但我无法找到使用 GCC 的方法。

我正在尝试在汇编中重写一个 C 方法,看看 GCC 是如何做的,这将是一个很大的帮助。

最佳答案

如果您使用调试符号进行编译(将 -g 添加到您的 GCC 命令行,即使您还使用了 -O31 ),您可以使用 objdump -S 生成与 C 源代码交错的更具可读性的反汇编。

>objdump --help
[...]
-S, --source Intermix source code with disassembly
-l, --line-numbers Include line numbers and filenames in output

objdump -drwC -Mintel 很好:

  • -r 显示重定位的符号名称(因此您会在下面的 call 指令中看到 puts)
  • -R 显示动态链接重定位/符号名称(对共享库有用)
  • -C 分解 C++ 符号名称
  • -w 是“宽”模式:它不换行机器代码字节
  • -Mintel:使用类似 GAS/binutils MASM 的 .intel_syntax noprefix 语法代替 AT&T
  • -S:在反汇编中插入源代码行。

你可以在你的 ~/.bashrc 中加入类似 alias disas="objdump -drwCS -Mintel" 的内容。如果不是在 x86 上,或者如果您喜欢 AT&T 语法,请省略 -Mintel


例子:

> gcc -g -c test.c
> objdump -d -M intel -S test.o

test.o: file format elf32-i386


Disassembly of section .text:

00000000 <main>:
#include <stdio.h>

int main(void)
{
0: 55 push ebp
1: 89 e5 mov ebp,esp
3: 83 e4 f0 and esp,0xfffffff0
6: 83 ec 10 sub esp,0x10
puts("test");
9: c7 04 24 00 00 00 00 mov DWORD PTR [esp],0x0
10: e8 fc ff ff ff call 11 <main+0x11>

return 0;
15: b8 00 00 00 00 mov eax,0x0
}
1a: c9 leave
1b: c3 ret

请注意,这不是使用-r,因此call rel32=-4 没有用puts 注释 符号名称。并且看起来像一个中断的 call 跳转到了 main.call 指令的中间。请记住,调用编码中的 rel32 位移只是一个占位符,直到链接器填充一个真正的偏移量(在这种情况下为 PLT stub ,除非您静态链接 libc)。


脚注 1:交错源代码可能很困惑,对优化构建没有太大帮助;为此,请考虑 https://godbolt.org/或其他可视化哪些指令与哪些源代码行一起使用的方法。在优化代码中有 not always a single source line that accounts for an instruction但调试信息将为每个 asm 指令选择一个源代码行。

关于c - 使用 GCC 生成可读程序集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1289881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com