sbrk vs mmap
ssouhlal at FreeBSD.org
Fri Jan 12 06:47:46 UTC 2007
darran kartaschew wrote:
> Hi Guys,
> I'm having some issues with rewriting a simple malloc() function to be
> with FreeBSD (AMD64). This is part of porting an application from
> to FreeBSD.
> After pulling my hair out for a while, I've found that the sbrk()
> system call just returns "45 - Operation Not Supported" error,
> irrespective of the parameters passed to it. (I've found the source
> for sbrk() and see that it's not implemented).
> So I decided to try using mmap() instead. All memory allocations don't
> have to be continuous, so mmap() will suffice. The problem is I'm
> getting an invalid file handle error? According to the man page, if
> use MAP_ANON you're just allocating a block of memory without linking
> to a file, and a handle of -1 should be supplied... Any way code is as
> mov r4, 0 ; don't care where the memory is allocated
> mov r5, 1048576 ; alloc 1MB
> mov r3, 3 ; RW access to memory
> mov r2, 4096 ; MAP_ANON - not a file
> mov r8d, -1 ; -1 for file handle if using MAP_ANON
> mov r9, 0 ; ignored for MAP_ANON
> mov r0, 197 ; mmap();
> mov qword [_mmap], r0 ; save address so we can release it on exit;
> It fails with an EBADF (9) ; Bad File Descriptor error...
> Note: r0 = rax, r1 = rbx, r2 = rcx, r3 = rdx, r4 = rdi, r5 = rsi, r6 =
> rbp, r7 = rsp. Various parameters for mmap() are found in mman.h>.
> So does anyone have an example of a working call to mmap() or tell me
> what's wrong with the above code?
> I've done up a test C program that simple calls mmap(), after
> tracing through the compiled C program using gdb I can't see that
> I'm doing anything different to what gcc/glibc are doing? (except
> the macro expansion that's in libc which adds an additional
> 0 to the top of the stack).
> PS. FASM 1.66 running on FreeBSD 6.1 (AMD64).
> PPS. This is NOT a homework assignment! (tm) :P
I think you are missing a parameter.
mmap (as well as pwrite, lseek, truncate and ftruncate), has a "hidden"
parameter just before the offset that is ignored, due to a bug in ancient
GCC versions. So, basically, you should also push a 0 on the stack.
Take a look at src/sys/libc/sys/mmap.c .
I have a patch to remove this useless argument, but haven't committed it
More information about the freebsd-hackers