简体   繁体   English

汇编代码中的Segmentation Fault / SIGSEV

[英]Segmentation Fault/ SIGSEV in assembly code

I am working on a project that calls an assembly function from c code. 我正在一个从C代码调用汇编函数的项目中。 When running the code I made I am getting segmentation faults and I am not sure why. 运行代码时,我遇到了段错误,但不确定为什么。

file.c: 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: 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. 我通过以下方式编译代码: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)". 我调试了代码,发现在最后一行“ cmpl $ 0x0,-0x8(%rbp)”之后出现SIGSEV信号。 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). 我不太确定您的汇编代码实际上在做什么 ,但是它错过了ret语句(并且需要还原堆栈)。 There is no "implicit return" in assembly as known from C code. 如C代码所知,汇编中没有“隐式返回”。 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): 因此,您需要在汇编函数的顶部和底部添加一些代码行(您也可以将其与已编译但未汇编或反汇编的C函数进行比较,它们具有与手写体类似的结构):

push %rbp
mov %rsp, %rbp

...

mov %rbp, %rsp
pop %rbp
ret

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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