当我的程序在gdb中被反汇编时,我可以看到buf的地址被压入堆栈,但我没有看到格式字符串被压到它上面。这是什么原因?它是一个聪明的编译器优化吗?
我已经尝试编译一些printf语句的不同变体,看看我是否可以模仿“%s”字符串(或它的地址)没有被压入堆栈,但是我无法做到。
这是程序代码:
int main(int argc, char **argv) {
char buf[128];
if(argc < 2) return 1;
strcpy(buf, argv[1]);
printf("%s\n", buf);
return 0;
}
使用gcc 4.5.2编译,32位linux
答案 0 :(得分:7)
是的,似乎gcc会抛弃“printf(”%s \ n“,buff)”并将“puts()”替换为其位置:
vi tmp.c =>
#include <stdio.h>
#include <string.h>
int
main(int argc, char **argv)
{
char buf[128];
if(argc < 2)
return 1;
strcpy(buf, argv[1]);
printf("%s\n", buf);
return 0;
}
$ gcc -S -Wall -pedantic tmp.c 少tmp.s =&gt;
.file "tmp.c"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $148, %esp
movl %ecx, -140(%ebp)
movl -140(%ebp), %eax
cmpl $1, (%eax)
jg .L2
movl $1, -136(%ebp)
jmp .L4
.L2:
movl -140(%ebp), %edx
movl 4(%edx), %eax
addl $4, %eax
movl (%eax), %eax
movl %eax, 4(%esp)
leal -132(%ebp), %eax
movl %eax, (%esp)
call strcpy
leal -132(%ebp), %eax
movl %eax, (%esp)
call puts
movl $0, -136(%ebp)
.L4:
movl -136(%ebp), %eax
addl $148, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.1.2 20080704 (Red Hat 4.1.2-48)"
.section .note.GNU-stack,"",@progbits
答案 1 :(得分:1)
以下答案适用于x86 64位汇编程序。
简短的回答:x86没有%s作为某种汇编指令,即纯c甚至java现在也是如此。
答案很长:
使用符号编译程序(非剥离):gcc -g yourprogram.c
使用混合的c代码转储程序集:objdump -S yourProgram.o
以下文字显示了strcpy
和printf
在装配中的显示方式。我还添加了你应该如何阅读程序集:
strcpy(buf, argv[1]);
4005eb: 48 8b 85 60 ff ff ff mov -0xa0(%rbp),%rax
Move argv[0] to %rax register
4005f2: 48 83 c0 08 add $0x8,%rax
Add 8 to %rax which means we now store argv[1]
4005f6: 48 8b 10 mov (%rax),%rdx
Copy argv[1] to the destination register %rdx
4005f9: 48 8d 85 70 ff ff ff lea -0x90(%rbp),%rax
Move buf to %rax
400600: 48 89 d6 mov %rdx,%rsi
Move argv[1] to %esi which is the source register implicitly used by string funcs
400603: 48 89 c7 mov %rax,%rdi
Move buf to destination register
400606: e8 85 fe ff ff callq 400490 <strcpy@plt>
Call strcpy which uses %rsi and %rdi
Now we have argv[1] in buf, right!?
printf("%s\n", buf);
40060b: 48 8d 85 70 ff ff ff lea -0x90(%rbp),%rax
The first line loads what you have at the base pointer -0x90 to the %rax register which means that it loads the address of buf into rax as buf is on the stack.
400612: 48 89 c7 mov %rax,%rdi
Just mov it to the %rdi register.
400615: e8 86 fe ff ff callq 4004a0 <puts@plt>
Call the puts function with buf