/***************************************************************************
 * assert.cpp: implementation of Assert function
 *
 * This file is part of KTabEdit, a KDE tabulature editor
 *
 * copyright (C) 2007- the KTabEdit development team <mrgwen@gmail.com>
 ***************************************************************************/

/***************************************************************************
 * 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 of the License, or
 * (at your option) any later version.
 *
 * See the file COPYING for more information.
 ***************************************************************************/

#include "assert.h"

#include <execinfo.h>
#include <sstream>
#include <stdlib.h>

void ktabedit::assertion_failed(const std::string& msg, const std::string& expr, const std::string&  function, const std::string& file, long line) throw (std::exception)
{
	std::stringstream msgStream;
	
	if (msg == std::string())
		msgStream << "ASSERT: " << expr << " in function " << function << ", file " << file << ", line " << line << "\n";
	else
		msgStream << msg << expr << " in function " << function << ", file " << file << ", line " << line << "\n";
	
	throw ContractException(msgStream.str(), ktabedit::backtrace());
}

std::string ktabedit::backtrace()
{
	void* array[10];
	size_t size;
	char** strings;
	std::stringstream msgBacktrace;
	
	size = ::backtrace(array, 10);
	strings = backtrace_symbols(array, size);
	
	for (unsigned i = 0; i < size; i++)
		msgBacktrace << strings[i] << "\n";
	
	free (strings);
	
	return msgBacktrace.str();
}
