[英]x86-64 Linux NASM. Function parameter passing of type int array declared as a function in C++ file
我尝试使用这个建议来解决这个问题
对于Linux编程arr [],n,&a,&b在RDI,RSI,RDX和RCX中传递。
并且程序的输出不会正确地汇总数组中的整数。 它输出了一个很明显错误的数字。
下面找到的两个文件是从这里找到的原始32位版本修改的。 http://mcs.uwsuper.edu/sb/224/Intro/c_asm.html
我想要的是编译一个程序集文件,该文件在名为array.cpp
的C ++文件中调用函数参数,然后将生成的目标文件array.o
与g++
。
我遇到的问题与将正确的寄存器传递到堆栈或者为rsi
寄存器上的每个偏移量添加的字节数有关(我使用8,因为每个堆栈元素是64位)。
也可能是rbp
寄存器没有正确加载到数组地址的正确偏移量和数组 中元素的数量 。
mov rcx, [rbp+24] ; array length
mov rsi, [rbp+16] ; array address
无论如何,这是array.cpp
文件,下面是nasm文件,我称之为nasm_cpp.asm
。
他们编译,链接和运行
nasm -f elf64 nasm_cpp.asm -o array.o
g++ -m64 array.cpp array.o
./a.out
#include <iostream>
using namespace std;
extern "C" int array(int a[], int length); // external ASM procedure
int main()
{
int a[] = { 10, 10}; // array declaration
int array_length = 2; // length of the array
int sum = array(a, array_length); // call of the ASM procedure
cout << "sum=" << sum << endl; // displaying the sum
}
这是下面的nasm_cpp.asm
;nasm -f elf64 nasm_cpp.asm -o array.o
;g++ -m64 array.cpp array.o
;./a.out
global array ; required for linker and NASM
section .text ; start of the "CODE segment"
array: push rbp
mov rbp, rsp ; set up the rBP
push rcx ; save used registers
push rdi
push rsi
mov rcx, [rbp+24] ; array length
mov rsi, [rbp+16] ; array address
xor rax, rax ; clear the sum value
lp: add rax, [rsi] ; fetch an array element
add rsi, 8 ; move to another element
loop lp ; loop over all elements
pop rsi ; restore used registers
pop rdi
pop rcx
pop rbp
ret ; return to caller
我按照问题下面的评论中的建议进行了操作,现在可以使用,cpp文件与上面相同。
;nasm -f elf64 nasm_cpp.asm -o array.o
;g++ -m64 array.cpp array.o
;./a.out
global array ; required for linker and NASM
section .text ; start of the "CODE segment"
array:
push rbp
mov rbp, rsp ; set up the rBP
mov rcx, rsi ; array length
mov rsi, rdi ; array address
xor rax, rax ; clear the sum value
lp: add eax, [rsi] ; fetch an array element
add rsi, 4 ; move to another element
loop lp ; loop over all elements
pop rbp
ret ; return to caller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.