//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// cc1.cc -- 
//
// Author           : Peter A. Buhr
// Created On       : Fri Aug 26 14:23:51 2005
// Last Modified By : Peter A. Buhr
// Last Modified On : Mon Sep  3 16:57:05 2018
// Update Count     : 125
//

#include <iostream>
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <cstdio>										// stderr, stdout, perror, fprintf
#include <cstdlib>										// getenv, exit, mkstemp
#include <unistd.h>										// execvp, fork, unlink
#include <sys/wait.h>									// wait

#include "config.h"										// configure info


//#define __DEBUG_H__


string compiler_name( CFA_BACKEND_CC );					// path/name of C compiler

string D__GCC_BPREFIX__( "-D__GCC_BPREFIX__=" );
string D__CFA_FLAGPREFIX__( "-D__CFA_FLAG__=" );

char tmpname[] = P_tmpdir "/CFAXXXXXX";
int tmpfilefd = -1;


bool prefix( string arg, string pre ) {
	return arg.substr( 0, pre.size() ) == pre;
} // prefix

enum { NumSuffixes = 2 };
const string suffixes[NumSuffixes] = { "cfa", "hfa", };

void suffix( string arg, const char * args[], int & nargs ) {
	//std::cerr << arg << std::endl;
	size_t dot = arg.find_last_of( "." );
	//std::cerr << dot << " " << (dot != string::npos ? arg.substr( dot + 1 ) : "fred" ) << std::endl;
	if ( dot == string::npos ) return;
	string sx = arg.substr( dot + 1 );
	for ( int i = 0; i < NumSuffixes; i += 1 ) {
		if ( sx == suffixes[i] ) {
			args[nargs] = "-x";
			nargs += 1;
			args[nargs] = "c";
			nargs += 1;
			return;
		} // if
	} // for
} // suffix


void checkEnv( const char * args[], int & nargs ) {
	char *value;

	value = getenv( "__CFA_COMPILER__" );
	if ( value != NULL ) {
		compiler_name = value;
		#ifdef __DEBUG_H__
		cerr << "env arg:\"" << compiler_name << "\"" << endl;
		#endif // __DEBUG_H__
	} // if

	value = getenv( "__GCC_MACHINE__" );
	if ( value != NULL ) {
		args[nargs] = ( *new string( value ) ).c_str(); // pass the argument along
		#ifdef __DEBUG_H__
		cerr << "env arg:\"" << args[nargs] << "\"" << endl;
		#endif // __DEBUG_H__
		nargs += 1;
	} // if

	value = getenv( "__GCC_VERSION__" );
	if ( value != NULL ) {
		args[nargs] = ( *new string( value ) ).c_str(); // pass the argument along
		#ifdef __DEBUG_H__
		cerr << "env arg:\"" << args[nargs] << "\"" << endl;
		#endif // __DEBUG_H__
		nargs += 1;
	} // if
} // checkEnv


void rmtmpfile() {
	if ( unlink( tmpname ) == -1 ) {					// remove tmpname
		perror ( "CFA Translator error: cpp failed" );
		exit( EXIT_FAILURE );
	} // if
	tmpfilefd = -1;										// mark closed
} // rmtmpfile


void sigTermHandler( __attribute__((unused)) int signal ) {
	if ( tmpfilefd != -1 ) {							// RACE, file created ?
		rmtmpfile();									// remove
		exit( EXIT_FAILURE );							// terminate 
	} // if
} // sigTermHandler


