将各种参数从C传递给汇编程序

时间:2014-06-21 11:39:17

标签: c assembly parameters parameter-passing nasm

我必须编写一个汇编程序子程序dswap(int, double*, int, double*, int),它由C程序调用并由NASM汇编。我的任务是根据其他三个int参数操纵两个给定的向量(double *)。现在我很难知道我的汇编程序代码中如何访问这些参数以及如何从向量访问特定元素。你能指点我一些文件/例子吗?

2 个答案:

答案 0 :(得分:0)

您希望查看"堆叠帧",如果您使用的是x86,请查看微编码指令"输入"并且"离开"做,但不要使用它们。相反,使用编码输出等效项来设置堆栈帧,以便您可以访问自己的传递参数。

考虑到,在C中,参数处理已完成,您可以将许多参数传递给函数/子例程,但只能返回一个参数。

答案 1 :(得分:0)

我做了一个小调查,结果发现MinGW gcc生成符合COFF的目标文件。至于nasm - 有一个命令行 - -f coff,你可以使用它来强制它产生COFF格式的目标文件。接下来,它在定义程序的形式上受到很大限制。在汇编列表中,在编写实际函数之前,不要忘记指定SEGMENT _text。必须以某种方式定义该函数:

SEGMENT _text
global _dswap ;; underscore here is important - it's cdecl style.
_dswap:
push ebp ;; look below
mov ebp, esp ;; cdecl function prologue. Entering stack frame.
sub esp, 20h ;; This is for your local variables if needed.
;;do your work here. Use ebp as the origin for parameters. The very first passed parameter to the stack is ebp + 8(ebp + 4 is a return address).
;;
add esp, 20h ;; if you performed your local variables allocation. You can access them with mov eax, [esp + 10] for instance. But I recommend you to speci fy constants with EQU macro to make the code more readable. From your signature I see that you pass pointers to doubles. They reside on the regular stack. You have to pop them to floating point stack within this function before you can do something with these variables.
pop ebp ;; Leaving stack frame
ret ;; cdecl assumes that the caller shall clean parameters.

在您的c文件中,您只需声明原型而不使用任何extern关键字。默认情况下,函数原型是extern。

您是否打算通过使用此功能交换两个双向量?

作为提示 - 打开msys MinGW控制台(您必须先安装它的每个组件),输入以下test.c文件:

double foo(double lhl, double rhl)
{
    return lhl + rhl;
}

main()
{
    foo(4.5, 2.7);
    return 0;
}

使用gcc -c test.c编译它 接下来,您将看到test.o文件。现在是时候研究这些东西是如何运作的了。您需要具有转储仓实用程序或任何其他反汇编实用程序:

dumpbin /disasm:nobytes test.o > listing.asm

但我建议你阅读http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl