سؤال

I'm trying to write an assembly function that allocates memory and stores the address in a given pointer. However, I cannot figure out how to store the address in the parameter passed to the function.

I have the following:

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

Any ideas?

هل كانت مفيدة؟

المحلول

You can't store the new pointer in ReAllocate_Memory since you don't have the address of it within that routine.

Either

  • modify that routine to take a pointer to the variable (get and pass the address with lea eax, SockArray; push eax or similar) and then load the parameter and store to it with e.g. mov edx, [ebp + 0x10] then mov [edx], eax.

or else, and this is way easier:

  • don't attempt to store the new pointer in ReAllocate_Memory. Since it is returned in eax you can simply store it in the calling scope, same as you do after the malloc call.

Aside: loading edx with a value and then calling a function (free) is dangerous: sub-routines are not required to preserve the value of edx. Better not to load that until after free returns, even if it happens to currently work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top