// -*-C++-*- 

/*  src/platform/POSIXPlatform.cpp  */

/*
 * Author: Philogelos A. <Philogelos@yahoo.com>
 * Maintainer: Philogelos A.
 * Keywords: C++, library, containers
 *
 * Copyright (C) 1998 Philogelos A.
 *
 * This file is part of Quercus Robusta.
 *
 * Quercus Robusta is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this software; see the file COPYING.LIB.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */



/* $Id$ */
#if !defined(_INLINE)
static char cvsid[] = "@(#)$Id$";
static char debugFileId[] = __FILE__;
#endif

#include "platform/POSIXPlatform.hpp"

#if defined( USE_POSIX )

#define _XOPEN_SOURCE
#include <sys/signal.h>

#include <sys/types.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#if defined( __linux__ )
#include <sigaction.h>
#endif
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>

#include "String.hpp"
#include "Debug.hpp"
#include "OGuard.hpp"

#if defined( USE_GETITIMER ) && defined( USE_CLOCK_GETTIME )
#error "Use either USE_GETITIMER or USE_CLOCK_GETTIME"
#endif

extern "C" int kill(pid_t pid, int sig);
#if defined( USE_CLOCK_GETTIME )
extern "C" int clock_gettime( clockid_t clock_id, struct timespec *tp );
#endif

#if defined( USE_GETITIMER )
static long resetTimer()
{
  struct itimerval newCharge;
  struct itimerval value;

  test_( getitimer( ITIMER_REAL, &value ) == 0 );
  if( value.it_value.tv_sec < 1000000 )
	{
	  newCharge.it_interval.tv_sec = 100000000;
	  newCharge.it_interval.tv_usec = 0;
	  newCharge.it_value.tv_sec = 100000000;
	  newCharge.it_value.tv_usec = 0;
	  
	  test_( setitimer( ITIMER_REAL, &newCharge, NULL ) == 0 );
	  if( value.it_value.tv_sec != 0 )
		{
		  DLOG( "Microsecond timer was adjusted!" );
		}
	}
  return 1000000 - value.it_value.tv_usec;
}
#endif

static void panicHandler( int aSigNum )
{
  DLOG( "Catched unexpected signal %i", aSigNum );
  while( true )
	{}
}

#if defined( __linux__ )
extern "C" int sigaction( int __sig, 
						  const struct sigaction *__act,
						  struct sigaction *__oact );
#endif

void setSignalHandlerToPanic( int aSigNum )
{
  struct sigaction action;

  action.sa_handler = panicHandler;
  action.sa_flags = 0;
  test_( sigaction( aSigNum, &action, NULL ) == 0 );
}

POSIXPlatform::POSIXPlatform()
{
  setImageName( IMAGE_NAME );
  setSignalHandlerToPanic( SIGSEGV );
  setSignalHandlerToPanic( SIGBUS );
#if defined( USE_GETITIMER )
  resetTimer();
#endif
}

POSIXPlatform::~POSIXPlatform()
{}

char *POSIXPlatform::getErrorDescription( int errCode )
{
  ++callsNum;
  return strerror( errCode );
}

void POSIXPlatform::exitImmediate( long status )
{
  ++callsNum;
  _exit( status );
}
  
void POSIXPlatform::suicide()
{
  ++callsNum;
  kill( getpid(), SIGABRT );
  while( true )
	{}
}

void POSIXPlatform::attachDebugger()
{
  int result;
  const char *errorMessage;
  boolean MelTheProgrammer;

  ++callsNum;
  errorMessage = "Fork failed in attempt to attach debugger";
  result = fork();
  if( result == 0 )
	{
	  char *pidBuffer;

	  pidBuffer = new char[ ( 3 * sizeof( pid_t ) ) + 1 ];
	  this -> sprintf( pidBuffer, "%i", getppid() );
	  /* XXX how to get to the argv[0]? */
	  result = execlp
		( DEBUGGER_COMMAND, DEBUGGER_COMMAND, 
		  getImageName(), pidBuffer, NULL );
	  delete []pidBuffer;
	  errorMessage = "Exec failed in attempt to attach debugger";
	}
  if( result < 0 )
	{
	  rawErrorPrintf( errorMessage );
	  suicide();
	}
  /* you can set this from debugger to break out of loop */
  MelTheProgrammer = true;
  while( MelTheProgrammer )
	{}
}

