【问题标题】:segmentation fault when calling c function调用c函数时出现分段错误
【发布时间】:2013-11-19 06:17:14
【问题描述】:

我是 x86-64 汇编的新手,我正在运行一个简单的 x64 汇编代码:

.global main

.text
main:                                
    mov     $message, %rdi       
    sub     $8, %rsp             
    call    puts                 
    add     $8, %rsp             
    ret                          
message:
    .asciz "Hello, World"        

在cygwin下使用gcc编译代码后,总是返回错误:

segmentation error

但如果我删除

call puts

程序运行没有错误。那么这个调用语句有什么问题呢?

【问题讨论】:

  • 您可能缺少函数调用 ABI 的一部分。这是高度依赖于平台的。编写一个等效的 C 程序并用-S -O3 编译它。生成的汇编程序应该会提示您平台需要什么。通常,在汇编程序中编写函数本身并不是一个好主意。至少用 C 编写包装器并在内部使用 __asm__ 包含特定的汇编器部分要容易得多。

标签: c gcc assembly cygwin


【解决方案1】:

您必须在只读数据部分定义message...
像这样……

.rodata                               # read-only data section
message:
    .string    "Hello, World!"

在 32 位机器上,使用 AT&T 语法,代码如下...

.section .rodata
msg:
    .string    "Hello, World!"        # msg is in the read only data section.

.section .text
    .globl    main
    .type     main, @function
main:
    pushl    %ebp
    movl     %esp, %ebp
    andl     $-16, %esp
    subl     $16,  %esp

    movl     $msg, (%esp)             # We move the argument of puts to (%esp)
    call     puts                     # puts is called

    movl     $0,   (%esp)             # moved the argument of(0) exit to (%esp)
    call     exit                     # exit is called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2022-01-04
    • 2020-04-04
    相关资源
    最近更新 更多