Monday, 12 June 2017

How to access global variables and TOC


int a = 2;
int b = 3;

int foo(void) {
  printf("a+b=%d",a + b);
  return 0;
}



foo:                                    # @foo
.Lfunc_begin0:
.Lfunc_gep0:
        addis r2, r12, .TOC.-.Lfunc_gep0@ha
        addi r2, r2, .TOC.-.Lfunc_gep0@l
.Lfunc_lep0:
        .localentry     foo, .Lfunc_lep0-.Lfunc_gep0
# BB#0:                                 # %entry
        mflr r0
        std r0, 16(r1) # save the link register to 16(r1), i.e stackFrame + 16`
        stdu r1, -96(r1)  # prolog
        addis r3, r2, .LC0@toc@ha
        addis r4, r2, .LC1@toc@ha
        addis r12, r2, .L.str@toc@ha
        ld r3, .LC0@toc@l(r3)
        ld r4, .LC1@toc@l(r4)
        lwz r3, 0(r3)
        lwz r4, 0(r4)
        add r3, r4, r3
        extsw r4, r3
        addi r3, r12, .L.str@toc@l
        bl printf
        nop  # may insert tls depending on the where is the callee definition.
        li r3, 0
        addi r1, r1, 96  # the reverse of the 3rd instr
        ld r0, 16(r1) # load the old link reigster address
        mtlr r0  # restore the link register value
        blr
        .long   0
        .quad   0
.Lfunc_end0:
        .size   foo, .Lfunc_end0-.Lfunc_begin0

No comments:

Post a Comment