void Stage1( const int argc, const char * const argv[] ) {
	int code;

	string arg;
	string bprefix;

	const char *cpp_in = NULL;
	const char *cpp_out = NULL;

	bool CFA_flag = false;
	bool cpp_flag = false;
	const char *o_name = NULL;

	const char *args[argc + 100];						// leave space for 100 additional cpp command line values
	int nargs = 1;										// number of arguments in args list; 0 => command name
	const char *cargs[20];								// leave space for 20 additional cfa-cpp command line values
	int ncargs = 1;										// 0 => command name

	signal( SIGINT,  sigTermHandler );
	signal( SIGTERM, sigTermHandler );

	#ifdef __DEBUG_H__
	cerr << "Stage1" << endl;
	#endif // __DEBUG_H__
	checkEnv( args, nargs );							// arguments passed via environment variables
	#ifdef __DEBUG_H__
	for ( int i = 1; i < argc; i += 1 ) {
		cerr << "argv[" << i << "]:\"" << argv[i] << "\"" << endl;
	} // for
	#endif // __DEBUG_H__

	// process all the arguments

	for ( int i = 1; i < argc; i += 1 ) {
		arg = argv[i];
		if ( prefix( arg, "-" ) ) {
			// strip g++ flags that are inappropriate or cause duplicates in subsequent passes

			if ( arg == "-quiet" ) {
			} else if ( arg == "-imultilib" || arg == "-imultiarch" ) {
				i += 1;									// and the argument
			} else if ( prefix( arg, "-A" ) ) {
			} else if ( prefix( arg, "-D__GNU" ) ) {
				//********
				// GCC 5.6.0 SEPARATED THE -D FROM THE ARGUMENT!
				//********
			} else if ( arg == "-D" && prefix( argv[i + 1], "__GNU" ) ) {
				i += 1;									// and the argument

				// strip flags controlling cpp step

			} else if ( arg == "-D__CPP__" ) {
				cpp_flag = true;
			} else if ( arg == "-D" && string( argv[i + 1] ) == "__CPP__" ) {
				i += 1;									// and the argument
				cpp_flag = true;
			} else if ( arg == "-D__CFA_PREPROCESS__" ) {
				CFA_flag = true;
			} else if ( arg == "-D" && string( argv[i + 1] ) == "__CFA_PREPROCESS__" ) {
				i += 1;									// and the argument
				CFA_flag = true;
			} else if ( prefix( arg, D__CFA_FLAGPREFIX__ ) ) {
				cargs[ncargs] = ( *new string( arg.substr( D__CFA_FLAGPREFIX__.size() ) ) ).c_str();
				ncargs += 1;
			} else if ( arg == "-D" && prefix( argv[i + 1], D__CFA_FLAGPREFIX__.substr(2) ) ) {
				cargs[ncargs] = ( *new string( string( argv[i + 1] ).substr( D__CFA_FLAGPREFIX__.size() - 2 ) ) ).c_str();
				ncargs += 1;
				i += 1;									// and the argument
			} else if ( prefix( arg, D__GCC_BPREFIX__ ) ) {
				bprefix = arg.substr( D__GCC_BPREFIX__.size() );
			} else if ( arg == "-D" && prefix( argv[i + 1], D__GCC_BPREFIX__.substr(2) ) ) {
				bprefix = string( argv[i + 1] ).substr( D__GCC_BPREFIX__.size() - 2 );
				i += 1;									// and the argument

			// all other flags

			} else if ( arg == "-o" ) {
				i += 1;
				o_name = argv[i];
			} else {
				args[nargs] = argv[i];					// pass the flag along
				nargs += 1;
				// CPP flags with an argument
				if ( arg == "-D" || arg == "-U" || arg == "-I" || arg == "-MF" || arg == "-MT" || arg == "-MQ" ||
					 arg == "-include" || arg == "-imacros" || arg == "-idirafter" || arg == "-iprefix" ||
					 arg == "-iwithprefix" || arg == "-iwithprefixbefore" || arg == "-isystem" || arg == "-isysroot" ) {
					i += 1;
					args[nargs] = argv[i];				// pass the argument along
					nargs += 1;
					#ifdef __DEBUG_H__
					cerr << "argv[" << i << "]:\"" << argv[i] << "\"" << endl;
					#endif // __DEBUG_H__
				} else if ( arg == "-MD" || arg == "-MMD" ) {
					args[nargs] = "-MF";				// insert before file
					nargs += 1;
					i += 1;
					args[nargs] = argv[i];				// pass the argument along
					nargs += 1;
					#ifdef __DEBUG_H__
					cerr << "argv[" << i << "]:\"" << argv[i] << "\"" << endl;
					#endif // __DEBUG_H__
				} // if
			} // if
		} else {										// obtain input and possibly output files
			if ( cpp_in == NULL ) {
				cpp_in = argv[i];
				#ifdef __DEBUG_H__
				cerr << "cpp_in:\"" << cpp_in << "\"" << endl;
				#endif // __DEBUG_H__
			} else if ( cpp_out == NULL ) {
				cpp_out = argv[i];
				#ifdef __DEBUG_H__
				cerr << "cpp_out:\"" << cpp_out << "\""<< endl;
				#endif // __DEBUG_H__
			} else {
				cerr << "Usage: " << argv[0] << " input-file [output-file] [options]" << endl;
				exit( EXIT_FAILURE );
			} // if
		} // if
	} // for

	#ifdef __DEBUG_H__
	cerr << "args:";
	for ( int i = 1; i < nargs; i += 1 ) {
		cerr << " " << args[i];
	} // for
	if ( cpp_in != NULL ) cerr << " " << cpp_in;
	if ( cpp_out != NULL ) cerr << " " << cpp_out;
	cerr << endl;
	#endif // __DEBUG_H__

	if ( cpp_in == NULL ) {
		cerr << "Usage: " << argv[0] << " input-file [output-file] [options]" << endl;
		exit( EXIT_FAILURE );
	} // if

	if ( cpp_flag ) {
		// The -E flag is specified on the cfa command so only run the preprocessor and output is written to standard
		// output or -o. The call to cfa has a -E so it does not have to be added to the argument list.

		args[0] = compiler_name.c_str();
		suffix( cpp_in, args, nargs );					// check suffix
		args[nargs] = cpp_in;
		nargs += 1;
		if ( o_name != NULL ) {							// location for output
			args[nargs] = "-o";
			nargs += 1;
			args[nargs] = o_name;
			nargs += 1;
		} // if
		args[nargs] = NULL;								// terminate argument list

		#ifdef __DEBUG_H__
		cerr << "nargs: " << nargs << endl;
		for ( int i = 0; args[i] != NULL; i += 1 ) {
			cerr << args[i] << " ";
		} // for
		cerr << endl;
		#endif // __DEBUG_H__

		execvp( args[0], (char *const *)args );			// should not return
		perror( "CFA Translator error: cpp level, execvp" );
		exit( EXIT_FAILURE );
	} // if

	// Create a temporary file to store output of the C preprocessor.

	tmpfilefd = mkstemp( tmpname );
	if ( tmpfilefd == -1 ) {
		perror( "CFA Translator error: cpp level, mkstemp" );
		exit( EXIT_FAILURE );
	} // if

	#ifdef __DEBUG_H__
	cerr << "tmpname:" << tmpname << " tmpfilefd:" << tmpfilefd << endl;
	#endif // __DEBUG_H__

	// Run the C preprocessor and save the output in tmpfile.

	if ( fork() == 0 ) {								 // child process ?
		// -o xxx.ii cannot be used to write the output file from cpp because no output file is created if cpp detects
		// an error (e.g., cannot find include file). Whereas, output is always generated, even when there is an error,
		// when cpp writes to stdout. Hence, stdout is redirected into the temporary file.
		if ( freopen( tmpname, "w", stdout ) == NULL ) { // redirect stdout to tmpname
			perror( "CFA Translator error: cpp level, freopen" );
			exit( EXIT_FAILURE );
		} // if

		args[0] = compiler_name.c_str();
		suffix( cpp_in, args, nargs );					// check suffix
		args[nargs] = cpp_in;							// input to cpp
		nargs += 1;
		args[nargs] = NULL;								// terminate argument list

		#ifdef __DEBUG_H__
		cerr << "cpp nargs: " << nargs << endl;
		for ( int i = 0; args[i] != NULL; i += 1 ) {
			cerr << args[i] << " ";
		} // for
		cerr << endl;
		#endif // __DEBUG_H__

		execvp( args[0], (char *const *)args );			// should not return
		perror( "CFA Translator error: cpp level, execvp" );
		exit( EXIT_FAILURE );
	} // if

	wait( &code );										// wait for child to finish

	#ifdef __DEBUG_H__
	cerr << "return code from cpp:" << WEXITSTATUS(code) << endl;
	#endif // __DEBUG_H__

	if ( WIFSIGNALED(code) != 0 ) {						// child failed ?
		rmtmpfile();									// remove tmpname
		cerr << "CFA Translator error: cpp failed with signal " << WTERMSIG(code) << endl;
		exit( EXIT_FAILURE );
	} // if

	if ( WEXITSTATUS(code) != 0 ) {						// child error ?
		rmtmpfile();									// remove tmpname
		exit( WEXITSTATUS( code ) );					// do not continue
	} // if

	// If -CFA flag specified, run the cfa-cpp preprocessor on the temporary file, and output is written to standard
	// output.  Otherwise, run the cfa-cpp preprocessor on the temporary file and save the result into the output file.

	if ( fork() == 0 ) {								// child runs CFA
		cargs[0] = ( *new string( bprefix + "cfa-cpp" ) ).c_str();

		// Source file-name used to generate routine names containing global initializations for TU.
		cargs[ncargs] = ( *new string( "-F" ) ).c_str();
		ncargs += 1;
		cargs[ncargs] = ( *new string( string( cpp_in ) ) ).c_str();
		ncargs += 1;

		cargs[ncargs] = tmpname;
		ncargs += 1;
		if ( o_name != NULL ) {
			cargs[ncargs] = o_name;
			ncargs += 1;
		} else if ( ! CFA_flag ) {						// run cfa-cpp ?
			cargs[ncargs] = cpp_out;
			ncargs += 1;
		} // if
		cargs[ncargs] = NULL;							// terminate argument list

		#ifdef __DEBUG_H__
		cerr << "cfa-cpp ncargs: " << o_name << " " << CFA_flag << " " << ncargs << endl;
		for ( int i = 0; cargs[i] != NULL; i += 1 ) {
			cerr << cargs[i] << " ";
		} // for
		cerr << endl;
		#endif // __DEBUG_H__

		execvp( cargs[0], (char * const *)cargs );		// should not return
		perror( "CFA Translator error: cpp level, execvp" );
		exit( EXIT_FAILURE );
	} // if

	wait( &code );										// wait for child to finish

	#ifdef __DEBUG_H__
	cerr << "return code from cfa-cpp:" << WEXITSTATUS(code) << endl;
	#endif // __DEBUG_H__

	// Must unlink here because file must exist across execvp.
	rmtmpfile();										// remove tmpname

	if ( WIFSIGNALED(code) ) {							// child failed ?
		cerr << "CFA Translator error: cfa-cpp failed with signal " << WTERMSIG(code) << endl;
		exit( EXIT_FAILURE );
	} // if

	exit( WEXITSTATUS(code) );
} // Stage1


