/*
 * libsal/debug/debug_onfatal.c
 * Routines to manipulate what happens when a fatal error occurs
 * 
 * DESCRIPTION
 * 
 * 	These routines are used by sal_debug_Init(), and sal_dprint(),
 * 	to set, and perform, actions when a fatal error is logged.
 * 
 * 	Original Author
 * 	===============
 * 	Stuart Herbert
 * 	Academic Computing Services, The University of Sheffield
 */

#include <libsal/debug/internal.h>
#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>
#include <stdlib.h>

static sal_debug_fatalfunc_t static_pfFatalError = abort;

void sal_debug_SetOnFatal
(
  sal_debug_fatalfunc_t pfFatalArg
)
{
  TEST_ARG(pfFatalArg != NULL, 1);
  
  static_pfFatalError = pfFatalArg;
}

void sal_debug_OnFatal
(
  void
)
{
  /* if we don't have a fatal error handler, log the error and core dump
   * otherwise call the fatal error handler */
  if (static_pfFatalError == NULL)
  {
    sal_debug_dprintf(SAL_DEBUG_MSG_ERRORAUTHOR, "Unable to call fatal error handler - core dumping NOW\n");
    abort();
  }
  else
    (*static_pfFatalError)();
  
  /* if we get to here, then the fatal error handler has returned, which
   * it really shouldn't have. */
  
  sal_debug_dprintf(SAL_DEBUG_MSG_ERRORAUTHOR, "Fatal error handler has not terminated the process - core dumping NOW\n");
  abort();
}
