#include <stdio.h>
#include "except.h"

#define EXCEPTION 2

struct type_raii_t {
	char * msg;
};

//Dtor function to test clean up routines
void dtor( struct type_raii_t * this ) {
	printf("%s\n", this->msg);
}

//Type macro use to make scope unwinding easier to see.
#define raii_t __attribute__(( cleanup(dtor) )) struct type_raii_t

//Leaf functions that raises exception
void bar() {
	raii_t a = { "Bar dtor" };

	throw( EXCEPTION );
}

//Matcher function which will check if the exception was correctly caught
extern int this_exception;
_Unwind_Reason_Code foo_try_match() {
	return this_exception == 2 ? _URC_HANDLER_FOUND : _URC_CONTINUE_UNWIND;
}

//Try statements are hoisted out see comments for details
//With this could probably be unique and simply linked from
//libcfa but there is one problem left, see the exception table 
//for details
void try( void (*try_block)(), void (*catch_block)() )
{
	//Setup statments
	//These 2 statments won't actually result in any code,
	//they only setup global tables.
	//However, they clobber gcc cancellation support from gcc.
	//We can replace the personality routine but replacing the exception
	//table gcc generates is not really doable, it generates labels based
	//on how the assembly works.
	//Setup the personality routine
	asm volatile (".cfi_personality 0x3,__gcfa_personality_v0");
	//Setup the exception table
	asm volatile (".cfi_lsda 0x3, .LLSDACFA2");

	//Label which defines the start of the area for which the handler is setup
	asm volatile (".TRYSTART:");

	//The actual statements of the try blocks
	try_block();

	//asm statement to prevent deadcode removal
	asm volatile goto ("" : : : : CATCH );

	//Normal return
	return;

	//Exceptionnal path
	CATCH : __attribute__(( unused ));
	//Label which defines the end of the area for which the handler is setup
	asm volatile (".TRYEND:");
	//Label which defines the start of the exception landing pad
	//basically what will be called when the exception is caught
	//Note, if multiple handlers are given, the multiplexing should be done
	//by the generated code, not the exception runtime
	asm volatile (".CATCH:");

	//Exception handler
	catch_block();
}

//Exception table data we need to generate
//While this is almost generic, the custom data refers to
//foo_try_match try match, which is no way generic
//Some more works need to be done if we want to have a single 
//call to the try routine
asm (
	//HEADER
	".LFECFA1:\n"
	"	.globl	__gcfa_personality_v0\n"
	"	.section	.gcc_except_table,\"a\",@progbits\n"
	".LLSDACFA2:\n"							//TABLE header
	"	.byte	0xff\n"
	"	.byte	0xff\n"
	"	.byte	0x1\n"
	"	.uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n"		//BODY length
	//Body uses language specific data and therefore could be modified arbitrarily
	".LLSDACSBCFA2:\n"						//BODY start
	"	.uleb128 .TRYSTART-try\n"				//Handled area start  (relative to start of function)
	"	.uleb128 .TRYEND-.TRYSTART\n"				//Handled area length
	"	.uleb128 .CATCH-try\n"				//Hanlder landing pad adress  (relative to start of function)
	"	.uleb128 1\n"						//Action code, gcc seems to use always 0
	//Beyond this point we don't match gcc data'
	"	.uleb128 foo_try_match-try\n"			//Handler routine to check if the exception is matched
	".LLSDACSECFA2:\n"						//BODY end
	"	.text\n"							//TABLE footer
	"	.size	try, .-try\n"
	"	.ident	\"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n"
	"	.section	.note.GNU-stack,\"x\",@progbits\n"
);

void foo() {
	raii_t a = { "Foo dtor" };

	//Since try will clobber the gcc exception table assembly,
	//We need to nest this to have gcc regenerate the data
	void foo_try_block() {
		raii_t b = { "Foo try dtor" };

		bar();

		printf("Called bar successfully\n");
	}

	void foo_catch_block() {
		printf("Exception caught\n");
	}

	//Actual call to the try block
	try( foo_try_block, foo_catch_block );

	printf( "Foo exited normally\n" );
}

int main() {
	raii_t a = { "Main dtor" };

	foo();

	printf("End of program reached\n");
}