#!/usr/bin/perl -w
use strict;
use File::Basename;
use File::stat;
use Getopt::Long;

# This perl script is a conversion from the original shell script, which was:
#
# echo "     total       text       data        bss filename"
# sed 's/[^ ]* \.\///' syslink.input | sed 's/ .*//' | xargs size | awk 'NR != 1' | awk '{ printf("% 10d % 10d % 10d % 10d %s %s %s\n", $4, $1, $2, $3, $6, $7, $8) }' | sort -n

# Config.
my $version = "1.02";
my $progName = basename $0;
my $file_syslink = "./syslink.input";
my $file_debugmap = "./debug.map";
my $size_command = "isos-size";
my $catobj_command = "isos-ld -r"; #my $catobj_command = "catobj -l isos-ld -y isos-objcopy -d isos-objdump -no-prefix-tors";
my $strip_command = "isos-strip";
my $compress_command = "gzip -c"; #my $compress_command = "bzip2 -k -c";
my $tmp_name = "./ams-tmp";
my $tmp_name2 = "./ams-tmp2";
my $tmp_name3 = "./ams-tmp3";

# Parse command line options.
my $sortBy = "ram";
my $outputType = "module";
my $displayHelp = 0;
my $verbose;
my $res = GetOptions("help" => \$displayHelp,
		     "output:s" => \$outputType,
		     "sort:s" => \$sortBy,
		     "v|verbose"  => \$verbose);

# Check options.
if (($sortBy ne "module")
 && ($sortBy ne "ram")
    && ($sortBy ne "flash")) {
    print "The 'sort' option can only be used with 'module', 'ram', or 'flash'.\n\n";
    $displayHelp = 1;
}

if (($outputType ne "module")
 && ($outputType ne "file")) {
    print "The 'output' option can only set to 'module', or 'file'.\n\n";
    $displayHelp = 1;
}

# Display help?
if ($displayHelp || ($res ne 1)) {
    print <<EOF;
Usage: $progName [ options ]

Options:
    --help                           Displays this help text.
    --output=[module|file]           Outputs information for files or modules (default:module).
    --sort=[module|ram|flash]        Specifies how to sort output (default:ram).
                                     Note flash size is only approximate.
    --verbose                        Turn on verbose (debugging) output.
Version: $version
EOF
    exit (1);
}

# Undefine line separator
undef $/;

# Flush immediately to stdout
$| = 1;

# Read syslink file.
unless (open(FILE_SYSLINK, $file_syslink)) {
    print "This utility needs to be run in a build directory, ie. one that contains\n";
    print "the file called 'syslink.input'.\n";
    exit(1);
}
my $line_syslink = "";
$line_syslink = <FILE_SYSLINK>;
close(FILE_SYSLINK);

# Check data from syslink.input
if ($line_syslink eq "") {
    print "Error: Cannot parse syslink.input. Is this build directory the result\n";
    print "       of an unsuccessful build? This utility only works on a valid\n";
    print "       build directory.\n";
    exit(1);
}

# Split syslink file into the array.
my @line_syslink = split /\n/, $line_syslink;

# Read debugmap file.
unless (open(FILE_DEBUGMAP, $file_debugmap)) {
    print "This utility needs to be run in a build directory, ie. one that contains\n";
    print "the file called 'debug.map'.\n";
    exit(1);
}
my $line_debugmap = "";
$line_debugmap = <FILE_DEBUGMAP>;
close(FILE_DEBUGMAP);

# Check data from debug.map
if ($line_debugmap eq "") {
    print "Error: Cannot parse debug.map. Is this build directory the result\n";
    print "       of an unsuccessful build? This utility only works on a valid\n";
    print "       build directory.\n";
    exit(1);
}

# Split debugmap file into the array.
my @line_debugmap = split /\n/, $line_debugmap;

# Get list of files for "size" command.
my $file_list = "";

