Question

I am trying to call malloc from iOS arm64 assembly .s file, However calling _test_malloc from *.m file, it does not return from _test_malloc() (running this on iPhone5s)

What am I misunderstanding ?

//test_malloc.s
.private_extern _test_malloc
.globl  _test_malloc
.align  2
_test_malloc:
    mov  x0,  #8    
    bl   _malloc    //wordPtr = malloc(8)
    ret



//run_test_malloc.m
    extern uint32_t* test_malloc();
    static void run_test_malloc() {
        uint32_t* ptr = test_malloc();   
    }
Was it helpful?

Solution 2

Here is how I fixed it:

.private_extern _test_malloc
.globl          _test_malloc
.align          2
_test_malloc:
    //function prolog
    stp fp, lr, [sp, #-16]!
    mov fp, sp

    orr x0, xzr, #0x8
    bl _malloc         //malloc(8)

    //function epilog
    ldp fp, lr, [sp], #16
    ret lr

OTHER TIPS

You're not saving the caller's link register contents. You need to save this in your function prologue instruction and you need to restore it in the function epilogue. Because you're saving something on your stack, you'll need to also adjust the stack pointer down so it stays 16-byte aligned as required by the ABI. You'll need to set your frame pointer register and restore it after the function all.

I would recommend disassembling compiler-generated functions to see how this setup and teardown is done. It is simple template code that's done the same in nearly every function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top