# $Header: sAgentUtils.pm 29-apr-2008.16:46:43 svrrao Exp $
#
#
# Copyright (c) 2001, 2008, Oracle. All rights reserved.  
#
#    NAME
#      sAgentUtils.pm - OSD watchdog code.
#
#    DESCRIPTION
#       This script contains OSD code for e.g traceback generation from 
#       corefiles
#
#    MODIFIED   (MM/DD/YY)
#      svrrao    04/29/08 - AIX specific changes
#      sunagarw  11/21/07 - check for executable and script before using.
#      vnukal    07/12/07 - Fix Bug 6203090. Traceback files for state agents
#      sksaha    11/04/04 - Add package info
#      sksaha    10/29/04 - Created

package sAgentUtils;
use EMAgent;
use EmctlCommon;

#
# sDebugCore
# sDebugCore is called when the monitor detects a core dump
# Parameter : CoreFile
#
sub sDebugCore
{
  $self = $_[0];
  $debugFile = $_[1];

  if($self->{initialized})
  {
    my($DBX) = "/usr/bin/dbx";

    if( -e $DBX )
    {
      my($traceBack) = $debugFile.".traceback";
      my($threads) = $debugFile.".threads";
      my($tempFile) = $debugFile.".tmp";
      my ($EMHOME) = $self->{emHome};

      EmctlCommon::testCEMDAvail();

      #Delete old core files if neccessary
      EMAgent::deleteExtraAgentCores($EMHOME);

      $qmessage = "q";

      if ( $^O eq "aix" )
      {
        # Create a tempFile for inputting gdb commands for core.threads file ...
        open TMPF, ">$tempFile";
        printf TMPF "thread\n"                 .
                    "$qmessage\n" ;
        close TMPF;

        system("$DBX $EMDROOT/bin/emagent $debugFile <$tempFile > $threads 2>&1");

        # Need to glob the threads file to dbx individual threads
        open (THREADFILE, $threads);

        # start a frest tempFile for backtrace
        open TMPF, ">$tempFile";
        while(<THREADFILE>)
        {
          @toks = split;

          if($toks[0] =~ /\$t/)
          {
            $toks[0] =~ s/\$t//;
            $toks[0] =~ s/>//;
            printf TMPF "echo =========================== THREAD $toks[0] ================================== \n";
            printf TMPF "thread current $toks[0]\n"  .
                        "where\n";
          }
        }
        printf TMPF "$qmessage\n";
        close TMPF;
        close(THREADFILE);

        system("echo ============================ THREAD BY THREAD BACK TRACE IN CORE DUMP ======================= > $traceBack");
        system("$DBX $EMDROOT/bin/emagent $debugFile <$tempFile >> $traceBack 2>&1");
 

        # Remove temporary command file
        unlink("$tempFile");
        return;
      }
    }
  }
}

1;
