汇编代码理解求助:C代码生成的x86汇编指令疑问解析
Understanding the Confusing Assembly Instructions
Hey there! Let's break down each of those marked ?? instructions and clear up your follow-up confusion, linking everything directly to your C code and how x86-64 assembly works on most Unix-like systems (using the System V AMD64 calling convention).
First, let's recap the key lines from your C code that correspond to this assembly:
char const* y = argv[1]; printf("%s\n", y);
Quick reminders to set the stage:
argvis achar**— that's a pointer to an array of string pointers (each pointer is 8 bytes in x86-64).main's arguments are stored on the stack after setting up the frame, soargvlives at-0x20(%rbp).- For function calls, the first argument goes in
rdi, the second inrsi, etc.
Let's unpack each ?? line:
0x00000000000006ba <+26>: mov 0x8(%rax),%rax- Right before this,
mov -0x20(%rbp),%raxpulledargv(the second argument tomain) from the stack intorax. - Since
argvpoints to an array of 8-byte pointers,argv[1]is located 8 bytes past the start of the array.0x8(%rax)computes that address, and this instruction loads the pointer to your first command-line argument intorax.
- Right before this,
0x00000000000006be <+30>: mov %rax,-0x8(%rbp)- This stores the pointer we just fetched (
argv[1]) into the stack slot reserved for your variabley. - This is exactly the assembly equivalent of
char const* y = argv[1];— we're savingy's value onto the stack frame.
- This stores the pointer we just fetched (
0x00000000000006c2 <+34>: mov -0x8(%rbp),%rax- This loads
y's value back from the stack intorax. - It might look unnecessary, but compilers often generate this kind of "round-trip" code when preparing values for function calls. We need this pointer in a register to pass it to the print function next.
- This loads
Your big question: mov %rax,%rdi # Return value copied to 1st argument register - why??
- Here's the twist you missed: your compiler optimized
printf("%s\n", y)toputs(y)! puts()only needs one argument (the string to print, and it automatically adds a newline), so passing the string pointer inrdi(the first argument register for System V AMD64) is exactly correct.- The
callq 0x560is callingputs, notprintf— your manual annotation was off here, which is why the argument count seemed wrong.
内容的提问来源于stack exchange,提问作者Average_guy
相关产品推荐
相关产品推荐

