简体   繁体   中英

Segmentation Fault/ SIGSEV in assembly code

I am working on a project that calls an assembly function from c code. When running the code I made I am getting segmentation faults and I am not sure why.

file.c:

#include <stdio.h> 
#include <time.h>
#include <unistd.h>


extern void asmFunction();

void callAsmFunction(){
  while(1){
    asmFunction();
}

return;
}


int main(int argc, char* argv[]){
  callAsmFunction();
}

asmFunction.s:

.global asmFunction
asmFunction:
    push %rbp
    movl $0x1,-0x8(%rbp)
    cmpl $0x0,-0x8(%rbp)
    jne .L2
    nop
    nop
    nop
.L2:
    cmpl $0x0,-0x8(%rbp)
    jne .L3
    nop
    nop
    nop
.L3:
    cmpl $0x0,-0x8(%rbp)

I compiled my code the following way: gcc -o file file.c asmFunction.s.

I debugged my code and saw that I would get a SIGSEV signal occurring after the last line "cmpl $0x0,-0x8(%rbp)". I do not understand why though. Is it how I am compiling my code?

I'm not quite sure what your assembly code is actually doing , but it misses an ret statement (and needs to restore the stack). There is no "implicit return" in assembly as known from C code. Also, it looks like the setup of the stack frame has not finished.

So you will need to add some code lines as this at the top and bottom of your assembly function (you can also compare to compiled, but not assembled or disassembled C functions, which have a similar structure as hand-written):

push %rbp
mov %rsp, %rbp

...

mov %rbp, %rsp
pop %rbp
ret

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM