Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc stack optimization?

I just wrote a code sample in C and tried disassembling it. Following is the code sample.

void start() {
    char phone[100];
    strcmp(phone, "12312312313");

    char name[100];
    strcmp(name, "eQuiNoX");

    char contact[100];
    strcmp(contact, "PM twitter.com/eQuiNoX__");
}

When I disassemble the start function I get the following:-

08048414 <start>:
 8048414: 55                    push   ebp
 8048415: 89 e5                 mov    ebp,esp
 8048417: 81 ec 58 01 00 00     sub    esp,0x158
 804841d: c9                    leave  
 804841e: c3                    ret   
  1. I have not enabled any kind of optimization. Could someone explain why I get 158 subtracted from esp rather than assembly code which pushes values onto the stack and calls the strcmp method? Is it because it does not depend on any user input?
  2. Also, is there any way I could generate the extended assembly(im not sure if thats the right term, i just wish to see the assembly code for pushing values onto the stack and the calling of the strcmp function). Is there any way I could do that?
  3. Is this kind of behavior specific to processor architectures or gcc versions or both?

1 Answers

First, strcmp is a standard library function, so gcc is free to have special knowledge about how it works. In fact, it does; it'll seldom generate a library call. You can try -fno-builtin to disable.

Second, you're comparing to unitialized values. This is, I believe undefined behavior. So the compiler may do anything it pleases, including producing random code.

You can try the -S option to gcc get more detailed disassembly (or, rather, lack of assembly); alternatively, if you compile with -g (debugging), objdump -S will display the source along with the assembled code.

Here is an example I compiled with gcc -fno-builtin -g -O0 test.c -c and then dumped with objdump -S test.o:

test.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <main>:
#include <string.h>

int main() {
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 83 ec 10             sub    $0x10,%rsp
    const char foo[] = "foo";
   8:   8b 05 00 00 00 00       mov    0x0(%rip),%eax        # e <main+0xe>
   e:   89 45 f0                mov    %eax,-0x10(%rbp)
    return strcmp(foo, "bar");
  11:   48 8d 45 f0             lea    -0x10(%rbp),%rax
  15:   be 00 00 00 00          mov    $0x0,%esi
  1a:   48 89 c7                mov    %rax,%rdi
  1d:   e8 00 00 00 00          callq  22 <main+0x22>
}
  22:   c9                      leaveq 
  23:   c3                      retq   
like image 170
derobert Avatar answered Sep 10 '26 15:09

derobert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!