Returning an int* from ASM

I'm writing a function in ASM which is supposed to copy the (constant) value 2 into every index of an array declared in .data. My code compiles, but I don't get any output through my C program. Here's the code:

        .globl my_func
        .globl _my_func

my_func:
_my_func:
    movl    %esp,%ebp
    pushl   %ebp
    movl    $0,%ecx
    leal    array,%eax
    jmp     continue


continue:
_continue:
    movl    $2,array(%ecx,4)
    cmpl    $1024,%ecx
    jne     incr
    je      finish

incr:
_incr:
    addl    $4,%ecx
    jmp     continue


finish:
_finish:
    popl    %ebp
    ret

        .data

    .align 4
array:  .fill   1024

It is called from here:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

extern int* my_func();

int main(int argc, const char * argv[])
{
    int i = 0;
    int* a = my_func();
    for(i = 0; i < 1024/4; i++){
        printf("%d\n", a[i]);
    }

    return 0;
}

As mentioned, the program does compile and run, but the main function does not output anything to the terminal. And yes, I know the code isn't optimal -- I'm currently following an introductory course in computer architecture and ASM, and I'm just checking out instructions and data.

I am assembling the code for IA32 on an Intel Mac with OSX10.9, using LLVM5.1

Thanks in advance.

Upvotes: 0

Views: 221

Answers (2)

Michael
Michael

Reputation: 58427

The function prologue where you save the previous frame pointer and set it up for the new stack frame should be:

pushl   %ebp
movl    %esp,%ebp

Yours is in the opposite order, so when your function returns the caller's frame pointer will be incorrect.

Upvotes: 3

Anonymouse
Anonymouse

Reputation: 945

return values are normally in eax, so you need to set eax to the address of the start of the memory you want to return in finish.

fyi: you shouldn't need to declare your label twice, the leading underscore is only needed for public functions you want to access from C

Upvotes: 0

Related Questions