## Saturday, September 24, 2016

### Intel Assembly Basics movl , cmpl , jns

Intel Assembly Basics

Here's a simple code block, what does it do?

0x080483c1 <+6>: movl \$0x15,-0x4(%ebp)
0x080483c8 <+13>: cmpl \$0x0,-0x4(%ebp)
0x080483cc <+17>: jns 0x80483d5
0x080483ce <+19>: movl \$0xf,-0x4(%ebp)
0x080483d5 <+26>: ...

movl is 'move long' which in this case is a 32 bit integer. Hex 0x15 is 16+5=21 so it's putting 21 onto the first value in the stack (-0x4).

cmpl is 'compare long' so it's comparing 2 integers, the value 0x0 which is simply 0 and the first value on the stack (-0x4) which from the previous line we know has a value 21. Hex 0x15 is 16+5=21 so it's putting 21 onto the first value in the stack (-0x4). Compare wants to determine if the values are the same or different. So it does that by subtracting 21 - 0 . If the result of the subtraction is 0 then it would set the Zero Flag (ZF) to 1 (or true). If the result of the subtraction is anything else then it sets the Zero Flag (ZF) to 0 (or false). Thus in this case 21-0=21 so the Zero Flag (ZF) is set to 0 (or false). Also the compare instruction sets the Sign Flag (SF) to 1 if the result is a negative number and and 0 if it's positive. In this case it's +21 to it's positive so it's set to 0.

jns is 'jump if not signed'. Jump if not signed jumps if the Sign Flag (SF) is 0 (thus if the previous compare result was positive +). So in this case SF was set to 0 which means the value was positive (or not signed), so it's going to jump to address 0x80483d5.

movl is 'move long' again just like above, and this time it's putting 15 into the top value in the stack (-0x4), but in this case since we jumped, this instruction never actually gets executed.

Thus to wrap this all up, you could rewrite this code in psuedo C code as follows

int x = 21;
if(x < 21)
x = 15;