How to convert Intel Assembly C to AT&T C++

333 Views Asked by At

I trying to convert function "__cpuid" from С language to C++. I have a problem that the g++ compiler does not work with Intel assembler.

I'm trying to translate this code:

__asm
    {
        mov    esi, CPUInfo
        mov    eax, InfoType
        xor ecx, ecx
        cpuid
        mov    dword ptr[esi + 0], eax
        mov    dword ptr[esi + 4], ebx
        mov    dword ptr[esi + 8], ecx
        mov    dword ptr[esi + 12], edx
    }

I tried to do it using examples from the Internet, I got this code, but it doesn't work:

__asm
    (


            "movl   %CPUInfo,%esi\n"
            "movl   %InfoType,%eax\n"
            "xorl   %ecx,%ecx\n"
            "cpuid\n"
            "movl   %eax,0(%esi)\n"
            "movl   %ebx,4(%esi))\n"
            "movl   %ecx,8(%esi)\n"
            "movl   %edx,12(%esi)\n"
             :"=r"(CPUInfo)
 

    );
2

There are 2 best solutions below

2
Lakshay Rohila On

On linux (and in many other platforms, non-linux, non-gcc), you can assemble the intel assembly code into an object file with assembler such as nasm. Then you can link your assembly object into the application without need of mixing messages or assembly language syntax.

2
xiver77 On
void cpuid(int InfoType, int *CPUInfo) {
  int a = InfoType;
  int c = 0;
  int b, d;
  __asm__ (
    "cpuid"
    : "+a"(a), "=b"(b), "+c"(c), "=d"(d)
  );
  CPUInfo[0] = a;
  CPUInfo[1] = b;
  CPUInfo[2] = c;
  CPUInfo[3] = d;
}

a, b, c, and d each binds to eax, ebx, ecx, and edx register. The GCC docs explains how this works in detail.