问题
I'm studying the x86 assembly language. In order to better understand what's going on behind the scenes of string creation, I have a sample program that just prints a string. GCC produced the following Assembly program, and I'm having trouble understanding the compiler's output:
Assembly Code:
Dump of assembler code for function main:
0x0000000000400596 <+0>: push %rbp
0x0000000000400597 <+1>: mov %rsp,%rbp
0x000000000040059a <+4>: sub $0x10,%rsp
0x000000000040059e <+8>: movq $0x400668,-0x8(%rbp)
0x00000000004005a6 <+16>: mov -0x8(%rbp),%rax
0x00000000004005aa <+20>: mov %rax,%rsi
=> 0x00000000004005ad <+23>: mov $0x400675,%edi
0x00000000004005b2 <+28>: mov $0x0,%eax
0x00000000004005b7 <+33>: callq 0x4004a0 <printf@plt>
0x00000000004005bc <+38>: mov $0x0,%eax
0x00000000004005c1 <+43>: leaveq
0x00000000004005c2 <+44>: retq
C Code:
#include <stdio.h>
int main()
{
char *me = "abcdefghijkl";
printf("%s",me);
}
At the conceptual level, I understand that the stack pointer is being subtracted to allocate memory on the stack, and then somehow, and this is the part I'm having trouble understanding the mechanics of, the program creates the string.
Can someone please help? Thanks.
回答1:
It's a lot clearer if you use the -S
flag to gcc
to create an assembly file for your program (gcc -S asm.c
). This generates a asm.s
file:
.file "asm.c"
.section .rodata
.LC0:
.string "abcdefghijkl"
.LC1:
.string "%s"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movq $.LC0, -8(%rbp)
movq -8(%rbp), %rax
movq %rax, %rsi
movl $.LC1, %edi
movl $0, %eax
call printf
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.5 20150623 (Red Hat 4.8.5-36)"
.section .note.GNU-stack,"",@progbits
From this you can see that the string is just some initialized memory in the .rodata
section assigned the label .LC0
. Changing that memory changes the string.
来源:https://stackoverflow.com/questions/59291865/how-does-this-x86-assembly-code-create-a-string