11

我看过关于同样错误的帖子,但我仍然收到错误:

 too many memory references for `mov'
 junk `hCPUIDmov buffer' after expression

...这是代码(mingw编译器/ C::B):


    #include iostream

    using namespace std;

    union aregister
    {
        int theint;
        unsigned bits[32];
    };

    union tonibbles
    {
        int integer;
        short parts[2];
    };

    void GetSerial()
    {
        int part1,part2,part3;
        aregister issupported;
        int buffer;

        __asm(
            "mov %eax, 01h"
            "CPUID"
            "mov buffer, edx"
        );//do the cpuid, move the edx (feature set register) to "buffer"


        issupported.theint = buffer;
        if(issupported.bits[18])//it is supported
        {
            __asm(
                "mov part1, eax"
                "mov %eax, 03h"
                "CPUID"
            );//move the first part into "part1" and call cpuid with the next subfunction to get
            //the next 64 bits

            __asm(
                "mov part2, edx"
                "mov part3, ecx"
            );//now we have all the 96 bits of the serial number


            tonibbles serial[3];//to split it up into two nibbles

            serial[0].integer = part1;//first part
            serial[1].integer = part2;//second
            serial[2].integer = part3;//third
        }
    }

4

2 回答 2

16

您的汇编代码格式不适合 gcc。

首先,gcc 使用 AT&T 语法(编辑:默认情况下,感谢 nrz),因此它需要%为每个寄存器引用添加一个$,为立即操作数添加一个。目标操作数始终在右侧

其次,您需要为\n\t新行传递行分隔符(例如 )。由于 gcc 将您的字符串直接传递给汇编器,因此它需要特定的语法。

您通常应该尽量减少您的汇编程序,因为它可能会导致优化器出现问题。最小化所需汇编程序的最简单方法可能是将 cpuid 指令分解为一个函数,然后重用它。

void cpuid(int32_t *peax, int32_t *pebx, int32_t *pecx, int32_t *pedx)
{
    __asm(
         "CPUID"
          /* All outputs (eax, ebx, ecx, edx) */
        : "=a"(*peax), "=b"(*pebx), "=c"(*pecx), "=d"(*pedx)   
          /* All inputs (eax) */
        : "a"(*peax)                                           
    );
}

然后只需调用 using;

int a=1, b, c, d;

cpuid(&a, &b, &c, &d);

另一种可能更优雅的方法是使用宏来完成

于 2013-02-23T00:22:30.610 回答
6
  1. 由于 C 的工作方式,

    __asm(
        "mov %eax, 01h"
        "CPUID"
        "mov buffer, edx"
    );
    

    相当于

    __asm("mov %eax, 01h" "CPUID" "mov buffer, edx");
    

    这相当于

    __asm("mov %eax, 01hCPUIDmov buffer, edx");
    

    这不是你想要的。

  2. AT&T 语法(GAS 的默认)将目标寄存器放在末尾。

  3. AT&T 语法要求立即数以 $ 为前缀。

  4. 你不能像那样引用局部变量;您需要将它们作为操作数传递。

维基百科的文章给出了一个返回 eax 的工作示例。

以下代码段可能涵盖了您的用例(我对 GCC 内联汇编或 CPUID 并不十分熟悉):

int eax, ebx, ecx, edx;
eax = 1;
__asm( "cpuid"
     : "+a" (eax), "+b" (ebx), "+c" (ecx), "+d" (edx));
buffer = edx
于 2013-02-23T00:35:04.117 回答