magicleon94
magicleon94

Reputation: 5162

Segmentation fault when calling assembly function from C code

I'm trying to link assembly functions to a C code for exercise. Here's my assembly function, written in x86 assembly:

.code32

.section .text
.globl max_function
.type max_function, @function 
# i parametri saranno in ordine inverso a partire da 8(%ebp)

max_function:
    pushl %ebp              # save ebp
    movl %esp, %ebp         # new frame function
    movl $0, %edi           # first index is 0
    movl 8(%ebp), %ecx      # ecx is loaded with the number of elements
    cmpl $0, %ecx            # check that the number of elements is not 0
    je end_function_err    #if it is, exit

    movl 12(%ebp),%edx      # edx is loaded with the array base
    movl (%edx), %eax       # first element of the array

    start_loop:
    incl %edi               #increment the index
    cmpl %edi,%ecx          #if it's at the end quit
    je loop_exit
    movl (%edx,%edi,4),%ebx   #pick the value
    cmpl %ebx,%eax              #compare with actual maximum value
    jle start_loop              #less equal -> repeat loop
    movl %ebx,%eax              #greater -> update value
    jmp start_loop              #repeat loop

    loop_exit:
    jmp end_function            #finish

end_function:                   #exit operations
    movl %ebp, %esp
    popl %ebp
    ret

end_function_err:
    movl $0xffffffff, %eax            #return -1 and quit
    jmp end_function

It basically defines a function that finds the maximum number of an array (or it should be)

And my C code:

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

extern int max_function(int size, int* values);

int main(){
    int values[] = { 4 , 5 , 7 , 3 , 2 , 8 , 5 , 6 } ;
    printf("\nMax value is: %d\n",max_function(8,values));
}

I compile them with gcc -o max max.s max.c.
I get a SegmentationFault when executing the code.
My suspect is that I don't access the value in a right manner, but I can't see why, even because I based my code on an example code that prints argc and argv values when called from the command line.

I'm running Debian 8 64-bit

Upvotes: 1

Views: 1111

Answers (1)

magicleon94
magicleon94

Reputation: 5162

The problems were:

  • not preserving %ebx and %edi
  • not compiling for 32 bit (had to use -m32 flag for gcc)
  • cmpl operands were inverted

Thanks everybody, problem is solved. I'll focus more on debugging tools to (disassembling and running step by step was very useful)!

Upvotes: 1

Related Questions