/*
 * heap.S86  -  Heap management routines for target library
 *
 * Copyright (C) 2003-2007 Gero Kuhlmann   <gero@gkminix.han.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: heap.S86,v 1.7 2007/01/06 18:30:51 gkminix Exp $
 *
 *====================================================================
 */


#include <common.i86>

.file __FILE__
.line __LINE__



/*
 *====================================================================
 *
 * Start the text segment and define all public entry points
 */

	.text

	.global	brk			# define global symbols
	.global	sbrk



/*
 *====================================================================
 *
 * Set new heap pointer
 * Input:  AX    -  New heap pointer
 * Output: Carry flag set if error
 * Changed registers: none
 */
brk:	push	bx
	cmp	ax,offset __bss_end
	jb	8f
	mov	bx,[stktop]
	sub	bx,[stksiz]		# compute upper heap boundary
	cmp	ax,bx			# check heap pointer
	ja	8f
	mov	[hpptr],ax		# set new heap pointer
	clc
	jmp	9f

8:	stc				# return with error
9:	pop	bx
	ret



/*
 *====================================================================
 *
 * Advance heap pointer up or down
 * Input:  AX    -  Value to add to heap pointer
 * Output: AX    -  Old heap pointer value (-1 if error)
 * Changed registers: AX
 */
sbrk:	or	ax,ax			# check if we have to just return the
	jnz	2f			# heap pointer
	mov	ax,[hpptr]
	clc
	jmp	9f

2:	push	word ptr [hpptr]
	add	ax,[hpptr]		# set new heap pointer
	call	brk
	pop	ax
	jnc	9f
	mov	ax,-1			# return with error
9:	ret




/*
 *====================================================================
 *
 * Data definitions
 */
	.data

	.global	stksiz


hpptr:	.word	__bss_end		# current heap pointer
stksiz:	.word	__stack_size		# current stack size




/*
 *====================================================================
 *
 * Variable definitions
 */
	.bss

	.extern	stktop			# top of stack pointer




/*
 *====================================================================
 */
	.end

