2

I've created a simple program so I can examine its assembly representation:

//sum.c
int sum(int x, int y)
{
    int t = x + y;
    return t;
}

//main.c
int main()
{
    return sum(4, 7);
}

I compiled this with gcc -o prog main.c sum.c -m32 and disassembled it with objdump -d prog.

An unusual thing I noticed about the assembly was that some functions would be appended with a series of xchg %ax,%ax or nop instructions. For example, this is what sum looks like:

0804840c <sum>:
804840c:    55            push   %ebp
804840d:    89 e5         mov    %esp,%ebp
804840f:    83 ec 10      sub    $0x10,%esp
8048412:    8b 45 0c      mov    0xc(%ebp),%eax
8048415:    8b 55 08      mov    0x8(%ebp),%edx
8048418:    01 d0         add    %edx,%eax
804841a:    89 45 fc      mov    %eax,-0x4(%ebp)
804841d:    8b 45 fc      mov    -0x4(%ebp),%eax
8048420:    c9            leave  
8048421:    c3            ret    
8048422:    66 90         xchg   %ax,%ax
8048424:    66 90         xchg   %ax,%ax
8048426:    66 90         xchg   %ax,%ax
8048428:    66 90         xchg   %ax,%ax
804842a:    66 90         xchg   %ax,%ax
804842c:    66 90         xchg   %ax,%ax
804842e:    66 90         xchg   %ax,%ax

What is the purpose of these extra instructions? Is gcc possibly trying to align functions to certain addresses for some reason?

Hugo Burd
  • 301
  • 1
  • 4
  • 12
  • Well I hate SO closes it as a duplicate, I only wanted to suggest the duplicate... – ouah Oct 22 '14 at 03:28
  • @ouah That's what you get, Mr-gold-badge-smarty-pants! But really, they should warn you before jumping to close. I do agree with your dup however. – Jonathon Reinhart Oct 22 '14 at 03:31
  • It's precisely correct. The only difference here, I think, is that GCC is using a two-byte NOP to minimize usage of the µop cache. –  Oct 22 '14 at 03:35
  • @ouah: Looks entirely appropriate to me. Worry not. – Kerrek SB Oct 22 '14 at 08:26

0 Answers0