c - 在 64 位汇编中编写函数

标签 c assembly

我正在尝试在 64 位汇编中编写一个函数 (max),但我不知道我做错了什么,也许你们中的一些人可以确定我做错了什么:/

函数如下:

int max(int a, int b) {
/* Return the larger of the two integers `a' and `b'. */
if (a > b)
return a;
else
return b;
}

这是我的汇编代码(带注释):

    push %rbp
    mov %rsp, %rbp
    mov %rdi, %rax
    mov %rsi, %rcx
    test %rax, %rax                // Checking if first parameter is signed
    js .signedRAX
    test %rcx, %rcx                // Checking if second parameter is signed
    js .signedRCX
    jmp .compare                   // If either one signed then jump to .compare
  .signedRAX:
    test %rcx, %rcx                // Checking if both are signed
    js .signedRAXandRCX
    mov %rcx, %rax                 // If not then return the positive number
    jmp .end                       // finish the function
  .signedRCX:
    jmp .end                       // If only the second parameter is signed then jump  
  .signedRAXandRCX:                // straight to end of function and return %rax
    cmp %rax, %rcx                 // If both are signed compare which one is the max
    jl .end 
    mov %rcx, %rax
    jmp .end
  .compare:
    cmp %rax, %rcx                 // If both are positive then compare which one is 
    jg .end                        // the max
    mov %rcx, %rax
  .end:
    mov %rbp, %rsp
    pop %rbp
    ret

比较两个既有符号又有正数的参数时,我得到了错误的输出。

最佳答案

你的工作太复杂了。

如果我将你的程序输入gcc -S,我得到

max:
.LFB0:
        .cfi_startproc
        pushl   %ebp
        .cfi_def_cfa_offset 8
        .cfi_offset 5, -8
        movl    %esp, %ebp
        .cfi_def_cfa_register 5
        movl    8(%ebp), %eax
        cmpl    12(%ebp), %eax
        jle     .L2
        movl    8(%ebp), %eax
        jmp     .L3
.L2:
        movl    12(%ebp), %eax
.L3:
        popl    %ebp
        .cfi_restore 5
        .cfi_def_cfa 4, 4
        ret
        .cfi_endproc
.LFE0:

如果我接管你的“ABI”和传递参数的方式,

我明白了

max:
    push %rbp
    mov %rsp, %rbp
    mov %rdi, %rax
    mov %rsi, %rcx
    cmpl %rcx, %rax
    jle .L2
    movl %rcx, %rax
.L2:
    mov %rbp, %rsp
    pop %rbp
    ret

关于c - 在 64 位汇编中编写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671870/

相关文章:

c - 检查 exec 中的 E2BIG 错误情况

c - Pthread 互斥锁断言失败

c - 在C中加密纯文本文件

c - c 中嵌入的汇编代码为 cmp 提供了不正确的操作数类型错误

assembly - 使用 intel x86-64 指令从 YMM 寄存器到 RAX 的 MOV

linux - QEMU 是否适合学习 ARM 和 PowerPC 的汇编程序编程?

c - 当实际上永远不会发生溢出时,Visual Studio 会发出缓冲区溢出警告

c - 使用 calloc 释放内存并更改标准输出时检测到堆损坏

assembly - ARM 汇编中的程序计数器

c - 在打开优化的情况下读取汇编代码