FASM通过引用/指针传递

时间:2014-04-20 18:21:15

标签: assembly fasm

我试图编写一个汇编函数来分配内存并将地址存储在给定的指针中。但是,我无法弄清楚如何将地址存储在传递给函数的参数中。

我有以下内容:

struc SSLSocket sock, ssl, ctx, address, port, connected, type
{
   .sock dd sock
   .ssl dd ssl
   .ctx dd ctx
   .address dd address
   .port dw port
   .connected db connected
   .type dd type
}

SockArray dd 0  //will allocate 5 of the above struct on the heap and store it in this pointer.

section '.code' code readable executable
main:
   push ebp
   mov ebp,esp


   ;push 5
   ;call [malloc]
   ;add esp, 0x04
   ;mov [SockArray], eax

   push SockArray   ;pointer that will hold allocated memory
   push 23         ;size of struct
   call ReAllocate_Memory
   add esp, 0x08

   push [SockArray] //print address of allocated memory.
   push PrintPtr
   call [printf]
   add esp, 0x08


   mov esp, ebp
   pop ebx

   call [getchar]

   mov eax, 0x00
ret

ReAllocate_Memory:
   push ebp
   mov ebp, esp

   mov eax, [ebp + 0x0C]      ;Pointer that will hold address of allocation
   mov edx, [ebp + 0x08]      ;Size to allocate in bytes

   push eax
   call [free]                ;Free any allocated memory
   add esp, 0x04

   push edx
   call [malloc]              ;Allocate n-size bytes
   add esp, 0x04

   ;mov address into parameter pointer ([ebp + 0x0C]).

   mov esp, ebp
   pop ebp
ret

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您无法将新指针存储在ReAllocate_Memory中,因为您没有在该例行程序中拥有该指针的地址。

要么

  • 修改该例程以获取指向变量的指针(使用lea eax, SockArray; push eax或类似物获取并传递地址)然后加载参数并将其存储到例如mov edx, [ebp + 0x10]然后mov [edx], eax

或者,这更容易:

  • 不要尝试将新指针存储在ReAllocate_Memory中。由于它是在eax中返回的,因此您只需将其存储在调用范围内,就像在malloc调用之后一样。

除此之外:使用值加载edx然后调用函数(free)是危险的:子例程不需要保留edx的值。最好不要在free返回之前加载,即使它恰好在当前工作。

相关问题