3

I am trying to understand the assembly code for a simple program, shown below.

void f()
{
  int i, x = 0;
  for (i = 0; i < 10; i++)
    x++;

  printf("Value of x: %d\n", x);
}

and its corresponding assembly code on my machine is

00000000000007d4 <f>:
 7d4:   a9be7bfd    stp x29, x30, [sp, #-32]!
 7d8:   910003fd    mov x29, sp
 7dc:   b9001fff    str wzr, [sp, #28]
 7e0:   b9001bff    str wzr, [sp, #24]
 7e4:   14000007    b   800 <f+0x2c>
 7e8:   b9401fe0    ldr w0, [sp, #28]
 7ec:   11000400    add w0, w0, #0x1
 7f0:   b9001fe0    str w0, [sp, #28]
 7f4:   b9401be0    ldr w0, [sp, #24]
 7f8:   11000400    add w0, w0, #0x1
 7fc:   b9001be0    str w0, [sp, #24]
 800:   b9401be0    ldr w0, [sp, #24] 
 804:   7100241f    cmp w0, #0x9
 808:   54ffff0d    b.le    7e8 <f+0x14>
 80c:   b9401fe1    ldr w1, [sp, #28]
 810:   90000000    adrp    x0, 0 <__abi_tag-0x278>
 814:   9121c000    add x0, x0, #0x870
 818:   97ffff9a    bl  680 <printf@plt>
 81c:   d503201f    nop
 820:   a8c27bfd    ldp x29, x30, [sp], #32
 824:   d65f03c0    ret

I understand the loop, but line 814 - 818 is really confusion to me. What's the purpose of adding #0x870 to x0? What does line 818 mean? And how arguments are passed to the printf() function?

I expect words like "Value of x: " appears in the assembly code, but it seems like the compiler simply knows what to print.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
JaytheInj
  • 47
  • 6
  • 4
    The string is elsewhere, it's a constant embedded in the (usually read only) data section. The lines 810-814 calculate its address. Line 818 is the call to `printf` (via the PLT). As to argument passing, consult ABI reference docs, but TL;DR: first argument is in `x0`, second in `x1` (`w1` for your `int`). PS: instead of disassembly, you can look at the assembly source produced by the compiler. That will be more readable and will also contain your string. You can use `gcc -S` or godbolt.org for online. – Jester Jan 23 '23 at 00:36
  • 1
    Enable optimization, it'll be much less of a mess of store/reload of the loop counter, leaving just the interesting instructions. [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/a/38552509) The address for `adrp` is `0` because you're looking at an unlinked `.o`, not a running executable with ASLR done. The `"Value of x:` *will* appear in the asm output, in `.section .rodata`; your code gets its address. With numbers instead of labels because you're looking at disassembly, not compiler asm output. – Peter Cordes Jan 23 '23 at 01:23

0 Answers0