for (my $count = 0; $count <= $#line_syslink; $count += 1) {
    my @current_line = split / /, $line_syslink[$count];

    # Remove leading "./" (so file name will be in canonical "dir/file.o"
    # form.
    my $file_name = $current_line[1];
    if ($file_name =~ /^\.\//) {
        $file_name = substr $file_name, 2;
     }

    # Add object name to list.
    $file_list .= "$file_name ";
}

# Get set of object files that are actually linked into the image. Names are
# of the form "subsys/file.o" or "subsys/lib.a(file.o)".
my %object_list;

for (my $count = 0; $count <= $#line_debugmap; $count += 1) {
    my @current_line = split /\s+/, $line_debugmap[$count];

    # Add object name to list.
    if (($#current_line ge 4) &&
        ($current_line[1] =~ ".text|.data|.rodata")) {
        $object_list{$current_line[4]} = 1;
    }
}

# Get info about each object, and put each line into an array.
my @object_info = split /\n/, `$size_command $file_list`;
my @object_name;
my @text_size;
my @data_size;
my @bss_size;
my @total_size;
my @compressed_size;
my @module_dir;
my %module_size;
my %module_size_compressed;
my @module_list;
my $all_file_names = "";
my $all_files_size_compressed = 0;
my $output_count = 0;

# Remove the
#    text    data     bss     dec     hex filename
# header line from the output.
splice(@object_info, 0, 1);

# Collect all info. For object file, info is of the form
#    6408      96       0    6504    1968 openssh/sshd.o
# For library module, info is of the form
#    4276       0       0    4276    10b4 krb5_asn.o (ex openssl/libcrypto.a)

for (my $count = 0; $count <= $#object_info; $count += 1) {
    # Remove leading whitespace from the size output
    $object_info[$count] =~ s/^\s*//;

    # Split up output from 'size' command.
    my @current_line = split /[\s()]+/, $object_info[$count];

    # Get object name, formatting it the same as in object_list, i.e.
    # "subsys/file.o" or "subsys/lib.a(file.o)".
    my $object_name;
    my $file_name;

    if ($#current_line eq 5) {
        $object_name = $current_line[5];
        $file_name = $current_line[5];
    } elsif ($#current_line ge 7) {
        $object_name = $current_line[7]."(".$current_line[5].")";
	my ($dummy1, $dir, $dummy2) = fileparse($current_line[7]);
	$file_name = $dir.$current_line[5];
    } else {
        printf "Error: Invalid output from %s:\n%s\n", $size_command,
	       @current_line;
	exit(1);
    }

    printf STDOUT "Processing object (%3d/%d): %-50s", ($count + 1),
           ($#object_info + 1), $object_name;

    # If not actually linked into the image, ignore it.
    if (!$object_list{$object_name}) {
	if ($verbose) {
	    printf STDOUT "\rWarning: object '$object_name' ignored - not in debug.map.%-20s\n", "";
	}
        printf STDOUT "\r";
        next;
    }

    printf STDOUT "\r";

    # File is used, so add to list of all files.
    $all_file_names .= $file_name." ";

    # Get other details.
    $object_name[$output_count] = $object_name;
    $text_size[$output_count] = $current_line[0];
    $data_size[$output_count] = $current_line[1];
    $bss_size[$output_count] = $current_line[2];
    $total_size[$output_count] = $current_line[3];

    # Get module directory for this object.
    {
	my ( $dummy1, $dir, $dummy2) = fileparse($file_name);
	$module_dir[$output_count] = $dir;
    }

    # Calculate approximate size when compressed.
    my $result1 = system("$strip_command -o $tmp_name $file_name");
    my $result2 = 0;
    if ($result1 eq 0) {
	$result2 = system("$compress_command $tmp_name > $tmp_name2");
	if ($result2 eq 0) {
	    $compressed_size[$output_count] = (stat $tmp_name2)->size;
	}
	unlink($tmp_name2);
    }
    unlink($tmp_name);

    # Add size to module statistics.
    if ($verbose) {
	printf STDOUT "\rObject '$object_name' is in module '$module_dir[$output_count]'.%-20s\n", "";
    }
    $module_size{$module_dir[$output_count]} += $total_size[$output_count];
    $module_size_compressed{$module_dir[$output_count]} +=
                                           $compressed_size[$output_count];
    {
	my @search = grep /^$module_dir[$output_count]$/, @module_list;
	if ($#search eq -1) {
	    push @module_list, $module_dir[$output_count];
	}
    }

    if ($result1 || $result2) {
	printf "\nAborted.\n";
	exit(1);
    }

    # Increment output counter.
    $output_count += 1;
}

# Output results.
if ($outputType eq "file") {
    print "                                     Object Description       Text       Data        BSS        RAM      Flash\n";
    my $total_ram = 0;
    my $total_flash = 0;

    while ($#object_name > -1) {
	# Use first element as initial size.
	my $subscript_number = 0;
	
	# Sort by size by finding a larger size.
	if ($sortBy eq "ram") {
	    my $largest_size = $total_size[$subscript_number];
	    for (my $count = 0; $count <= $#object_name; $count += 1) {
		if ($total_size[$count] > $largest_size) {
		    $largest_size = $total_size[$count];
		    $subscript_number = $count;
		}
	    }
	}
	
	# Sort by compressed size by finding a larger compressed size.
	if ($sortBy eq "flash") {
	    my $largest_size = $compressed_size[$subscript_number];
	    for (my $count = 0; $count <= $#object_name; $count += 1) {
		if ($compressed_size[$count] > $largest_size) {
		    $largest_size = $compressed_size[$count];
		    $subscript_number = $count;
		}
	    }
	}
	
	# Output info.
	printf "%55s %10d %10d %10d %10d %10d\n", $object_name[$subscript_number],
	$text_size[$subscript_number],
	$data_size[$subscript_number],
	$bss_size[$subscript_number],
	$total_size[$subscript_number],
	$compressed_size[$subscript_number];

	# Add to running totals.
	$total_ram += $total_size[$subscript_number];
	$total_flash += $compressed_size[$subscript_number];
	
	# Remove this object from arrays.
	splice(@object_name, $subscript_number, 1);
	splice(@text_size, $subscript_number, 1);
	splice(@data_size, $subscript_number, 1);
	splice(@bss_size, $subscript_number, 1);
	splice(@total_size, $subscript_number, 1);
	splice(@compressed_size, $subscript_number, 1);
	splice(@module_dir, $subscript_number, 1);
    }
    printf "                                                                                   Total %10d %10d\n", $total_ram, $total_flash;
} else {
    print "                                     Module Description        RAM      Flash\n";
    my $total_ram = 0;
    my $total_flash = 0;

    while ($#module_list > -1) {
	# Use first element as initial size.
	my $subscript_number = 0;
	my $module = $module_list[$subscript_number];

	# Sort by size by finding a larger size.
	if ($sortBy eq "ram") {
	    my $largest_size = $module_size{$module};
	    for (my $count = 0; $count <= $#module_list; $count += 1) {
		if ($module_size{$module_list[$count]} > $largest_size) {
		    $subscript_number = $count;
		    $module = $module_list[$count];
		    $largest_size = $module_size{$module};
		}
	    }	    
	}	

	# Sort by compressed size by finding a larger compressed size.
	if ($sortBy eq "flash") {
	    my $largest_size = $module_size_compressed{$module};
	    for (my $count = 0; $count <= $#module_list; $count += 1) {
		if ($module_size_compressed{$module_list[$count]} > $largest_size) {
		    $subscript_number = $count;
		    $module = $module_list[$count];
		    $largest_size = $module_size_compressed{$module};
		}
	    }	    
	}	

	# Add to running totals.
	$total_ram += $module_size{$module};
	$total_flash += $module_size_compressed{$module};

	# Output info.
	printf "%55s %10d %10d\n", $module, $module_size{$module}, $module_size_compressed{$module};
	
	# Remove from array.
	splice(@module_list, $subscript_number, 1);
    }

    printf "                                                  Total %10d %10d\n", $total_ram, $total_flash;
}
