[alt.sources] [comp.unix.questions...] Re: Is there an alternative to sbrk

gwyn@smoke.BRL.MIL (Doug Gwyn) (03/03/90)

Archive-name: fake-sbrk/02-Mar-90
Original-posting-by: gwyn@smoke.BRL.MIL (Doug Gwyn)
Original-subject: Re: Is there an alternative to sbrk()
Reposted-by: emv@math.lsa.umich.edu (Edward Vielmetti)

[This is an experimental alt.sources re-posting from the newsgroup(s)
comp.unix.questions,comp.sys.next. Comments on this service to emv@math.lsa.umich.edu 
(Edward Vielmetti).]


In article <5538@ur-cc.UUCP> bwbe_c52@uhura.cc.rochester.edu (Brent Benson) writes:
>	The UNIX system calls `brk' and `sbrk' are not supported
>	on the NeXT computer.

Try the following emulation; you may need to add an initial call sbrk(0)
at the beginning of main() just to make sure things are set up properly,
although I've attempted to automate that for you.  If this emulation
doesn't work, the system architecture is probably unsuitable for use of
brk()/sbrk() and you'll need to rework the application code accordingly.

/*
	sbrk(), brk() emulation based on calloc()

	last edit:	02-Mar-1990	D A Gwyn
 */

#include	<errno.h>		/* for errno, ENOMEM */

#if __STDC__
#include	<stdlib.h>		/* for calloc */
#else
extern char	*calloc();
#endif

#ifndef	HEAP_SIZE		/* with 32-bit ints, 0x200000 is recommended */
#define	HEAP_SIZE	0x8000		/* size of simulated heap, in bytes */
#endif

#define	BRK_OK		0
#define	BRK_ERR		(-1)
#define	SBRK_ERR	((char *)-1)	/* horrible interface design */

static char	*bottom = 0;		/* bottom of calloc()ed pseudo-heap */
static char	*brkval = 0;		/* current value of simulated break */

int
brk( endds )
	char	*endds;
	{
	int	offset;

	if ( bottom == 0 )
		if ( (bottom = (char *)calloc( HEAP_SIZE, 1 )) == 0 )
			return BRK_ERR;	/* unable to set up pseudo-heap */
		else
			brkval = bottom;

	if ( (offset = endds - bottom) < 0 || offset > HEAP_SIZE )
		{
		errno = ENOMEM;
		return BRK_ERR;		/* attempt to set break out of heap */
		}
	else	{
		brkval = endds;
		return BRK_OK;
		}
	}

char *
sbrk( incr )
	int	incr;
	{
	int	offset;

	if ( bottom == 0 )
		if ( (bottom = (char *)calloc( HEAP_SIZE, 1 )) == 0 )
			return SBRK_ERR;	/* unable to set up heap */
		else
			brkval = bottom;

	if ( (offset = (brkval - bottom) + incr) < 0 || offset > HEAP_SIZE )
		{
		errno = ENOMEM;
		return SBRK_ERR;	/* attempt to set break out of heap */
		}
	else	{
		char	*oldbrk = brkval;

		brkval += incr;
		return oldbrk;
		}
	}