#!/bin/sh
#
# Check for unfreed memory

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "$0 FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get all needed commands in our PATH
PATH=/sbin:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w
#line 31

# Don't use 'strict', if you do, we need to pull the zeus perl paths,
# and there isn't overly much point
#use strict;

BEGIN {
   # make sure we have all the perl modules we need
   unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
            "$ENV{ZEUSHOME}/admin/lib/perl",
            "$ENV{ZEUSHOME}/zxtm/lib/perl",
            "$ENV{ZEUSHOME}/perl" );
}

my $usage = "mtrace: memory leak detector\n\n" .
    "Usage: mtrace <pid> [<timelimit> <fadetime>]\n\n" .
    "timelimit = 0 means run forever.\n".
    "To dump current leaks, send mtrace SIGUSR2, to stop, SIGUSR1.\n" .
    "When <timelimit> (default: 30s) is reached, for <fadetime> (default: <timelimit>) ".
    "seconds only free()s are recorded.\n" .
    "dtrace is required; only runs on Solaris.\n";

if( scalar( @ARGV ) < 1 ) {
   print STDERR $usage;
   exit 1;
}


my( $dpid, $timelimit, $fadetime ) = @ARGV;

if( $dpid !~ /^\d+$/) {
   print $usage;
   exit 0;
}

die "This script is only supported on Solaris\n" unless `uname` eq "SunOS\n";

# Check we have dtrace
open( DTRACEVER, "dtrace -V |" ) or die "Couldn't run dtrace: $!\n";
while( <DTRACEVER> ) {
   # TODO: actually care what the version is?
}
close( DTRACEVER ) or die "Error running dtrace: $!\n";

if( !defined( $timelimit ) ) {
   $timelimit = 30;
} elsif( $timelimit !~ /^\d+$/ ) {
   print STDERR "The timelimit must be a decimal integer, got '$timelimit'\n";
   exit 2;
}

if( !defined( $fadetime ) ) {
   $fadetime = $timelimit;
} elsif( $fadetime !~ /^\d+$/ ) {
   print STDERR "The fadetime must be a decimal integer, got '$fadetime'\n";
   exit 2;
}

my $dcmd = "dtrace -p $dpid -n ".
"'pid${dpid}::*alloc:entry {printf(\"Amount %d\", arg0);}" .
" pid${dpid}::*alloc:return {printf(\"%p\", arg1);ustack();}" .
" pid${dpid}::free:entry /arg0 > 1/ {printf(\"%p\", arg0 );} ' |";

my $linenum = 0;
my $total_allocs = 0;
my $total_frees = 0;
my %allocs = ();
my %reused = ();
my $addr = '';
my $amount = 0;

if( !open( DTRACE, $dcmd ) ) {
   die "Cannot run command '$dcmd'\n";
}

my $stop = $timelimit > 0 ? time() + $timelimit : 0xffffffff;

$SIG{USR1}  = sub { print STDERR "user says 'stop'\n" ; $stop = time(); };

sub dumpstate()
{
   while( my( $k, $v ) = each( %allocs ) ) {
      print $v->{stack}, "\n";
   }
}

$SIG{USR2}  = sub { print "Current non-freed mallocs:\n" ; dumpstate(); };

if( !$timelimit ) {
   print( STDERR "***\n",
          " Running forever.\n",
          " To stop (after fade-out) send me USR1:  kill -USR1 $$\n",
          " To dump current state send me USR2   :  kill -USR2 $$\n***\n" );
}

my $v = 0;
my $fading = 0;

# solaris sometimes calls the internal function '_smalloc' from
# malloc - make sure we handle these allocations correctly
my $smalloc = 0;

