Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acessing struct fields within an assembly X64 function

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?

like image 460
DVD Avatar asked Feb 11 '26 20:02

DVD


1 Answers

For this any many similar problems, the easiest solution is to write an example in C that does what you want, then use gcc -m64 -S ... to generate assembler source, and then use that source as a template for your own assembly code.

Consider the following example:

#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;
}

If we generate asm using gcc -Wall -O1 -m64 -S foo.c -o foo.S we get the following for the "foo" function:

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

As you can see, movl (%rdi), %eax gets the element a of the struct, and then addl 4(%rdi), %eax adds element b, and the function result is returned in %eax.

like image 119
Paul R Avatar answered Feb 14 '26 08:02

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!