#  $Header: resInfo.pl 10-oct-2002.16:46:25 vsekuboy Exp $
# 
# Copyright (c) 2001, 2002, Oracle Corporation.  All rights reserved.  
#
#    NAME
#      resInfo.pl
#
#    Description:
#       This script is used in the EMD to collect resident size information of processes
#	This is used only on linux and HP
#       The expected o/p if the script executes successfully is
#  
#	em_result=$totResMem
#
#    CREATED
#    vsekuboy 10/10/02 - Added HP-UX
#    vsekuboy 10/09/02 - Created

$ENV{PATH} = "/bin:/usr/bin:/usr/local/bin";

chomp ($os = `uname -s`);
if ( $os eq "HP-UX" ) {
   $resinfo = `$ENV{EMDROOT}/bin/nmupm resinfo @ARGV`;
   print "$resinfo";
   exit 0;
}

if($#ARGV==-1) {
  print "Usage : proc.pl [pid1, pid2, pid3....]\n";
  exit 1;
}

$totPSize = 0;
$totSSize = 0;

for ($i=0; $i<@ARGV; $i++) {
	$pid = $ARGV[$i];

	$pSize=getTotalPrivateDataSize($pid)/1024;
	$sSize=getTotalSharedDataSize($pid)/1024;

	$totPSize += $pSize;
	if ($sSize > $totSSize) {
		$totSSize=$sSize;
	};

};
$totResMem=$totPSize+$totSSize;

print "em_result=$totResMem\n";

sub getTotalPrivateDataSize {
  my ($pid) = @_;
  return getTotalDataSize($pid,"p");
}

sub getTotalSharedDataSize {
  my ($pid) = @_;
  return getTotalDataSize($pid,"s");
}


sub getTotalDataSize {
  my ($pid,$type) = @_;

  my $SHARED = "s";
  my $PRIVATE = "p";
  if($type!=$SHARED && $type!=$PRIVATE) {
     print "Should request for either of these types: ($SHARED|$PRIVATE)\n";
     exit;
  }
  open(MAPS,"/proc/$pid/maps") || die "Cannot open /proc/$pid/maps $!";
 my  $Tsum = 0;
  while ( $line = <MAPS> ) {
       my @fields=split(/\s+/,$line); #field separator is space
       my @fields1 = split(/-/,$fields[0]); # field separator is -
       @types = split(//,$fields[1]); # get the chars
      # print "$types[3]:$fields1[0]:$fields1[1]:$fields[1]\n";
 #      print "$fields1[1]\n";
       if($types[3] eq $SHARED && $type eq $SHARED) {
           $Tsum = $Tsum + hex($fields1[1])-hex($fields1[0]);
       }
       elsif($types[3] eq $PRIVATE && $type eq $PRIVATE) {
           $Tsum = $Tsum + hex($fields1[1])-hex($fields1[0]);
       }
   
  }
  close(MAPS);
  #printf("TSum : %d\n", $Tsum);
  return $Tsum;
}