void Stage2( const int argc, const char * const * argv ) {
	string arg;

	const char *cpp_in = NULL;

	const char *args[argc + 100];						// leave space for 100 additional cfa command line values
	int nargs = 1;										// number of arguments in args list; 0 => command name

	#ifdef __DEBUG_H__
	cerr << "Stage2" << endl;
	#endif // __DEBUG_H__
	checkEnv( args, nargs );							// arguments passed via environment variables
	#ifdef __DEBUG_H__
	for ( int i = 1; i < argc; i += 1 ) {
		cerr << "argv[" << i << "]:\"" << argv[i] << "\"" << endl;
	} // for
	#endif // __DEBUG_H__

	// process all the arguments

	for ( int i = 1; i < argc; i += 1 ) {
		arg = argv[i];
		if ( prefix( arg, "-" ) ) {
			// strip inappropriate flags

			if ( arg == "-quiet" || arg == "-version" || arg == "-fpreprocessed" ||
				// Currently CFA does not suppose precompiled .h files.
				prefix( arg, "--output-pch" ) ) {

				// strip inappropriate flags with an argument

			} else if ( arg == "-auxbase" || arg == "-auxbase-strip" || arg == "-dumpbase" ) {
				i += 1;
				#ifdef __DEBUG_H__
				cerr << "arg:\"" << argv[i] << "\"" << endl;
				#endif // __DEBUG_H__

				// all other flags

			} else {
				args[nargs] = argv[i];					// pass the flag along
				nargs += 1;
				if ( arg == "-o" ) {
					i += 1;
					args[nargs] = argv[i];				// pass the argument along
					nargs += 1;
					#ifdef __DEBUG_H__
					cerr << "arg:\"" << argv[i] << "\"" << endl;
					#endif // __DEBUG_H__
				} // if
			} // if
		} else {										// obtain input and possibly output files
			if ( cpp_in == NULL ) {
				cpp_in = argv[i];
				#ifdef __DEBUG_H__
				cerr << "cpp_in:\"" << cpp_in << "\"" << endl;
				#endif // __DEBUG_H__
			} else {
				cerr << "Usage: " << argv[0] << " input-file [output-file] [options]" << endl;
				exit( EXIT_FAILURE );
			} // if
		} // if
	} // for

	#ifdef __DEBUG_H__
	cerr << "args:";
	for ( int i = 1; i < nargs; i += 1 ) {
		cerr << " " << args[i];
	} // for
	cerr << endl;
	if ( cpp_in != NULL ) cerr << " " << cpp_in;
	#endif // __DEBUG_H__

	args[0] = compiler_name.c_str();
	args[nargs] = "-S";									// only compile and put assembler output in specified file
	nargs += 1;
	args[nargs] = cpp_in;
	nargs += 1;
	args[nargs] = NULL;									// terminate argument list

	#ifdef __DEBUG_H__
	cerr << "stage2 nargs: " << nargs << endl;
	for ( int i = 0; args[i] != NULL; i += 1 ) {
		cerr << args[i] << " ";
	} // for
	cerr << endl;
	#endif // __DEBUG_H__

	execvp( args[0], (char * const *)args );			// should not return
	perror( "CFA Translator error: cpp level, execvp" );
	exit( EXIT_FAILURE );								// tell gcc not to go any further
} // Stage2


int main( const int argc, const char * const argv[], __attribute__((unused)) const char * const env[] ) {
	#ifdef __DEBUG_H__
	for ( int int i = 0; env[i] != NULL; i += 1 ) {
		cerr << env[i] << endl;
	} // for
	#endif // __DEBUG_H__

	string arg = argv[1];

	// Currently, stage 1 starts with flag -E and stage 2 with flag -fpreprocessed.

	if ( arg == "-E" ) {
		Stage1( argc, argv );
	} else if ( arg == "-fpreprocessed" ) {
		Stage2( argc, argv );
	} else {
		cerr << "Usage: " << argv[0] << " input-file [output-file] [options]" << endl;
		exit( EXIT_FAILURE );
	} // if
} // main

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
