Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 932
mudge Avatar asked May 06 '10 14:05

mudge


People also ask

How is memory allocated in assembly?

The sys_brk() system call is provided by the kernel, to allocate memory without the need of moving it later. This call allocates memory right behind the application image in the memory. This system function allows you to set the highest available address in the data section.

How is dynamic memory management performed in Linux?

Dynamic memory is allocated by either the malloc() or calloc() functions. These functions return pointers to the allocated memory. Once you have a block of memory of a certain initial size, you can change its size with the realloc() function. Dynamic memory is released with the free() function.

How do I dynamically allocate memory?

To allocate memory dynamically, library functions are malloc() , calloc() , realloc() and free() are used. These functions are defined in the <stdlib. h> header file.

How does Linux allocate memory?

Linux-based operating systems use a virtual memory system. Any address referenced by a user-space application must be translated into a physical address. This is achieved through a combination of page tables and address translation hardware in the underlying computer system.


1 Answers

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 
like image 101
Flexo Avatar answered Oct 03 '22 04:10

Flexo