#! /bin/sh
# Utility to print out sizes of the different memory spaces
#   of an ELF file 


AWK=gawk
AVRSIZE=arm-none-eabi-size

# Usage
if test $# -lt 1; then
   echo "Usage: printmem.sh <ELF file>" >&2
    echo "Prints sizes of the different memory spaces in an ELF file." >&2
   exit 1
fi

# Memory size variables
PROGMAX=131072
DATAMAX=8192
EEPROMMAX=0

${AVRSIZE} -A "$1" | ${AWK} -v progmax=${PROGMAX} -v \
datamax=${DATAMAX} -v eeprommax=${EEPROMMAX} -v device=$2 -- '
/^\.(text|data|bootloader) / {text += $2}
/^\.(data|bss|noinit) / {data += $2}
/^\.(eeprom) / {eeprom += $2}
END {
   print  "STM32 Memory Usage:";
   print  "-------------------";
    if (device != "")
    {
        printf "Device: %s\n\n", device
    }
   printf "Program:%8d bytes", text
    if (progmax > 0)
    {
        printf " (%2.1f%% Full)", (text / progmax) * 100;
    }
    else
    {
        printf ""
    }
    printf  " (.text + .data + .bootloader)\n"
   printf "Data:   %8d bytes", data;
    if (datamax > 0)
    {
        printf " (%2.1f%% Full)", (data / datamax) * 100;
    }
    else
    {
        print ""
    }
    printf  " (.data + .bss + .noinit)\n"
   if (e > 0) 
    { 
        printf "EEPROM: %8d bytes", eeprom;
        if (eeprommax > 0)
        {
            printf " (%2.1f%% Full)", (eeprom / eeprommax) * 100;
        }
        else
        {
            printf ""
        }
        printf " (.eeprom)\n"
    }
}'
