2

Is it possible to access directly struct fields within an assembly function? And how can I access via assembly an global variable?

In inline assembly on intel syntax I can do this:

 struct str
 {
   int a;
   int b;
 }
 int someGlobalVar;

 __declspec(naked)   void __fastcall func(str * r)
 {
    __asm
    {
       mov dword ptr [ecx].a, 2
       mov dword ptr [ecx].b,someGlobalVar
    }
}

How do I do this in a assembly x64 function (not inline), with ATT syntax (gcc), if it's not possible how do I do this in an inline function?

4

1 回答 1

3

对于任何许多类似的问题,最简单的解决方案是用 C 编写一个执行您想要的示例,然后使用gcc -m64 -S ...它生成汇编源代码,然后将该源代码用作您自己的汇编代码的模板。

考虑以下示例:

#include <stdio.h>

typedef struct
{
    int a;
    int b;
} S;

int foo(const S *s)
{
    int c = s->a + s->b;

    return c;
}

int main(void)
{
    S s = { 2, 2 };

    printf("foo(%d, %d) = %d\n", s.a, s.b, foo(&s));

    return 0;
}

如果我们使用生成 asm,gcc -Wall -O1 -m64 -S foo.c -o foo.S我们会得到以下“foo”函数:

.globl _foo
_foo:
LFB3:
    pushq   %rbp
LCFI0:
    movq    %rsp, %rbp
LCFI1:
    movl    (%rdi), %eax
    addl    4(%rdi), %eax
    leave
    ret

可以看到,movl (%rdi), %eax获取struct的元素a,然后addl 4(%rdi), %eax添加元素b,函数结果在%eax.

于 2011-02-07T13:09:34.553 回答