Pregunta

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()?

¿Fue útil?

Solución

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.

Otros consejos

Source:

#include <unistd.h>
#define SOME_NUMBER  8
int main() {
  void *ptr = sbrk(8);
  return 0;
}

Compile using with Assembly Output option

gcc -S -o test.S test.c

Then look at the ASM code

_main:
Leh_func_begin1:
    pushq   %rbp
Ltmp0:
    movq    %rsp, %rbp
Ltmp1:
    subq    $16, %rsp
Ltmp2:
    movl    $8, %eax
    movl    %eax, %edi
    callq   _sbrk
    movq    %rax, -16(%rbp)
    movl    $0, -8(%rbp)
    movl    -8(%rbp), %eax
    movl    %eax, -4(%rbp)
    movl    -4(%rbp), %eax
    addq    $16, %rsp
    popq    %rbp
    ret
Leh_func_end1:

There is no system call for it but you should be able to still make the call

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top