#include <cstdio>
#include <cassert>
#include <cstdarg>

// TEST CASE TO SHOW LIBCXX BUG IN VASPRINTF. COMPILES ON MINGW AND MAYBE OTHERS.
// ON WHATEVER SYSTEM IT SUCCEEDS IN COMPILING ON, IT SHOULD DEMONSTRATE THE PROBLEM IN LIBCXX FOR MINGW.
// IT SHOULD FAIL THE FIRST TIME WITH AN ASSERTION AND PRINTF A MESSAGE TO SHOW THE BUG.
// ONCE THIS HAPPENS, CHANGE THE LINE BELOW FROM 0 TO 1 TO ENABLE THE PROPOSED VERSION THAT FIXES THE BUG.
// THEN COMPILE AND RUN AGAIN.
// IF NO ASSERTION/MESSAGE RESULTS, THE BUG SHOULD BE FIXED.

#define USE_CURRENT_ASPRINTF 0

// Proposed version of asprintf to replace the current version.
// Like sprintf, but when return value >= 0 it returns a pointer to a malloc'd string in *sptr.
// If return >= 0, use free to delete *sptr.
int proposed_vasprintf( char **sptr, const char *__restrict fmt, va_list ap )
{
    *sptr = NULL;
    int count = vsnprintf( NULL, 0, fmt, ap ); // Query the buffer size required.
	if( count >= 0 ) {
	    char* p = static_cast<char*>(malloc(count+1)); // Allocate memory for it.
	    if ( p == NULL )
	        return -1;
        if ( vsnprintf( p, count+1, fmt, ap ) == count ) // We should have used exactly what was required.
            *sptr = p;
        else { // Otherwise something is wrong, likely a bug in vsnprintf. If so free the memory and report the error.
            free(p);
            return -1;
        }
    }

    return count;
}

// Exact same code as is IN libcxx right now.
int current_vasprintf( char **sptr, const char *__restrict fmt, va_list ap )
{
    *sptr = NULL;
    int count = vsnprintf( *sptr, 0, fmt, ap );
    if( (count >= 0) && ((*sptr = (char*)malloc(count+1)) != NULL) )
    {
        vsprintf( *sptr, fmt, ap );
        sptr[count] = '\0'; // Should and does generate a warning on a good compiler, shows you something is wrong.
    }

    return count;
}

// Exact same code as is in libcxx, support\win32\support.cpp except modified
// to have a new name, that wont clash and to conditionally call either the current or the proposed vasprintf.
int libcxx_asprintf(char **sptr, const char *__restrict fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
#if USE_CURRENT_ASPRINTF
    int result = current_vasprintf(sptr, fmt, ap);
#else
    int result = proposed_vasprintf(sptr, fmt, ap);
#endif
    va_end(ap);
    return result;
}

static void test_asprintf_overwrite()
{
	char* const expected_value = ( char* ) -1; // Any non 0 value is fine.
    char msg[] = { "hello" };
    const int msg_len = sizeof msg - 1;
	char* sptr[msg_len+1] = { NULL }; // First element of sptr is initialized to NULL, it should change.
	sptr[msg_len] = expected_value; // And last element is initialized to a non 0 expected value.

    // asprintf SHOULD change sptr[0] to point to a newly malloc'd string,
    // containing the same contents as msg and that's all.

    // asprintf should NOT change any other element of sptr, epsecially the last element.
    // If it does, it has to be because of corruption by asprintf/vasprintf (one calls the other). 
    // as no other elements of sptr are passed to asprintf and if asprintf is not called, the change does not occur.
    
	libcxx_asprintf( &sptr[0], "%s", msg );
    if ( sptr[0] == NULL ) {
	    printf( "asprintf/vsprintf test case is wrong\n" );
	    assert( false );
    }
	if ( sptr[ msg_len ] != expected_value ) {
	    printf( "asprintf/vsprintf has caused corruption\n" );
	    assert( false );
	}
    printf( "asprintf is working!\n" );	
}

int main()
{
    test_asprintf_overwrite();
}
