Assembly Language for Beginners

(nextflipdebug2) #1

1.9. SCANF()
Listing 1.78: Optimizing GCC 4.4.5 (objdump)
1 004006c0

:
2 ; function prologue:
3 4006c0: 3c1c0042 lui gp,0x42
4 4006c4: 27bdffe0 addiu sp,sp,-32
5 4006c8: 279c8940 addiu gp,gp,-30400
6 4006cc: afbf001c sw ra,28(sp)
7 4006d0: afbc0010 sw gp,16(sp)
8 ; call puts():
9 4006d4: 8f998034 lw t9,-32716(gp)
10 4006d8: 3c040040 lui a0,0x40
11 4006dc: 0320f809 jalr t9
12 4006e0: 248408f0 addiu a0,a0,2288 ; branch delay slot
13 ; call scanf():
14 4006e4: 8fbc0010 lw gp,16(sp)
15 4006e8: 3c040040 lui a0,0x40
16 4006ec: 8f998038 lw t9,-32712(gp)
17 ; prepare address of x:
18 4006f0: 8f858044 lw a1,-32700(gp)
19 4006f4: 0320f809 jalr t9
20 4006f8: 248408fc addiu a0,a0,2300 ; branch delay slot
21 ; call printf():
22 4006fc: 8fbc0010 lw gp,16(sp)
23 400700: 3c040040 lui a0,0x40
24 ; get address of x:
25 400704: 8f828044 lw v0,-32700(gp)
26 400708: 8f99803c lw t9,-32708(gp)
27 ; load value from "x" variable and pass it to printf() in $a1:
28 40070c: 8c450000 lw a1,0(v0)
29 400710: 0320f809 jalr t9
30 400714: 24840900 addiu a0,a0,2304 ; branch delay slot
31 ; function epilogue:
32 400718: 8fbf001c lw ra,28(sp)
33 40071c: 00001021 move v0,zero
34 400720: 03e00008 jr ra
35 400724: 27bd0020 addiu sp,sp,32 ; branch delay slot
36 ; pack of NOPs used for aligning next function start on 16-byte boundary:
37 400728: 00200825 move at,at
38 40072c: 00200825 move at,at


Now we see thexvariable address is read from a 64KiB data buffer using GP and adding negative offset to
it (line 18). More than that, the addresses of the three external functions which are used in our example
(puts(),scanf(),printf()), are also read from the 64KiB global data buffer using GP (lines 9, 16 and
26). GP points to the middle of the buffer, and such offset suggests that all three function’s addresses,
and also the address of thexvariable, are all stored somewhere at the beginning of that buffer. That
make sense, because our example is tiny.

Another thing worth mentioning is that the function ends with twoNOPs (MOVE $AT,$AT— an idle instruc-
tion), in order to align next function’s start on 16-byte boundary.

Initialized global variable

Let’s alter our example by giving thexvariable a default value:

int x=10; // default value

Now IDA shows that thexvariable is residing in the .data section:

Listing 1.79: Optimizing GCC 4.4.5 (IDA)
.text:004006A0 main:
.text:004006A0
.text:004006A0 var_10 = -0x10
.text:004006A0 var_8 = -8
.text:004006A0 var_4 = -4
.text:004006A0
.text:004006A0 lui $gp, 0x42
.text:004006A4 addiu $sp, -0x20
Free download pdf