Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nasm - access struct elements by value and by address

I started to code in NASM assembly lately and my problem is that I don't know how I access struct elements the right way. I already searched for solutions on this site and on google but everywhere I look people say different things. My program is crashing and I have the feeling the problem lies in accessing the structs.

When looking at the example code:

STRUC Test
    .normalValue RESD 1
    .address RESD 1
ENDSTRUC

TestStruct:    
    istruc Test
        at Test.normalValue dd ffff0000h
        at Test.address dd 01234567h
    iend

;Example:
mov eax, TestStruct ; moves pointer to first element to eax

mov eax, [TestStruct] ; moves content of the dereferenced pointer to eax (same as mov eax, ffff0000h)

mov eax, TestStruct
add eax, 4
mov ebx, eax ; moves pointer to the second element (4 because RESD 1)

mov eax, [TestStruct+4] ; moves content of the dereferenced pointer to eax (same as mov eax, 01234567h)

mov ebx, [eax] ; moves content at the address 01234567h to ebx

Is that right?

Help is appreciated

like image 672
Troll Sama bin Laden Avatar asked Feb 25 '26 20:02

Troll Sama bin Laden


1 Answers

I dont know if you figured out but here is our code with some little modification that works. All instructions are correct except the last one mov ebx, [eax] which is expected caus you are trying to access content at address 0x1234567 resulting in SIGSEGV

section .bss
  struc Test
    normalValue RESD 1
    address RESD 1
  endstruc

section .data
  TestStruct:
    istruc Test
      at normalValue, dd 0xffff0000
      at address, dd 0x01234567
    iend

section .text
  global _start

_start:

  mov eax, TestStruct ; moves pointer to first element to eax
  mov eax, [TestStruct] ; moves content of the dereferenced pointer to eax same as mov eax, ffff0000h
  mov eax, TestStruct
  add eax, 4
  mov ebx, eax ; moves pointer to the second element 4 because RESD 1
  mov eax, [TestStruct+4] ; moves content of the dereferenced pointer to eax same as mov eax, 01234567h
  mov ebx, [eax] ; moves content at the address 01234567h to ebx

Compile, link and run step by step with nasm -f elf64 main.nasm -o main.o; ld main.o -o main; gdb main

like image 174
vx3r Avatar answered Feb 28 '26 11:02

vx3r