gpt4 book ai didi

c - 在 GCC 下使用 RDRAND 时如何设置 REX 前缀?

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:31 25 4
gpt4 key购买 nike

我正在尝试使用 Intel 的 RDRAND 指令。根据Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 2 (第 4-298 页),RDRAND 默认生成 32 位随机值,即使在 64 位机器上也是如此:

In 64-bit mode, the instruction's default operation size is 32 bits. Using a REX prefix in the form of REX.B permits access to additional registers (R8-R15).

我正在尝试使用 rdrandq 强制生成 64 位,但它产生了一个错误(/tmp/ccLxwW6S.s 是由于使用了内联装配):

$ g++ -Wall rdrand.cxx -o rdrand.exe
/tmp/ccLxwW6S.s: Assembler messages:
/tmp/ccLxwW6S.s:5141: Error: invalid instruction suffix for `rdrand'

如何在 GCC 下强制使用 64 位版本的 RDRAND 指令?在 GCC 下使用 RDRAND 时如何设置 REX 前缀?

提前致谢。


在下面的代码中,output 是一个长度为sizebyte[]safety 是一种故障保护。两种不同的字长处理 X86, X32, and X64 platforms .

#if BOOL_X86
word32 val;
#else // X32 and X64
word64 val;
#endif

while (size && safety)
{
char rc;
__asm__ volatile(
#if BOOL_X86
"rdrandl %0 ; setc %1"
#else
"rdrandq %0 ; setc %1"
#endif
: "=rm" (val), "=qm" (rc)
:
: "cc"
);

if (rc)
{
size_t count = (size < sizeof(val) ? size : sizeof(val));
memcpy(output, &val, count);
size =- count;
}
else
{
safety--;
}
}

如果我从 RDRAND 中删除显式操作数大小(即使用 rdrand 而不是 rdrandlrdrandq),那么我会得到一个错误尝试使用 word64 时:

/tmp/ccbeXOvM.s: Assembler messages:
/tmp/ccbeXOvM.s:5167: Error: operand size mismatch for `rdrand'

最佳答案

您不需要操作数大小的后缀,只需将它与适当大小的寄存器一起使用(gcc 将根据您使用的 C 变量的类型来选择)。


gcc main.c -o main

(或)

gcc -m32 main.c -o main

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
unsigned int rnd32;
#ifdef __x86_64
long long unsigned int rnd64;
/*
The next instruction generates this asm:
48 0f c7 f0 rdrand %rax
*/
asm volatile("rdrand %0\n":"=r"(rnd64):);
printf("\nRND64=0x%llx\n",rnd64);
#endif
/*
The next instruction generates this asm:
0f c7 f1 rdrand %ecx
*/
asm volatile("rdrand %0\n":"=r"(rnd32):);
printf("RND32=0x%x\n",rnd32);
printf("\nAssembler code:\n\n");
system("objdump -d main|grep rdrand");
return 0;
}

https://repl.it/@zibri/rdrand

输出(64 位):

RND64=0x2f9f0e7d7f209575
RND32=0xbec8ff00

Assembler code:

40054f: 48 0f c7 f0 rdrand %rax
400557: 0f c7 f1 rdrand %ecx

输出(32 位):

RND32=0xa3d33766

Assembler code:

59a: 0f c7 f0 rdrand %eax

关于c - 在 GCC 下使用 RDRAND 时如何设置 REX 前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33075694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com