【问题标题】:C & Nasm64 combination - stack alignment, epilogue, prologue - OSX 64C & Nasm64 组合 - 堆栈对齐、尾声、序言 - OSX 64
【发布时间】:2014-10-12 06:03:39
【问题描述】:

以下程序导致分段错误,我似乎不明白为什么:

//something.c



int somefunc3();
void somefunc2();

void* globalptr;

void somefunc1(void* regs)
{
    globalptr = regs;   
    somefunc2();
}

int foo() 
{

    return somefunc3();
}


int main(void)
{
    show_all_registers();
    foo();
    show_all_registers();
}

asm:

//something1.asm

extern _somefunc1

global _somefunc2
global _somefunc3

section .text


%macro RESTORE_REGISTERS 0
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx 
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
    pop rcx
%endmacro

%macro SAVE_REGISTERS 0
    push rcx
    push rcx
    push rcx
    push rcx
    push rcx
    push rcx
    push rcx
    push rcx       
    push rcx
    push rcx
    push rcx
    push rcx    
    push rcx
    push rcx
    push rcx
    push rcx
%endmacro

_somefunc3:
    push rbp
    mov rbp, rsp
    SAVE_REGISTERS
    mov rdi, rsp

    sub rsp,8
    call    _somefunc1
    add rsp,8

    pop rbp
    ret

_somefunc2:
    push rbp
    mov rbp, rsp
    RESTORE_REGISTERS
    pop rbp
ret

几点说明:

  • 请不要试图理解这个程序的作用,因为你找不到任何有意义的东西。这只是我创建的一个用户模式应用程序,目的是理解一些东西。

  • show_all_registers 只是一个将所有 64 位寄存器打印到屏幕上的函数。

这是崩溃之前发生的情况:

64 Bit registers:
RAX=10767ad00, RCX=1, RDX=10767ab70, RBX=0, RSP=7fff58585bd0, RBP=7fff58585bd0, RSI=20000000200,     RDI=7
Segmentation fault: 11

使用 GDB 似乎在 somefunc2 上发生了崩溃(恢复寄存器时)

我认为这与堆栈对齐或我为 ASM 函数编写的结语和结语有关。还是有点新手,所以很可能是愚蠢的。

谢谢

【问题讨论】:

  • 您正在使用 GDB,您应该能够准确找出问题所在。 GDB 显示的哪个具体指令是 SIGSEGV 的来源?
  • somefunc2的返回操作。似乎它应该返回的地址无效或没有正确放置

标签: c macos nasm


【解决方案1】:

您的函数尾声不正确。您缺少mov rsp, rbp,因此您的堆栈帧在返回时完全关闭。

适当的功能是:

push rbp
mov  rbp, rsp
sub  rsp, [size of local variables]
...
mov  rsp, rbp
pop  rbp
ret

或者您可以使用LEAVE 指令进行简化:

push rbp
mov  rbp, rsp
sub  rsp, [size of local variables]
...
leave
ret

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2023-01-03
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多