/* Copyright (c) 1997-2009
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program 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 General Public License for more details.
*/

#ifndef _POLYMAKE_SIGNAL2EXCEPTION_H
#define _POLYMAKE_SIGNAL2EXCEPTION_H "$Id: signal2exception.h 9297 2009-09-02 13:27:00Z sherrmann $"

#include <signal.h>

template <class Exception>
void throw_it(int)
{
   throw Exception();
}

#if #cpu(sparc) && #system(svr4)
#include <ucontext.h>

template <int signal_no, class Exception>
class sig2exc {
private:
   struct sigaction save_old_action;

   static void sigwrapper(int, siginfo_t *info, ucontext_t *ct)
   {
      // registers saved at the trap point
      greg_t *reg=ct->uc_mcontext.gregs;
      const void (*thrower)(int)=&throw_it<Exception>;

      //  emulate call throw_it(info->si_code) from the trap location
      reg[REG_O0]=info->si_code;                      // %o0 = the 1st argument
      reg[REG_O7]=reg[REG_PC];                        // %o7 = return address
      reg[REG_PC]=reinterpret_cast<greg_t>(thrower);  // %pc = target address
      reg[REG_nPC]=reg[REG_PC]+4;                     // %npc = next instruction
   }
public:
   sig2exc()
   {
      struct sigaction new_action;
      new_action.sa_sigaction=sigwrapper;
      new_action.sa_flags=SA_SIGINFO;
      sigemptyset(&new_action.sa_mask);
      ::sigaction(signal_no,&new_action,&save_old_action);
   }

   ~sig2exc()
   {
      ::sigaction(signal_no,&save_old_action,0);
   }
};

#else
#  error   Sorry, this class is not implemented for this architecture
#endif

#endif // _POLYMAKE_SIGNAL2EXCEPTION_H
