Subject: Re: GCC3.3.1 switch coming soon.
To: Andrew Brown <atatat@atatdot.net>
From: Bang Jun-Young <junyoung@NetBSD.org>
List: tech-kern
Date: 09/27/2003 05:51:37
On Wed, Sep 24, 2003 at 11:04:36AM -0400, Andrew Brown wrote:
> it's also perhaps worth mentioning that freebsd has a MAP_STACK flag
> to mmap() that, if i correctly has the effects that:
> 
> * "addr" is the "stack top", as is the return address, meaning that if
> you write to addr, you'll fault (unless there's something already
> there), but that you can walk backwards "size".
> 
> * the region is expected to grow backwards from top to bottom (ie, you
> decrement your "stack pointer" and push values in when using it).
> 
> to put this another way:
> 
> 	void *a, *b;
> 	a = mmap(0x40000000, 4096, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0);
> 	b = mmap(0x40000000, 4096, PROT_READ|PROT_WRITE, MAP_STACK, -1, 0);
> 
> with both succeed and return 0x40000000.  the first call causes the
> page at 0x40000000 to be allocated and the second call causes the page
> *prior* to 0x40000000 to be allocated.  note that i'm basing this on
> skimming the code and the man page, not on actual experience.

Actually, the allocated stack lies between 0x40000000 - 0x40001000,
not 0x3FFFF000 - 0x40000000.

#include <sys/types.h>
#include <sys/mman.h>

main()
{
	void *a;
        a = mmap((void *)0x40000000, 4096, PROT_READ|PROT_WRITE, MAP_STACK, -1, 0);

	*((long *)0x40000000) = 0xBAADF00D;
	*((long *)0x40000004) = 0xBAADF00D;
	*((long *)0x3FFFFFFC) = 0xBAADF00D;
}

In this code, what causes a segfault is the last line.

Quote from FreeBSD mmap(2):
     MAP_STACK         [snip] This option creates a memory region that
                       grows to at most len bytes in size, starting from the
                       stack top and growing down.  The stack top is the
                       starting address returned by the call, plus len bytes.
                       The bottom of the stack at maximum growth is the start-
                       ing address returned by the call.

The returned address is called "the bottom" here. Quite confusing,
isn't it... :-)

Jun-Young

-- 
Bang Jun-Young <junyoung@NetBSD.org>