【问题标题】:Nasm - access struct elements by value and by addressNasm - 按值和地址访问结构元素
【发布时间】:2019-08-18 00:08:19
【问题描述】:

我最近开始在 NASM 程序集中编写代码,但我的问题是我不知道如何以正确的方式访问 struct 元素。我已经在这个网站和谷歌上搜索过解决方案,但我看到的每个地方人们都说不同的话。我的程序崩溃了,我感觉问题在于访问结构。

查看示例代码时:

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

是吗?

感谢您的帮助

【问题讨论】:

  • 对我来说似乎是正确的
  • 嗯,好吧...我以为我已经大致找出了导致这次崩溃的原因。好像我没有。无论如何谢谢..
  • 您可以向我们展示不工作的实际代码。
  • mov eax, TestStruct / add eax, 4 工作但毫无意义地缓慢。使用mov eax, TestStruct + 4 在组装+链接时进行添加。当所有输入都是汇编时常量时,通常避免运行时数学;没有编译器可以为您进行持续传播。当然,你也可以使用mov ebx, TestStruct / mov eax, [ebx + 4] 来假装你有一个运行时变量指针。

标签: pointers assembly struct x86 nasm


【解决方案1】:

我不知道你是否发现,但这是我们的代码,经过一些小的修改,可以正常工作。除了最后一条mov ebx, [eax] 之外,所有指令都是正确的,这是预期的,因为您试图访问地址0x1234567 的内容导致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

使用nasm -f elf64 main.nasm -o main.o; ld main.o -o main; gdb main一步一步编译、链接和运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多