void POSIXPlatform::setImageName( const char *aName )
{
  preC_( aName != NULL );
  
  imageName = aName;
}

const char *POSIXPlatform::getImageName() const
{
  return imageName;
}

char *POSIXPlatform::getTimeStampString()
{
  time_t instant;
#if defined( USE_CLOCK_GETTIME )
  struct timespec nanos;
#endif
  static char buffer[ 40 ];

  if( ( time( &instant ) == -1 )
#if defined( USE_CLOCK_GETTIME )
	  || ( clock_gettime( CLOCK_REALTIME, &nanos ) == -1 )
#endif
	  )
	{
	  strcpy( buffer, "UNKNOWN TIME" );
	}
  else
	{
	  static struct tm *t;

	  /* XXX _r version  localtime_r( &instant, &t ); */
	  t = localtime( &instant );
	  sprintf( buffer, "%4.4i/%2.2i/%2.2i %2.2i:%2.2i:%2.2i"
#if defined( USE_CLOCK_GETTIME )
			   ".%9.9li"
#endif
#if defined( USE_GETITIMER )
			   ".%6.6li"
#endif
			   ,
			   t -> tm_year + 1900, t -> tm_mon + 1, 
			   t -> tm_mday, t -> tm_hour, t -> tm_min, 
			   t -> tm_sec
#if defined( USE_CLOCK_GETTIME )
			   ,
			   nanos.tv_nsec
#endif
#if defined( USE_CLOCK_GETTIME ) || defined( USE_GETITIMER )
			   ,
			   resetTimer()
#endif
			   );
	}
  return buffer;
}

char *POSIXPlatform::getNL() const
{
  return ( char * ) "\n";
}

void *POSIXPlatform::allocateMemoryBootstrapPOSIX( Index aSize )
{
  return allocateMemoryBootstrapANSI( aSize );
}

void  POSIXPlatform::deallocateMemoryBootstrapPOSIX( void *aPointer )
{
  deallocateMemoryBootstrapANSI( aPointer );
}

boolean POSIXPlatform::equals( const Top *anOther ) const
{
  return( DCAST( anOther, POSIXPlatform ) == this );
}

Top *POSIXPlatform::clone() const
{
  return ( Top * ) this;
}

String  POSIXPlatform::toString() const
{
  return Object::toString() + " calls: " + String( callsNum );
}

String  POSIXPlatform::getClassName() const
{
  return "POSIXPlatform";
}

#if defined( WRAP_MAIN )

#include "exceptions/Exception.hpp"
#include "containers/lists/List.hpp"
#include "Backtrace.hpp"
#include "new-operator.hpp"
#include "LinkManager.hpp"
#include "OGuard.hpp"

int main( int argc, char *argv[], char *envp[] )
{
  List *args;

  try
	{
	  int retCode;

	  Platform::getInstance() -> setImageName( argv[ 0 ] );
	  Backtrace::initBacktrace();

#if defined( USE_THREADS )
	  Top::initThreads();
	  operatorNewInitThreads();
#endif	  

	  args = new List();
	  LinkManager::reg( args, args );

	  for( int i = 0 ; i < argc ; ++i )
		{
		  test_( argv[ i ] != NULL );
		  args -> append( new String( argv[ i ] ) );
		}
	  test_( argv[ argc ] == NULL );

	  retCode = QRMain( args );

	  LinkManager::free( args, args );
	  return retCode;
	}
  catch( Exception *anEx )
	{
	  OGuard _ex( anEx, anEx );
	  Debug::getLogger() -> exception( anEx );
	}
  catch( Throwable *thrown )
	{
	  DLOG( "Throwable catched" );
	}
  catch( ... )
	{
	  DLOG( "Unidentified exception catched" );
	}
  return 0;
}
#endif

#if defined(_INLINE)
#include "../src/Debug.ipp"
#include "../src/String.ipp"
#endif

/* USE_POSIX */
#endif

/* $Log$ */
