4

So I'm trying to write some C code by looking at the assembly here:

pushl   %ebp
movl    %esp, %ebp
movl    12(%ebp), %eax
addl    8(%ebp), %eax
movzbl  (%eax), %eax
movsbl  %al,%eax
popl    %ebp
ret

I see that I have two variables, and they are being added together, then I'm getting lost when looking when the function starts calling movzbl and movesbl. What's going on here?

rjp
  • 1,760
  • 13
  • 15
Daniel Love Jr
  • 950
  • 5
  • 13
  • 17
  • possible duplicate of [What does the MOVZBL instruction do in IA-32 AT&T syntax?](http://stackoverflow.com/questions/9317922/what-does-the-movzbl-instruction-do-in-ia-32-att-syntax) – Ciro Santilli OurBigBook.com Jun 29 '15 at 12:05

1 Answers1

12

A corresponding C function would be something like

char fn(char * string, int index)
{
    return string[index];
}

Specifically, the movzbl instruction fetches the byte stored at the sum of the two parameters, zero pads it, and stores it into eax. The movsbl instruction takes the lowest byte of eax, sign extends it, and stores the result back in eax.

microtherion
  • 3,938
  • 1
  • 15
  • 18
  • Hrm, ok I'm still a bit confused, so if I'm dealing with strings and characters, what's the addl call doing then? I had previously thought that I was adding two integers together. Does that just combine the string and the index? – Daniel Love Jr Jun 16 '14 at 22:56
  • In assembler, you generally don't know this until you see how the result is used. Here, you see that there is an indirect load from the result, so it must have been a pointer, so one of the two parameter must have been a pointer, and the other an integer of the same size (it's impossible to tell from this code snippet which was which). – microtherion Jun 16 '14 at 22:58
  • Ah ok, so what it's trying to do is something like what you wrote, it's attempting to get a specific character from some string? – Daniel Love Jr Jun 16 '14 at 23:00
  • Technically, it was not necessarily a character, all we can know is that it was a signed 8 bit quantity, but on many systems, a character would match that profile. – microtherion Jun 16 '14 at 23:03
  • Ah I see. So it could be anything possibly? – Daniel Love Jr Jun 16 '14 at 23:04