#!/bin/sh
#
# checksize  -  check that kernel sizes are correct
#
# Copyright (C) 1998 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.
#

#
# number of kb available in the upper memory area excluding an extended
# BIOS data area in a typical PC
#
memavail=31

#
# the AWK shell variable usually comes from the makefile
#
if [ "x$AWK" = "x" ]; then
	AWK="awk"
fi

#
# check for command line options
#
if [ $# -ne 1 -o ! -r "$1" ]; then
	echo "usage: $0 <map file>" >&2
	exit 1
fi

#
# determine number of bytes occupied by text, data and BSS segments
# from kernel map file
#
required=`$AWK '
  # initialize variables
  BEGIN {
	# required stack size - this is defined in init/kernel.S
	stacksize   = 4096
	end_of_text = 0
	end_of_bss  = 0
  }

  # find _end_of_text label and extract size of text segment
  $2 == "_end_of_text" {
	for (i = 1; i <= length($4); i++) {
		c = index("0123456789ABCDEF", toupper(substr($4, i, 1)))
		end_of_text = end_of_text * 16 + c - 1
	}
  }

  # find _end_of_bss label and extract total size of data and BSS segments
  $2 == "_end_of_bss" {
	for (i = 1; i <= length($4); i++) {
		c = index("0123456789ABCDEF", toupper(substr($4, i, 1)))
		end_of_bss = end_of_bss * 16 + c - 1
	}
  }

  # compute total number of bytes required
  END {
	if (end_of_text <= 0 || end_of_bss <= 0)
		print 0
	else
		print int((end_of_text + end_of_bss + stacksize + 1023) / 1024)
  }
' $1`

#
# finally check that enough memory is available
#
if [ $required -eq 0 ]; then
	echo "ERROR: invalid kernel map file" >&2
	exit 1
fi
if [ $required -gt $memavail ]; then
	echo "ERROR: kernel image is too large" >&2
	exit 1
fi
exit 0

