简体   繁体   English

从x86汇编器调用C函数

[英]Calling C function from the x86 assembler

I am trying to write a function that converts decimal numbers into binary in assembler. 我正在尝试编写一个将汇编程序中的十进制数转换为二进制数的函数。 Since printing is so troublesome in there, I have decided to make a separate function in C that just prints the numbers. 由于那里的打印非常麻烦,因此我决定在C中创建一个单独的函数来仅打印数字。 But when I run the code, it always prints '0110101110110100' 但是,当我运行代码时,它始终会打印“ 0110101110110100”

Heres the C function (both print and conversion): 这是C函数(打印和转换):

void printBin(int x) {
  printf("%d", x);
}

void DecToBin(int n)
{
    // Size of an integer is assumed to be 16 bits
    for (int i = 15; i >= 0; i--) {
        int k = n >> i;
        printBin(k & 1);
}

heres the code in asm: 这是asm中的代码:

.globl _DecToBin
.extern _printBin

_DecToBin:
  pushl %ebp
  movl %esp, %ebp

  movl 8(%ebp),%eax
  movl $15, %ebx
  cmpl $0, %ebx
  jl end

  start:
  movl %ebx, %ecx
  movl %eax, %edx
  shrl %cl, %eax
  andl $1, %eax
  pushl %eax
  call _printBin
  movl %edx, %eax
  dec %ebx
  cmpl $0, %ebx
  jge start

  end:

  movl %ebp, %esp
  popl %ebp
  ret

Cant figure out where the mistake is. 无法找出错误所在。 Any help would be appreciated 任何帮助,将不胜感激

disassembled code using online program 使用在线程序反汇编代码

Your principle problem is that it is very unlikely that %edx is preserved across the function call to printBin. 您的主要问题是在对printBin的函数调用中保留%edx的可能性很小。 Also: 也:

%ebx is not a volatile register in most (any?) C calling convention rules. 在大多数(任何?)C调用约定规则中,%ebx都不是易失性寄存器。 You need to check your compilers documentation and conform to it. 您需要检查编译器文档并遵守该文档。 If you are going to use ebx, you need to save and restore it. 如果要使用ebx,则需要保存和还原它。

The stack pointer needs to be kept aligned to 16 bytes. 堆栈指针需要保持与16个字节对齐。 On my machine (macos), it SEGVs under printBin if you don't. 在我的机器上(macos),如果没有,它会在printBin下显示SEGV。

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

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