我正在学习x86-64汇编,我找到了一本书《现代X86汇编语言编程:涵盖X86 64位,AVX,AVX2和AVX-512》,但它使用的是MASM和Visual C++,而我使用的是Linux。所以我试图将其中的一些程序转换为NASM语法,但是我遇到了一个问题,就是将计算结果存储在传递给函数的指针中。C++代码是
#include <iostream>
#include <iomanip>
#include <bitset>
using namespace std;
extern "C" int IntegerShift_(unsigned int a, unsigned int count, unsigned int* a_shl, unsigned int* a_shr);
static void PrintResult(const char* s, int rc, unsigned int a, unsigned int count, unsigned int a_shl, unsigned int a_shr)
{
bitset<32> a_bs(a);
bitset<32> a_shr_bs(a_shl);
bitset<32> a_shl_bs(a_shr);
const int w = 10;
const char nl = '\n';
cout << s << nl;
cout << "count = " << setw(w) << count << nl;
cout << "a = " << setw(w) << a << " (0b" << a_bs << ")" << nl;
if (rc == 0)
cout << "Invalid shift count" << nl;
else
{
cout << "shl = " << setw(w) << a_shl << " (0b" << a_shl_bs << ")" << nl;
cout << "shr = " << setw(w) << a_shr << " (0b" << a_shr_bs << ")" << nl;
}
cout << nl;
}
int main()
{
int rc;
unsigned int a, count, a_shl, a_shr;
a = 3119;
count = 6;
rc = IntegerShift_(a, count, &a_shl, &a_shr);
PrintResult("Test 1", rc, a, count, a_shl, a_shr);
return 0;
}
这段代码测试函数IntegerShift_,它是用汇编编写的。(在main函数中还有一些测试,我没有在这里包括,因为它们基本上与我所包括的测试相同)。书中最初的汇编代码是MASM代码:
.code
IntegerShift_ proc
xor eax,eax
cmp edx,31
ja InvalidCount
xchg ecx,edx
mov eax,edx
shl eax,cl
mov [r8],eax
shr edx,cl
mov [r9],edx
mov eax,1
InvalidCount:
ret
IntegerShift_ endp
end
将其翻译成NASM代码的明显方法(至少从我所知的情况来看)如下:
section .text
global IntegerShift_
IntegerShift_:
xor eax,eax
cmp esi,31
ja InvalidCount
xchg ecx,esi
mov eax,esi
shl eax,cl
mov [rdx],eax
shr esi,cl
mov [rsi],esi
mov eax,1
InvalidCount:
ret
但是,汇编,编译和运行此程序时,必须使用:
nasm -f elf64 [asm filename]
g++ -Wall -no-pie [object file filename] [cpp filename] -o prog
./prog
导致分段错误。我试着用我能想到的各种方法解决这个问题,花了几个多小时,但是我不能让它工作。我几乎可以肯定,问题出在我试图将结果存储在a_shl和a_shr指针地址中的方式上,但是我不明白我做错了什么,我将非常感谢您的帮助。提前谢谢!
null
https://en.wikipedia.org/wiki/x86_calling_conventions
其次,虽然大多数情况下可以使用32位寄存器,但必须将地址视为其完整的64位值。
最后,您还需要修改
经过这些修改:
;extern "C" int IntegerShift_(unsigned int a, unsigned int count, unsigned int* a_shl, unsigned int* a_shr);
; RDI, RSI, RDX, RCX,
section .text
global IntegerShift_
IntegerShift_:
xor eax,eax
cmp esi,31
ja InvalidCount
xchg rcx,rsi ; Need full 64-bit exchange
mov eax,edi ; (r)di is the 'a' value
shl eax,cl
mov [rdx],eax
shr edi,cl
mov [rsi],edi
mov eax,1
InvalidCount:
ret
你能一步完成密码吗?在这种情况下,您应该能够找到它分段故障的位置。
另一种方法是用C编写代码并查看反汇编清单。如果代码在C语言中工作,您可以使用汇编代码并根据您的喜好对其进行优化。你试过吗?
还有,你看过这篇文章吗?http://left404.com/2011/01/04/converting-x86-assembly-from-MASM-to-NASM-3