//
// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// libdebug.c --
//
// Author           : Thierry Delisle
// Created On       : Thu Mar 30 12:30:01 2017
// Last Modified By : 
// Last Modified On : 
// Update Count     : 0
//

extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <unistd.h>
}

enum { buffer_size = 512 };
static char buffer[ buffer_size ];

extern "C" {

	void __lib_debug_write( int fd, const char *in_buffer, int len ) {
		// ensure all data is written
		for ( int count = 0, retcode; count < len; count += retcode ) { 
			in_buffer += count;

			for ( ;; ) {
				retcode = write( fd, in_buffer, len - count );

				// not a timer interrupt ?
				if ( retcode != -1 || errno != EINTR ) break; 
			}

			if ( retcode == -1 ) _exit( EXIT_FAILURE );
		}
	}

	void __lib_debug_acquire() __attribute__((__weak__)) {}
	void __lib_debug_release() __attribute__((__weak__)) {}

	void __lib_debug_print_safe  ( const char fmt[], ... ) __attribute__(( format (printf, 1, 2) )) {
		va_list args;

		va_start( args, fmt );
		__lib_debug_acquire();
		
		int len = vsnprintf( buffer, buffer_size, fmt, args );
		__lib_debug_write( STDERR_FILENO, buffer, len );

		__lib_debug_release();
		va_end( args );
	}

	void __lib_debug_print_nolock( const char fmt[], ... ) __attribute__(( format (printf, 1, 2) )) {
		va_list args;

		va_start( args, fmt );
		
		int len = vsnprintf( buffer, buffer_size, fmt, args );
		__lib_debug_write( STDERR_FILENO, buffer, len );

		va_end( args );
	}

	void __lib_debug_print_vararg( const char fmt[], va_list args ) {
		int len = vsnprintf( buffer, buffer_size, fmt, args );
		__lib_debug_write( STDERR_FILENO, buffer, len );
	}

	void __lib_debug_print_buffer( char in_buffer[], int in_buffer_size, const char fmt[], ... ) __attribute__(( format (printf, 3, 4) )) {
		va_list args;

		va_start( args, fmt );
		
		int len = vsnprintf( in_buffer, in_buffer_size, fmt, args );
		__lib_debug_write( STDERR_FILENO, in_buffer, len );

		va_end( args );
	}
}