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

问题描述 投票:1回答:1

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

在64位模式下,指令的默认操作大小为32位。使用REX.B形式的REX前缀允许访问其他寄存器(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前缀?

提前致谢。


在下面的代码中,outputbyte[],长度为sizesafety是一个故障保险。两个不同的字大小处理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'
c gcc x86 inline-assembly rdrand
1个回答
1
投票

您不需要操作数大小的后缀,只需使用适当大小的寄存器(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
© www.soinside.com 2019 - 2024. All rights reserved.