How to Dynamically Allocate Memory Using Assembly and System Calls Under Linux

柔情痞子 提交于 2019-12-03 05:44:01

问题


I'm looking for some good code examples of dynamic memory allocation using an assembly language under Linux and using system calls, not malloc and friends.

What are some of the simplest but effective ways to do this?

On Intel 386+ computers.


回答1:


brk(2). And take a look at ELF.




回答2:


On Linux mmap2 is a sensible system call to use for this at a low level. It takes 6 arguments, so in IA32 you can call it using:

    mov eax, 192    ; mmap2
    xor ebx, ebx    ; addr = NULL
    mov ecx, 4096   ; len = 4096
    mov edx, $7     ; prot = PROT_READ|PROT_WRITE|PROT_EXEC
    mov esi, $22    ; flags = MAP_PRIVATE|MAP_ANONYMOUS
    mov edi, -1     ; fd = -1
    xor ebp, ebp    ; offset = 0 (4096*0)
    int $80         ; make call

(See the relevant kernel source for details on the parameter passing)

I built this with NASM and verified it worked using strace, which produced:

mmap2(NULL, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xf77ae000



回答3:


An alternative to brk() is to use the mmap() system call, with MAP_ANONYMOUS | MAP_PRIVATE.




回答4:


Use the brk system call to change the end of your data segment.

Take a look here: http://www.linuxjournal.com/article/6390 to understand what you're doing.



来源:https://stackoverflow.com/questions/2782010/how-to-dynamically-allocate-memory-using-assembly-and-system-calls-under-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!