c - _malloc 在汇编中到底做了什么?

标签 c assembly x86 reverse-engineering

public main
main proc near
push    ebp
mov     ebp, esp
and     esp, 0FFFFFFF0h
sub     esp, 30h
mov     dword ptr [esp], 8 ; size
call    _malloc
mov     [esp+2Ch], eax
mov     dword ptr [esp+4], 4
mov     eax, [esp+2Ch]
mov     [esp], eax
call    __start

上面的代码代表了我正在处理的一个大型项目的一部分。我试图将此代码转换为 C 等效代码,但我很难理解 malloc 的工作原理。

我认为 8 个字节是分配的内存大小;但是,我不确定这条线。

mov      eax, [esp+2ch] 

malloc 对 eax 做了什么?

此外,这会是等效的 C 代码吗?

int main(void)
{
int *ptr1;
ptr1 = (int *)malloc(sizeof(8));
*ptr1 = 4;
__start(*ptr1);

最佳答案

函数 malloc() 将分配一个大小为 size 字节的内存块。如果可以分配请求的内存,则返回指向内存块开头的指针。

注意:接收到的内存块内容没有初始化

ma​​lloc() 的语法:

void *malloc ( size_t size );

参数:

内存块的大小(以字节为单位)。

返回值:

如果请求成功,则返回指向内存块的指针。 如果函数未能分配请求的内存块,则返回 NULL,成功调用大小为零的 malloc() 也可能返回 NULL。

this CS 301 lecture by Dr. Lawlor 中所述:

Calling Malloc from Assembly Language

It's a pretty straightforward function: pass the number of BYTES you want as the only parameter, in rdi. "call malloc." You'll get back a pointer to the allocated bytes returned in rax. To clean up the space afterwards, copy the pointer over to rdi, and "call free" (I'm leaving off the free below, because you need the stack to do that properly).

Here's a complete example of assembly memory access. I call malloc to get 40 bytes of space. malloc returns the starting address of this space in rax (the 64-bit version of eax). That is, the rax register is acting like a pointer. I can then read and write from the pointed-to memory using the usual assembly bracket syntax:

mov edi, 40; malloc's first (and only) parameter: number of bytes to allocate
extern malloc
call malloc
; on return, rax points to our newly-allocated memory
mov ecx,7; set up a constant
mov [rax],ecx; write it into memory
mov edx,[rax]; read it back from memory
mov eax,edx; copy into return value register
ret

Rather than copy via the ecx register, you can specify you want a 32-bit memory write and read using "DWORD" in front of the brackets, like this:

mov edi, 40; malloc's first (and only) parameter: number of bytes to allocate
extern malloc
call malloc
; on return, rax points to our newly-allocated memory
mov DWORD [rax],7; write constant into memory
mov eax,DWORD [rax]; read it back from memory
ret

对于汇编语言中的 malloc...请参阅此链接 malloc

关于c - _malloc 在汇编中到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510132/

相关文章:

assembly - UEFI 是如何工作的?

assembly - 如何获取 VESA BIOS 信息

c - 关闭窗口按钮上的 gtk_widget_set_sensitive

c - 函数指针声明语法困惑

MacBook Pro、Windows XP、VS 2008 Express Edition 上原始 C 程序的损坏行为

c - 协助使用C代码和汇编代码绘制堆栈

assembly - x86 函数必须保留哪些寄存器?

c - 全局 IPv6 地址无法在 Solaris 上绑定(bind)

c - 如何将文件重定向到 C 中的 gets()

assembly - MIPS加载字的使用方法