Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux sbrk() as a syscall in assembly

So, as a challenge, and for performance, I'm writing a simple server in assembly. The only way I know of is via system calls. (through int 0x80) Obviously, I'm going to need more memory than allocated at assemble, or at load, so I read up and decided I wanted to use sbrk(), mainly because I don't understand mmap() :p

At any rate, Linux provides no interrupt for sbrk(), only brk().

So... how do I find the current program break to use brk()? I thought about using getrlimit(), but I don't know how to get a resource (the process id I'd guess) to pass to getrlimit(). Or should I find some other way to implement sbrk()?

like image 779
Jon Weldon Avatar asked Oct 09 '22 00:10

Jon Weldon


1 Answers

The sbrk function can be implemented by getting the current value and subtracting the desired amount manually. Some systems allow you to get the current value with brk(0), others keep track of it in a variable [which is initialized with the address of _end, which is set up by the linker to point to the initial break value].

This is a very platform-specific thing, so YMMV.

EDIT: On linux:

However, the actual Linux system call returns the new program break on success. On failure, the system call returns the current break. The glibc wrapper function does some work (i.e., checks whether the new break is less than addr) to provide the 0 and -1 return values described above.

So from assembly, you can call it with an absurd value like 0 or -1 to get the current value.

Be aware that you cannot "free" memory allocated via brk - you may want to just link in a malloc function written in C. Calling C functions from assembly isn't hard.

like image 84
Random832 Avatar answered Oct 12 '22 20:10

Random832