while( my $line = <DTRACE> ) {
   print "Checking line $line" if $v;
   ++$linenum;
   if( !$fading && length( $addr ) > 0 && $line =~ /(.*?)\`(.*?)\+(.*)$/ ) {
      #print "stack\n";
      #print $2, "\n";
      #my $func = `echo $2 | c++filt`;
      my $func = "$2\n";
      #if( $line !~ /^\s*lib/ ) {
      my $info = $allocs{$addr};
      $info->{linenum} = $linenum;
      $info->{stack} .= $func;
      #}
   } elsif( !$fading && $line =~ /malloc:return ([0-9a-fA-F]+)$/ ) {
      $addr = $1;
      if( exists $allocs{$addr} ) {
         # check whether this is the return from an 'outer' malloc
         if( $smalloc && $line !~ /_smalloc/ ) {
            print "Ignoring return from outer malloc\n" if $v;
            $addr = '';
            next;
         }
         print "Re-use of address $addr\n" if $v;
         $reused{$addr} += 1;
      }
      print "alloc: $addr -> $amount\n" if $v;
      $total_allocs++;
      $allocs{$addr} = {
                        line => $linenum,
                        stack => '',
                        amount => $amount
                       };
   } elsif( $line =~ /free:entry ([0-9a-fA-F]+)/ ) {
      $total_frees++;
      my $freed_addr = $1;
      #print "free on $freed_addr\n";
      if( exists $allocs{$freed_addr} ) {
         #print "Free for stack \n", "$allocs{$freed_addr}->{stack}\n";
         delete $allocs{$freed_addr};
      } else {
         #print "Freed mem at $1 was not allocated in this trace\n";
      }
      $addr = '';
   } elsif( $line =~ /malloc:entry Amount (\d+)/ ) {
      $amount = $1;
      $smalloc = ( $line =~ /_smalloc/ ) ? 1 : 0;
      print "Found amount $amount\n" if $v;
   } else{
      if( length( $addr ) > 0 ) {
         print "got a complete stack\n" if $v;
         #print "Alloc to $addr with stack \n", "$allocs{$addr}->{stack}\n";
      }
      $addr = '';
      $amount = 0;
   }

   if( !$fading ) {
      if( $linenum%100 == 0 && time() > $stop ) {
         $stop += $fadetime;
         $fading = 1;
         print STDERR "Now fading out (another $fadetime seconds)...\n";
      }
   } else {
      if( $linenum%100 == 0 && time() > $stop ) {
         last;
      }
   }
}

close( DTRACE );

my %leaked = ();

foreach my $addr( sort{ $allocs{$a}->{linenum} cmp $allocs{$b}->{linenum} } keys( %allocs ) ) {
   if( $ENV{MTRACE_VERBOSE} ) {
      print " Show stack at line $allocs{$addr}->{linenum} (key) or continue (enter)?\n";
      my $ans = <STDIN>; chomp( $ans );
      if( $ans ) {
         print $allocs{$addr}->{stack};
      }
   }
   my $leak = $leaked{$allocs{$addr}->{stack}};
   if( !defined( $leak ) ) {
      $leaked{$allocs{$addr}->{stack}} = {
                                          occ => 1,
                                          lines => $allocs{$addr}->{linenum},
                                          amount => $allocs{$addr}->{amount}
                                         };
   } else {
      $leak->{occ} += 1;
      $leak->{amount} += $allocs{$addr}->{amount};
      $leak->{lines} .= ", ";
      $leak->{lines} .= $allocs{$addr}->{linenum};
   }
}

require Zeus::Open3;

sub open2
{
    return Zeus::Open3::_open3(scalar caller,
            $_[1], $_[0], '>&STDERR', @_[2 .. $#_]);
}

%allocs = ();

my $have_cppfilt = 1;
my $total = 0;
foreach my $stack( sort {

   my $l2 = $leaked{$b};
   my $l1 = $leaked{$a};

   my $occ2 = $l2->{occ};
   my $occ1 = $l1->{occ};
   return 1 if( $occ1 > $occ2 );
   return -1 if( $occ1 < $occ2 );

   my $bytes2 = $l2->{amount};
   my $bytes1 = $l1->{amount};
   return 1 if( $bytes1 > $bytes2 );
   return -1 if( $bytes1 < $bytes2 );

   return 0;
} keys( %leaked ) ) {
   my $nice_stack = $stack;
   if( $have_cppfilt ) {
      # convert mangled function names to human-readable methods:
      my( $chld_out, $chld_in );
      my $pid = open2( $chld_out, $chld_in, 'c++filt' );
      if( defined( $pid ) ) {
         print( $chld_in $stack );
         close( $chld_in );
         my $buf = "";
         while( my $r = <$chld_out> ) {
            $buf .= $r;
         }
         if( !close( $chld_out ) ) {
            $have_cppfilt = 0;
         }
         waitpid( $pid, 0 );
         if( length( $buf ) > 0 ) {
            $nice_stack = $buf;
         } else {
            $have_cppfilt = 0;
         }
      } else {
         $have_cppfilt = 0;
      }
   }
   $total += $leaked{$stack}->{amount},
   printf( "The following stack did not free its %5d bytes of allocated memory in this trace %4d times:\n%s\n",
           $leaked{$stack}->{amount},
           $leaked{$stack}->{occ},
           $nice_stack
         );
   print "Line numbers: ", $leaked{$stack}->{lines}, "\n\n";
}
#foreach my $a( sort( keys( %reused ) ) ) {
#   print "$a re-used $reused{$a} times\n";
#}
print "Total lines processed: $linenum, $total_allocs allocs, $total_frees frees, $total bytes leaked\n";
exit 0;
