Exemple #1
0
// blockize the file, padding 0 if not divisible by BLOCK_SIZE
int blockize(FILE* fp)
{
	unsigned long fileLen;
	unsigned int file_blocks;
	unsigned int i;
	fseek(fp,0,SEEK_END);
	fileLen = ftell(fp); // get file length
	printf("\nfile size: %lu\n",fileLen);

	if(fileLen % BLOCK_SIZE==0) {
		// file divisible by block size
		file_blocks = fileLen/BLOCK_SIZE;
		printf("There are %d blocks\n",file_blocks);
	}
	else
	{
		// if not divisible, padding 0 at the end
		file_blocks = fileLen/BLOCK_SIZE+1;
		int padding = BLOCK_SIZE - fileLen % BLOCK_SIZE;
		unsigned char paddingBytes[padding];
		for (i=0;i<padding;i++)
			paddingBytes[i] = 0;
        write1StartTime = getCPUTime();
		fwrite(paddingBytes,padding,1,fp);
        write1Time += getCPUTime() - write1StartTime;
		printf("After padding %d zeros, there are %d blocks\n",padding,file_blocks);
	}
	return file_blocks;
}
int main(int argc, char *argv[])
{
	double startTime, endTime;

	startTime = getCPUTime();
	Func1();
	endTime = getCPUTime();

	std::cout << "startTime = " << startTime << " ms" <<std::endl;
	std::cout << "endTime = " << endTime << " ms" << std::endl;
	
	return 0;
}
Exemple #3
0
bool TimeoutChecker::didTimeOut(ExecState* exec)
{
    unsigned currentTime = getCPUTime();
    
    if (!m_timeAtLastCheck) {
        // Suspicious amount of looping in a script -- start timing it
        m_timeAtLastCheck = currentTime;
        return false;
    }
    
    unsigned timeDiff = currentTime - m_timeAtLastCheck;
    
    if (timeDiff == 0)
        timeDiff = 1;
    
    m_timeExecuting += timeDiff;
    m_timeAtLastCheck = currentTime;
    
    // Adjust the tick threshold so we get the next checkTimeout call in the
    // interval specified in intervalBetweenChecks.
    m_ticksUntilNextCheck = static_cast<unsigned>((static_cast<float>(m_intervalBetweenChecks) / timeDiff) * m_ticksUntilNextCheck);
    // If the new threshold is 0 reset it to the default threshold. This can happen if the timeDiff is higher than the
    // preferred script check time interval.
    if (m_ticksUntilNextCheck == 0)
        m_ticksUntilNextCheck = ticksUntilFirstCheck;
    
    if (m_timeoutInterval && m_timeExecuting > m_timeoutInterval) {
        if (exec->dynamicGlobalObject()->shouldInterruptScript())
            return true;
        
        reset();
    }
    
    return false;
}
Exemple #4
0
	void Timer::dump(ostream& s, Size depth) const
	{
		BALL_DUMP_STREAM_PREFIX(s);

		BALL_DUMP_DEPTH(s, depth);
		BALL_DUMP_CLASS_HEADER(s, Timer, this);

		BALL_DUMP_DEPTH(s, depth);
		s << "CPU speed: " << cpu_speed_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "is running: " << (is_running_ ? "true" : "false") << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "last clock seconds: " << last_secs_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "last user seconds: " << last_usecs_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "last user time: " << last_user_time_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "last system time: " << last_system_time_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "current clock seconds: " << current_secs_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "current user seconds: " << current_usecs_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "current user time: " << current_user_time_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "current system time: " << current_system_time_ << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "effective clock time: " << getClockTime() << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "effective user time: " << getUserTime() << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "effective system time: " << getSystemTime() << endl;

		BALL_DUMP_DEPTH(s, depth);
		s << "effective CPU time: " << getCPUTime() << endl;

		BALL_DUMP_STREAM_SUFFIX(s);
	}
Exemple #5
0
tarch::utils::Watch::~Watch() {
  if (!_calledStopManually) {
    stopTimer();
  }

  if (_plotResultInDestructor) {
    std::ostringstream message;
    message << "total number of clock ticks within block (cpu-time,calendar-time): "
            << "(" << getCPUTime() << "s"
            << "," << getCalendarTime() << "s"
            << ")";
    _log.info( _operationName, message.str() );
  }
}
Exemple #6
0
int precompute_response(FILE* fp, Chal * c,char * key) {

	unsigned char message[v*BLOCK_SIZE];
	unsigned char codeword[w*BLOCK_SIZE];
	char uth[BLOCK_SIZE];
	char ct[BLOCK_SIZE];
	int i,j,p;
	enc_init(key);
    // for each of the challenge
	for (j=0;j<q;j++) {

		int index = 0;
		for (i=0;i<v;i++) {
            // read in the random indexed blocks
            fseek(fp,c[j].s[i]*BLOCK_SIZE,SEEK_SET);
			unsigned char buffer[BLOCK_SIZE];
            readStartTime = getCPUTime();
            clock_gettime(CLOCK_MONOTONIC, &start);
			fread(buffer, BLOCK_SIZE, 1, fp);
            clock_gettime(CLOCK_MONOTONIC, &finish);
            double addTime = finish.tv_sec - start.tv_sec;
            addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
            readTime += getCPUTime() - readStartTime+addTime;
			for(p=0;p<BLOCK_SIZE;p++) {
				message[index] = buffer[p];
				index++;
			}
			fflush(stdout);
		}
        // perform a concatenated encoding
		concat_encode(message,codeword);
		for (i=0;i<BLOCK_SIZE;i++) {
            // get the u-th symbol
			uth[i] = codeword[BLOCK_SIZE*c[j].u+i];
		}
		clock_gettime(CLOCK_MONOTONIC, &start);
		encStartTime = getCPUTime();
        // encrypt the response and append at the end
		encrypt(ct,uth,sizeof(uth));
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		encTime += getCPUTime()-encStartTime+addTime;

        write2StartTime = getCPUTime();
		clock_gettime(CLOCK_MONOTONIC, &start);
		fwrite(ct,BLOCK_SIZE,1,fp);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
        write2Time+=getCPUTime()-write2StartTime+addTime;

	}
}
Exemple #7
0
int initial_outer_decoding(FILE* fp1,unsigned char * mac) {
	unsigned char newMac[16];
	unsigned char buf[BLOCK_SIZE];
	int i,j;
	FILE * orifp, * parifp;

	if ((orifp = fopen("original", "r+b")) == NULL){
		printf("couldn't open input file for reading.\n");
		return -1;
        }
	if ((parifp = fopen("parity", "w+b")) == NULL){
		printf("couldn't open input file for reading.\n");
		return -1;
        }
	fseek(fp1,m*BLOCK_SIZE,SEEK_SET);
	for (i=0;i<t-m;i++) {
		readStartTime = getCPUTime();
		fread(buf, BLOCK_SIZE, 1, fp1);
		readEndTime = getCPUTime();
		readTime += readEndTime-readStartTime;
		writeStartTime = getCPUTime();
   	fwrite(buf,BLOCK_SIZE,1,parifp);
      	writeEndTime = getCPUTime();
		writeTime += writeEndTime-writeStartTime;
	}
	fclose(parifp);
	if ((parifp = fopen("parity", "r+b")) == NULL){
		printf("couldn't open input file for reading.\n");
		return -1;
        }
   FILE* outer;
   if ((outer = fopen("outerdec", "w+b")) == NULL){
		printf("couldn't open input file for reading.\n");
		return -1;
        }     
   FILE* tempfp = fopen("tempfile", "w+b");
   initialize_ecc();
   outer_decoding(orifp, parifp, outer, tempfp, NULL);
	macStartTime = getCPUTime();
	printf("HMAC using key: ");
	displayCharArray(k_mac,16);	
	hmac("outerdec",newMac,k_mac);
	macEndTime = getCPUTime();
	macTime = macEndTime - macStartTime;
	printf("MAC of the file part: ");
	displayCharArray(newMac,16);

	for (i=0;i<16;i++) {
		if (newMac[i]!=mac[i])
			return -1;
	}
	return 0;
}
/**
@brief This function handles a system call request coming from a process running in Kernel Mode.
@return Void.
*/
HIDDEN void syscallKernelMode()
{
	/* Identify and handle the system call */
	switch (SYSBP_Old->a1)
	{
		case CREATEPROCESS:
			CurrentProcess->p_s.a1 = createProcess((state_t *) SYSBP_Old->a2);
			break;

		case TERMINATEPROCESS:
			terminateProcess();
			break;

		case VERHOGEN:
			verhogen((int *) SYSBP_Old->a2);
			break;

		case PASSEREN:
			passeren((int *) SYSBP_Old->a2);
			break;

		case GETCPUTIME:
			CurrentProcess->p_s.a1 = getCPUTime();
			break;

		case WAITCLOCK:
			waitClock();
			break;

		case WAITIO:
			CurrentProcess->p_s.a1 = waitIO((int) SYSBP_Old->a2, (int) SYSBP_Old->a3, (int) SYSBP_Old->a4);
			break;

		case SPECTRAPVEC:
			specTrapVec((int) SYSBP_Old->a2, (state_t *) SYSBP_Old->a3, (state_t *) SYSBP_Old->a4);
			break;

		default:
			/* Distinguish whether SYS5 has been invoked or not */
			checkSYS5(SYSBK_EXCEPTION, SYSBP_Old);
	}

	/* Call the scheduler */
	scheduler();
}
/**
 * @retval time Time in milliseconds
 */
double stopTimer( MTime* mtime )
{
  double time = -1.0;
  float milliseconds = 0;
  switch(mtime->type)
  {
    case CPU_CLOCK_TIME:
      time = (mtime->time=1000.0*(getCPUTime( ) - mtime->start));
      break;
    case CPU_WALL_TIME:
      time = (mtime->time=1000.0*(getRealTime() - mtime->start));
      break;
    case GPU_TIME:
      CHECK_ERROR(cudaEventRecord(mtime->gpustop));
      CHECK_ERROR(cudaEventSynchronize(mtime->gpustop));
      CHECK_ERROR(cudaEventElapsedTime(&milliseconds, mtime->gpustart, mtime->gpustop));
      time = static_cast<double>(milliseconds);
      break;
    default:
      throw std::invalid_argument("Unhandled TIME TYPE.");
  }
  return time;
}
Exemple #10
0
int checkFile(FILE* fp1,unsigned char * mac) {
	unsigned char newMac[16];
	unsigned char buf[BLOCK_SIZE];
	int i,j;
	FILE * orifp;
	fseek(fp1,0,SEEK_SET);
	if ((orifp = fopen("original", "w+b")) == NULL){
		printf("couldn't open input file for reading.\n");
		return -1;
        }
	for (i=0;i<m;i++) {
		readStartTime = getCPUTime();
		fread(buf, BLOCK_SIZE, 1, fp1);
		readEndTime = getCPUTime();
		readTime += readEndTime-readStartTime;
		writeStartTime = getCPUTime();
   	fwrite(buf,BLOCK_SIZE,1,orifp);
      	writeEndTime = getCPUTime();
		writeTime += writeEndTime-writeStartTime;
	}
	fclose(orifp);
	macStartTime = getCPUTime();
	printf("HMAC using key: ");
	displayCharArray(k_mac,16);	
	hmac("original",newMac,k_mac);
	macEndTime = getCPUTime();
	macTime = macEndTime - macStartTime;
	printf("MAC of the file part: ");
	displayCharArray(newMac,16);

	for (i=0;i<16;i++) {
		if (newMac[i]!=mac[i])
			return -1;
	}
	return 0;
}
Exemple #11
0
void checkInCPUTime( void )
{
    startCPUTime = getCPUTime();
}
Exemple #12
0
int main(int argc, char *argv[])
{
	FILE *stream = NULL;
	int i, j, r, count;
	bool flag;

	Matrix matrix = NULL;
	Vector rhs = NULL;
	VectorArray Lattice = NULL;
	Vector vector = NULL;

	LinearSystem initialsystem;
	ZSolveContext ctx;

	char *token;
	int memory;

	getopts(argc, argv);

	puts(FORTY_TWO_BANNER);

	if (OResume)
	{
		// START OF RESUME SECTION - READ FILES AND CREATE CONTEXT 

		strcat(BaseName, ".backup");
		stream = fopen(BaseName, "r");
		BaseName[BaseLength] = '\0';

		if (stream==NULL)
		{
			printf("Unable to open backup file %s.backup\n", BaseName);
			free(BaseName);
			exit(1);
		}

		// options
		if (fscanf(stream, "%d %d %d", &OVerbose, &OLogging, &OBackup)!=3 || OVerbose<0 || OVerbose>3 || OLogging<0 || OLogging>3 || OBackup<0)
		{
			fclose(stream);
			printf("Backup file %s.backup does not contain valid data.\n", BaseName);
			free(BaseName);
			exit(2);
		}

		// get context
		ctx = createZSolveContextFromBackup(stream, zsolveLogCallbackDefault, backupEvent);
		fclose(stream);

		// logfile
		if (OLogging>0)
		{
			strcat(BaseName, ".log");
			stream = fopen(BaseName, "a");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				printf("Unable to open log file %s.log\n", BaseName);
				free(BaseName);
				exit(1);
			}
			ctx->LogFile = LogFile = stream;
		}

		// END OF RESUME SECTION
	}
	else
	{
		// logfile
		if (OLogging>0)
		{
			strcat(BaseName, ".log");
			stream = fopen(BaseName, "w");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				printf("Unable to open log file %s.log\n", BaseName);
				free(BaseName);
				exit(1);
			}
			LogFile = stream;
		}
		// check for existance of solution files
		if (!OForce)
		{
			strcat(BaseName, ".zhom");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				fclose(stream);
				if (OVerbose>0)
					printf("%s.hom already exists! Use -f to force calculation.\n", BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "%s.hom already exists! Use -f to force calculation.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
			strcat(BaseName, ".zinhom");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				fclose(stream);
				if (OVerbose>0)
					printf("%s.inhom already exists! Use -f to force calculation.\n", BaseName);
				if (LogFile)
				{
					fprintf(LogFile, "%s.inhom already exists! Use -f to force calculation.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
		}
	
		// matrix
		strcat(BaseName, ".mat");
		stream = fopen(BaseName, "r");
		BaseName[BaseLength] = '\0';

		if (stream == NULL)
		{
			stream = fopen(BaseName, "r");
			if (stream) {
				if (OVerbose>0)
					printf("Matrix file %s.mat not found, falling back to project file %s.\n\n", BaseName, BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "Matrix file %s.mat not found, falling back to project file %s.\n\n", BaseName, BaseName);
					fclose(LogFile);
				}
			}
		}

		if (stream==NULL)
		{
			strcat(BaseName, ".lat");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream==NULL)
			{
				// lattice
				if (OVerbose>0)
					printf("Neither matrix file %s.mat nor lattice file %s.lat exists!\n", BaseName, BaseName);
				if (OLogging>0)
				{
					fprintf(LogFile, "Neither matrix file %s.mat nor lattice file %s.lat exists!\n", BaseName, BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
			else
			{
				// START OF LATTICE SECTION - READ FILES AND CREATE CONTEXT

				Lattice = readVectorArray(stream, false);
				fclose(stream);
				if (Lattice == NULL)
				{
					if (OVerbose>0)
						printf("Lattice file %s.lat does not contain valid data.\n", BaseName);
					if (OLogging>0)
					{
						fprintf(LogFile, "Lattice file %s.lat does not contain valid data.\n", BaseName);
						fclose(LogFile);
					}
					free(BaseName);
					exit(1);
				}
			
				// rhs
				if (ORightHandSide)
				{
					strcat(BaseName, ".rhs");
					stream = fopen(BaseName, "r");
					BaseName[BaseLength] = '\0';
					if (stream!=NULL)
					{
						fscanf(stream, "%d", &i);
						if (i!=1)
						{
							fclose(stream);
							printf("Height of RHS must be 1!\n");
							if (LogFile)
							{
								fprintf(LogFile, "Height of RHS must be 1!\n");
								fclose(LogFile);
							}
							deleteMatrix(matrix);
							free(BaseName);
							exit(1);
						}
						fscanf(stream, "%d", &i);
						while (i--)
						{
							if (fscanf(stream, "%d", &j) || j!=0)
							{
								printf("When reading from %s.lat, RHS file %s.rhs must contain a zero vector.\n", BaseName, BaseName);
								if (LogFile)
								{
									fprintf(LogFile, "When reading from %s.lat, RHS file %s.rhs must contain a zero vector.\n", BaseName, BaseName);
									fclose(LogFile);
								}
								deleteMatrix(matrix);
								free(BaseName);
								exit(1);
							}
						}
					}
				}

				// variable properties

				for (i=0; i<Lattice->Variables; i++)
				{
					Lattice->Properties[i].Column = i;
					Lattice->Properties[i].Lower = OHilbert ? 0 : -MAXINT;
					Lattice->Properties[i].Upper = MAXINT;
					Lattice->Properties[i].Free = (!OGraver && !OHilbert);
				}
			
				// read .rel
				strcat(BaseName, ".rel");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;

					if (fscanf(stream, "%d %d", &r, &j)<2 || r != 1)
					{
						printf("RELATION file %s.rel must start with the dimensions.\n", BaseName);
						flag = true;
					}

					for (i=0; i<j; i++)
					{
						if (readTokenFromFile(stream, "0123456789=<>", &token, &memory) == 0)
						{
							printf("RELATION file %s.rel ends unexpectedly.\n", BaseName);
							flag = true;
						}
						else if (!strcmp(token, "<") || !strcmp(token, ">"))
						{
							printf("When reading from %s.lat, inequalities are not allowed.\n", BaseName);
							flag = true;
						}
						else if (strcmp(token, "="))
						{
							printf("Unknown token '%s' in RELATION file %s.rel.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
	
					if (flag)
					{
						free(BaseName);
						exit(1);
					}
				}
			
				// read .sign
				strcat(BaseName, ".sign");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
	
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("SIGN file %s.sign must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789-abcdefghijklmnopqrstuvwxyz", &token, &memory) == 0)
						{
							printf("SIGN file %s.sign ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "0") || !strcmp(token, "free") || !strcmp(token, "f"))
						{
							Lattice->Properties[i].Upper = MAXINT;
							Lattice->Properties[i].Lower = -MAXINT;
							Lattice->Properties[i].Free = true;
						}
						else if (!strcmp(token, "1") || !strcmp(token, "hil") || !strcmp(token, "h"))
						{
							Lattice->Properties[i].Upper = MAXINT;
							Lattice->Properties[i].Lower = 0;
							Lattice->Properties[i].Free = false;
						}
						else if (!strcmp(token, "-1") || !strcmp(token, "-hil") || !strcmp(token, "-h"))
						{
							Lattice->Properties[i].Upper = 0;
							Lattice->Properties[i].Lower = -MAXINT;
							Lattice->Properties[i].Free = false;
						}
						else if (!strcmp(token, "2") || !strcmp(token, "graver") || !strcmp(token, "g"))
						{
							if (OHilbert)
							{
								printf("Input Error: Graver components for `hilbert' executable.\nInput Error: Use the `graver' executable instead.\n");
								flag = true;
							}
							else
							{
								Lattice->Properties[i].Upper = MAXINT;
								Lattice->Properties[i].Lower = -MAXINT;
								Lattice->Properties[i].Free = false;
							}
						}
						else
						{
							printf("Unknown token '%s' in SIGN file %s.sign.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);

					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}
			
				// read .ub
				strcat(BaseName, ".ub");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
		
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("UPPER BOUNDS file %s.ub must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
						{
							printf("UPPER BOUNDS file %s.ub ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "*"))
							Lattice->Properties[i].Upper = MAXINT;
						else if (sscanf(token, "%d", &j) == 1)
						{
							if (Lattice->Properties[i].Free)
							{
								printf("Upper bound '%s' cannot be set for free variables.\n", token);
								flag = true;
							}
							else if (j>=0)
								Lattice->Properties[i].Upper = j;
							else
							{
								printf("Negative upper bound '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
								flag = true;
							}
						}
						else
						{
							printf("Unknown token '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
		
					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}

				// read .lb
				strcat(BaseName, ".lb");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					token = NULL;
					memory = 0;
					flag = false;
		
					if (fscanf(stream, "%d %d", &r, &i)<2 || i != Lattice->Variables || r != 1)
					{
						printf("LOWER BOUNDS file %s.lb must start with '1 %d'.\n", BaseName, Lattice->Variables);
						flag = true;
					}
	
					for (i=0; i<Lattice->Variables; i++)
					{
						if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
						{
							printf("LOWER BOUNDS file %s.lb ends unexpectedly.\n", BaseName);
							flag = true;
						}
						if (!strcmp(token, "*"))
							Lattice->Properties[i].Lower = -MAXINT;
						else if (sscanf(token, "%d", &j) == 1)
						{
							if (Lattice->Properties[i].Free)
							{
								printf("Lower bound '%s' cannot be set for free variables.\n", token);
								flag = true;
							}
							else if (j<=0)
								Lattice->Properties[i].Lower = j;
							else
							{
								printf("Positive lower bound '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
								flag = true;
							}
						}
						else
						{
							printf("Unknown token '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
							flag = true;
						}
					}
					free(token);
					fclose(stream);
		
					if (flag)
					{
						deleteVectorArray(Lattice);
						free(BaseName);
						exit(1);
					}
				}
	
				ctx = createZSolveContextFromLattice(Lattice, LogFile, OLogging, OVerbose, zsolveLogCallbackDefault, backupEvent);
			
				// print lattice
				if (ctx->Verbosity>0)
				{
					printf("\nLattice to use:\n\n");
					printVectorArray(ctx->Lattice, false);
					printf("\n\n");
				}
				if (ctx->LogLevel>0)
				{
					fprintf(ctx->LogFile, "\nLattice to use:\n\n");
					fprintVectorArray(ctx->LogFile, ctx->Lattice, false);
					fprintf(ctx->LogFile, "\n\n");
				}

				// END OF LATTICE SECTION
			}
		}
		else
		{
			// START OF SYSTEM SECTION - READ FILES AND CREATE CONTEXT

			matrix = readMatrix(stream);
			fclose(stream);
			if (matrix==NULL)
			{
				printf("Matrix file %s does not contain valid data.\n", BaseName);
				if (LogFile)
				{
					fprintf(LogFile, "Matrix file %s does not contain valid data.\n", BaseName);
					fclose(LogFile);
				}
				free(BaseName);
				exit(1);
			}
	
			// rhs
			if (ORightHandSide)
			{
				strcat(BaseName, ".rhs");
				stream = fopen(BaseName, "r");
				BaseName[BaseLength] = '\0';
				if (stream!=NULL)
				{
					if (OGraver || OHilbert)
					{
						fclose(stream);
						printf("Input Error: No rhs file is allowed with --graver and --hilbert!\n");
						printf("Input Error: Please delete %s.rhs and rerun zsolve\n", BaseName);
						if (LogFile)
						{
							fprintf(LogFile, "Input Error: No rhs file is allowed with --graver and --hilbert!\n");
							fprintf(LogFile, "Input Error: Please delete %s.rhs and rerun zsolve\n", BaseName);
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					
					fscanf(stream, "%d", &i);
					if (i!=1)
					{
						fclose(stream);
						printf("Height of RHS must be 1!\n");
						if (LogFile)
						{
							fprintf(LogFile, "Height of RHS must be 1!\n");
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					fscanf(stream, "%d", &i);
					if (i!=matrix->Height)
					{
						fclose(stream);
						printf("Matrix height conflicts with width of rhs!\n");
						if (LogFile)
						{
							fprintf(LogFile, "Matrix height conflicts with width of rhs!\n");
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
					rhs = readVector(stream, matrix->Height);
					fclose(stream);
					if (rhs==NULL)
					{
						printf("RHS file %s.rhs does not contain valid data.\n", BaseName);
						if (LogFile)
						{
							fprintf(LogFile, "RHS file %s.rhs does not contain valid data.\n", BaseName);
							fclose(LogFile);
						}
						deleteMatrix(matrix);
						free(BaseName);
						exit(1);
					}
				}
			}

			// fill with zeros
			if (rhs==NULL)
			{
				rhs = createVector(matrix->Height);
				for (i=0; i<matrix->Height; i++)
					rhs[i] = 0;
			}

			// create system
			initialsystem = createLinearSystem();
	
			setLinearSystemMatrix(initialsystem, matrix);
			deleteMatrix(matrix);

			setLinearSystemRHS(initialsystem, rhs);
			deleteVector(rhs);

			// default limits

			if (OGraver)
				setLinearSystemLimit(initialsystem, -1, -MAXINT, MAXINT, false);
			else if (OHilbert)
				setLinearSystemLimit(initialsystem, -1, 0, MAXINT, false);
			else
				setLinearSystemLimit(initialsystem, -1, -MAXINT, MAXINT, true);
	
			// default equation type

			setLinearSystemEquationType(initialsystem, -1, EQUATION_EQUAL, 0);

			// read .rel
			strcat(BaseName, ".rel");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;

				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Equations || r != 1)
				{
					printf("RELATION file %s.rel must start with '1 %d'.\n", BaseName, initialsystem->Equations);
					flag = true;
				}

				for (i=0; i<initialsystem->Equations; i++)
				{
					if (readTokenFromFile(stream, "0123456789=<>", &token, &memory) == 0)
					{
						printf("RELATION file %s.rel ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "="))
						setLinearSystemEquationType(initialsystem, i, EQUATION_EQUAL, 0);
					// BUG: Not a real bug, but maybe misdefinition?? <= is not so hard to type :-)
					else if (!strcmp(token, "<"))
						setLinearSystemEquationType(initialsystem, i, EQUATION_LESSEREQUAL, 0);
					else if (!strcmp(token, ">"))
						setLinearSystemEquationType(initialsystem, i, EQUATION_GREATEREQUAL, 0);
					else
					{
						printf("Unknown token '%s' in RELATION file %s.rel.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);

				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .sign
			strcat(BaseName, ".sign");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;

				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("SIGN file %s.sign must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789-abcdefghijklmnopqrstuvwxyz", &token, &memory) == 0)
					{
						printf("SIGN file %s.sign ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "0") || !strcmp(token, "free") || !strcmp(token, "f"))
						setLinearSystemLimit(initialsystem, i, -MAXINT, MAXINT, true);
					else if (!strcmp(token, "1") || !strcmp(token, "hil") || !strcmp(token, "h"))
						setLinearSystemLimit(initialsystem, i, 0, MAXINT, false);
					else if (!strcmp(token, "-1") || !strcmp(token, "-hil") || !strcmp(token, "-h"))
						setLinearSystemLimit(initialsystem, i, -MAXINT, 0, false);
					else if (!strcmp(token, "2") || !strcmp(token, "graver") || !strcmp(token, "g"))
					{
						if (OHilbert)
						{
							if (!flag)
								printf("Input Error: Graver components for `hilbert' executable.\nInput Error: Use the `graver' executable instead.\n");
							flag = true;
						}
						else
							setLinearSystemLimit(initialsystem, i, -MAXINT, MAXINT, false);
					}
					else
					{
						printf("Unknown token '%s' in SIGN file %s.sign.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);

				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .ub
			strcat(BaseName, ".ub");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;
	
				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("UPPER BOUNDS file %s.ub must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
					{
						printf("UPPER BOUNDS file %s.ub ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "*"))
						setLinearSystemBound(initialsystem, i, 'u', MAXINT);
					else if (sscanf(token, "%d", &j) == 1)
					{
						if (initialsystem->VarProperties[i].Free)
						{
							printf("Upper bound '%s' cannot be set for free variables.\n", token);
							flag = true;
						}
						else if (j>=0)
							setLinearSystemBound(initialsystem, i, 'u', j);
						else
						{
							printf("Negative upper bound '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
							flag = true;
						}
					}
					else
					{
						printf("Unknown token '%s' in UPPER BOUNDS file %s.ub.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);
	
				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			// read .lb
			strcat(BaseName, ".lb");
			stream = fopen(BaseName, "r");
			BaseName[BaseLength] = '\0';
			if (stream!=NULL)
			{
				token = NULL;
				memory = 0;
				flag = false;
	
				if (fscanf(stream, "%d %d", &r, &i)<2 || i != initialsystem->Variables || r != 1)
				{
					printf("LOWER BOUNDS file %s.lb must start with '1 %d'.\n", BaseName, initialsystem->Variables);
					flag = true;
				}

				for (i=0; i<initialsystem->Variables; i++)
				{
					if (readTokenFromFile(stream, "0123456789*-", &token, &memory) == 0)
					{
						printf("LOWER BOUNDS file %s.lb ends unexpectedly.\n", BaseName);
						flag = true;
					}
					if (!strcmp(token, "*"))
						setLinearSystemBound(initialsystem, i, 'l', -MAXINT);
					else if (sscanf(token, "%d", &j) == 1)
					{
						if (initialsystem->VarProperties[i].Free)
						{
							printf("Lower bound '%s' cannot be set for free variables.\n", token);
							flag = true;
						}
						else if (j<=0)
							setLinearSystemBound(initialsystem, i, 'l', j);
						else
						{
							printf("Positive lower bound '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
							flag = true;
						}
					}
					else
					{
						printf("Unknown token '%s' in LOWER BOUNDS file %s.lb.\n", token, BaseName);
						flag = true;
					}
				}
				free(token);
				fclose(stream);
	
				if (flag)
				{
					deleteLinearSystem(initialsystem);
					free(BaseName);
					exit(1);
				}
			}

			ctx = createZSolveContextFromSystem(initialsystem, LogFile, OLogging, OVerbose, zsolveLogCallbackDefault, backupEvent);
	
			// END OF SYSTEM SECTION
		}
	}

	// DEBUG
//	printVectorArray(ctx->Lattice, true);

	zsolveSystem(ctx, !OResume);

	if (OGraver)
	{
		printf("Writing %d vectors to graver file, with respect to symmetry.\n", ctx->Graver->Size);
		if (LogFile)
			fprintf(LogFile, "Writing %d vectors to graver file, with respect to symmetry.\n", ctx->Graver->Size);
		
		strcat(BaseName, ".gra");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Graver->Size, ctx->Graver->Variables);
			fprintVectorArray(stream, ctx->Graver, false);
			fclose(stream);
		}
	}
	else if (OHilbert)
	{
		strcat(BaseName, ".hil");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Homs->Size + ctx->Frees->Size, ctx->Homs->Variables);
			fprintVectorArray(stream, ctx->Homs, false);
			fprintf(stream, "\n");
			fprintVectorArray(stream, ctx->Frees, false);
			fclose(stream);
		}
	}
	else
	{
		strcat(BaseName, ".zinhom");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Inhoms->Size, ctx->Inhoms->Variables);
			fprintVectorArray(stream, ctx->Inhoms, false);
			fclose(stream);
		}

		strcat(BaseName, ".zhom");
		stream = fopen(BaseName, "w");
		BaseName[BaseLength] = '\0';
		if (stream)
		{
			fprintf(stream, "%d %d\n\n", ctx->Homs->Size, ctx->Homs->Variables);
			fprintVectorArray(stream, ctx->Homs, false);
			fclose(stream);
		}

		if (ctx->Frees->Size>0)
		{
			strcat(BaseName, ".zfree");
			stream = fopen(BaseName, "w");
			BaseName[BaseLength] = '\0';
			if (stream)
			{
				fprintf(stream, "%d %d\n\n", ctx->Frees->Size, ctx->Frees->Variables);
				fprintVectorArray(stream, ctx->Frees, false);
				fclose(stream);
			}
		}
	}


	printf("\n4ti2 Total Time: ");
	printCPUTime(maxd(getCPUTime() - ctx->AllTime, 0.0));
	printf("\n");
	if (LogFile) {
		fprintf(LogFile, "\n4ti2 Total Time: ");
		fprintCPUTime(LogFile, maxd(getCPUTime() - ctx->AllTime, 0.0));
		fprintf(LogFile, "\n");
	}

	deleteZSolveContext(ctx, true);

	if (BaseName!=NULL)
		free(BaseName);

	if (LogFile)
		fclose(LogFile);

	return EXIT_SUCCESS;
}
Exemple #13
0
int main(int argc,char** argv)
{

	totalStartTime = getCPUTime();
	//endTime = getCPUTime();
	printf("start POR extract...\n");
	char * filename = argv[1];
    FILE *fp1,*fp2,*temp_fp;
	//open encoded file for reading
  	if ((fp1 = fopen(argv[1], "r")) == NULL){
        printf("couldn't open input file for reading.\n");
        return -1;
        }
    
	int p;
	//t = atoi(argv[3]);
	unsigned long fileLen;
	fseek(fp1,0,SEEK_END);
	fileLen = ftell(fp1);
	t = (fileLen-16-oldq*BLOCK_SIZE) / BLOCK_SIZE;
	m = t*k/n;
	printf("extract for file \"%s\" with size=%lu m=%lu and t=%lu\n",filename,fileLen,m,t);
	//use master key and call keygen to generate all the keys here.	
	master_keygen(argv[2]);
	
	//read mac from the end of the old file	
	unsigned char originalmac[16];
	int bufLength=16;
	readStartTime = getCPUTime();
	fseek(fp1, fileLen-bufLength, SEEK_SET);
	fread(originalmac, sizeof(originalmac), 1, fp1);
	readEndTime = getCPUTime();
	readTime += readEndTime-readStartTime;
	printf("\nMAC attached at the end of the file: ");
	displayCharArray(originalmac,16);
	
	if (checkFile(fp1,originalmac)==0) {
		printf("File is intact.\n");
		fclose(fp1);
		totalEndTime = getCPUTime();
		totalTime = totalEndTime - totalStartTime;
		printf("#RESULT#\n");
		printf("%lf\n",totalTime);
		printf("%lf\n",readTime);
		printf("%lf\n",prpTime);
		printf("%lf\n",eccTime);
		printf("%lf\n",macTime);
		printf("%lf\n",chalTime);
		printf("%lf\n",writeTime);
		exit(0);
	}
	else if (initial_outer_decoding(fp1,originalmac)==0){
		//initial_outer_decoding(fp1, newfp);
		//if (checkFile(newfp,originalmac)==0) {
			printf("File is recovered after outer encoding.\n");
			fclose(fp1);
			totalEndTime = getCPUTime();
			totalTime = totalEndTime - totalStartTime;
			printf("#RESULT#\n");
			printf("%lf\n",totalTime);
			printf("%lf\n",readTime);
			printf("%lf\n",prpTime);
			printf("%lf\n",eccTime);
			printf("%lf\n",macTime);
			printf("%lf\n",chalTime);
			printf("%lf\n",writeTime);
			exit(0);
		//}
	}
	//else {
		//printf("File is corrupted.\n");
		//exit(0);
	//}
	int tempv = v;
	q = alpha * t / tempv;
	decoded_blocks * db;
	unsigned int i,j,u,size,index;
	char * codeword,mac;
	chal c[q];
	unsigned char k_j_c[16]; 
	char str[999]; 
	char * temp_block;
	// after writing new file, delete old file

	char * r_file="recovered";
	char * temp ="temp";
	unsigned int * v_chal_indices;


	//open output file for writing
	if ((fp2 = fopen(r_file, "w+")) == NULL){
	         printf("couldn't open output file for writing.\n");
	         return -1;
    }

	//open temp file for writing
	if ((temp_fp = fopen(temp, "w+")) == NULL){
	         printf("couldn't open temperory file for writing.\n");
	         return -1;
    	}

	//allocate memory for d1
	db = malloc (sizeof(struct d_b)*t);  
	//for(i=0;i<t;i++) {
	//	printf("for db[%d], sizeof frequency=%lu\n",i,sizeof(db[i].frequency));
	//	printf("display frequency[5] %d\n",db[i].frequency[5]);
	//}
	if(db == NULL) {
		printf("failed to allocate memory for d.\n");
		return -1;
	}

	//total number of challenges		
	size = alpha*(t/v); 

	//allocate memory for the challenge set
	//if ((c = (chal *)malloc(sizeof(chal)*size))== NULL) {
	//	fprintf(stderr, "failed to allocate memory for challenges.\n");
	//	return -1;
	//}
	
	// populate challenge set
	printf("\nstart inner layer decoding...\n");
	printf("generate %lu challenges\n",q);
	keygen_init();
	seeding(k_chal);	
	for (j=0;j<q;j++){
		keygen(c[j].k_j_c, 16);
		c[j].j = j;
	}
	printf("kjc for each challenge generated\n");
	
    // for each challenge
	for (i=0;i<q;i++){
		
		//unsigned char * codeword = (unsigned char *) malloc(sizeof(unsigned char)*32*w);
		unsigned char codeword[32*w];
		unsigned long indices[v];

		index = 0;
		//execute each challenge w times
		for(u=0;u<w;u++){
			unsigned char * subcode = execute_challenge(fp1,c[i].j, c[i].k_j_c, u, indices);
			//printf("%d-th sub code\n",u);
			//displayCharArray(subcode,32);
			int tempI;
			for(tempI=0;tempI<32;tempI++)
				codeword[index++] = subcode[tempI];
		}
		//printf("codeword for challenge #%d\n",i);
		//displayCharArray(codeword,4096);
		// inner code decoding
		printf("start decoding for challenge #%d\n",i);
		inner_GMD(db,codeword,indices,fp1); 
		printf("finish decoding for challenge %d\n",i);

		//free the memory
		//free(codeword);
		//free(indices);

		//delete old file
			
		//remove(filename);
	}
	
	for (i=0;i<t;i++){
		int max_frequency=0;
		int max_index=0;
		
		for(j=0;j<sizeof(db[i].frequency);j++){
			if(db[i].frequency[j] > max_frequency){
				max_frequency = db[i].frequency[j];
				max_index = j;
			}
		}
		if(max_frequency==0) {
			fseek(fp1,i*32,SEEK_SET);
			unsigned char buffer[32];
			fread(buffer, 32, 1, fp1);
			fwrite(buffer,32,1,temp_fp);
		 }
		else {
		//check if the location can be corrected or has erasure 
		if(ceil(max_frequency / sizeof(db[i].frequency)) > (delta+0.5)){
			fwrite(db[i].file_blocks[max_index],32,1,temp_fp);
		}else{
			fwrite(db[i].file_blocks[max_index],32,1,temp_fp);
			//where to get the index from
			//db[i].file_blocks[0]=NULL;
	
			//-1 indicating erasure
			db[i].frequency[0]=-1;
		}
        }
	}
    fclose(fp1);
	fclose(temp_fp);
	
	//perform outer decoding
	//outer_decoding(temp_fp,fp2,db);
	
	//compute mac
	unsigned char newmac[16]; 
	//hmac("temp",newmac,k_mac);
    //printf("display MAC\n");
    //displayCharArray(newmac,16);
	
	//if verified, print the file. Else output the error
	int flag=1;	
	for(i=0;i<MACSIZE;i++){
		if(newmac[i]!=originalmac[i]){	
			flag=0;
			break;
		}
	}
	if (flag==1){
		printf("Your file is recovered\n");
    		//while (fscanf(fp2, "%s", str)!=EOF){
        //		printf("%s",str);
		//}
	}else{
		printf("Your file can not be recovered.\n");
		//return -1;
	}

	fclose(fp2);
    printf("#RESULT#\n");
    printf("%lf\n",totalTime);
    printf("%lf\n",readTime);
    printf("%lf\n",prpTime);
    printf("%lf\n",eccTime);
    printf("%lf\n",macTime);
    printf("%lf\n",chalTime);
    printf("%lf\n",writeTime);

	return 0;
}
Exemple #14
0
int main(int argc, char *argv[])
{

	//second argument is the file name to be permuted
	//atoi converted string to integer, we get the file size directly.
	if (argv[1])
    	blocks = atoi(argv[1]);
    else {
    	printf("passing block number as parameter\n");
    	exit(0);
    }
    	//printf("file size: %dG\n",filesize);
	
	//calculate blocklength 30 - 5 = 25 ( 2^30 stands for 1 gb, 2^5 for 32 bytes)
	//int temp = log2(GB) - log2(BLOCK_LENGTH);
	
    	//blocks = filesize * (1<<temp);
    	printf("block num: %d\n",blocks);
    	fflush(stdout);

	//find the bit length  of the each element of array to get number of blocks
	index_bit_length = log2(blocks);
	int bit = ceil(index_bit_length);
	    	printf("bit num: %d\n",bit);
	//declare for block indices table, and permuted indices table
	int * blockindices;
	int * prpblockindices;
	//allocate memory for input and output table
    	blockindices = (int *)malloc(blocks*sizeof(int));
    	prpblockindices = (int *)malloc(blocks*sizeof(int));

	//initialize block array to the block indices
    	int j=0;
	int i;
    	for (i=0;i<blocks;i++) {
		blockindices[i] = i;
    	}
	
	//hardcoding 6 seeds
	unsigned char * seed1 = "jiedai";
	unsigned char * seed2 = "ruchashintre";
	unsigned char * seed3 = "poojadesai";
	unsigned char * seed4 = "CMUMSE";
	unsigned char * seed5 = "BOSCH";
	unsigned char * seed6 = "jorge";
    double startTime, endTime;
    startTime = getCPUTime();
	//Generate 6 functions
	round1table = malloc(blocks*sizeof(unsigned int));
	generateRoundFunctions(seed1,round1table,blocks);
	round2table = malloc(blocks*sizeof(unsigned int));
	generateRoundFunctions(seed2,round2table,blocks);
	round3table = malloc(blocks*sizeof(unsigned int));
	generateRoundFunctions(seed3,round3table,blocks);
	round4table = malloc(blocks*sizeof(unsigned int));	
	generateRoundFunctions(seed4,round4table,blocks);
	round5table = malloc(blocks*sizeof(unsigned int));
	generateRoundFunctions(seed5,round5table,blocks);
	round6table = malloc(blocks*sizeof(unsigned int));
	generateRoundFunctions(seed6,round6table,blocks);
	printf("6 tables generated");
    endTime = getCPUTime();
    fprintf( stderr, "CPU time used for PRNG = %lf\n", (endTime - startTime) );
    
    startTime = getCPUTime();
	//using setting in the paper: change it later, to calculate a and b
	int a = ceil(sqrt(blocks));
	int b = ceil(sqrt(blocks))+1;
	printf("a=%d,b=%d\n",a,b);
	//get the keys for permutation
	
	//unsigned char * keyseed = "anappleadaykeepsadoctoraway";
	//int key = genkey(keyseed);
	
	//do this for six rounds
	for(i=0;i<blocks;i++){
		prpblockindices[i]=Fe(NOOFROUNDS, a, b,i, blocks, bit);
	}
	
	//for(i=0;i<blocks;i++){
		//printf("%d -> %d\n", blockindices[i], prpblockindices[i]);		
	//}
		printf("a=%d,b=%d\n",a,b);
		    endTime = getCPUTime();
    fprintf( stderr, "CPU time used for PRP = %lf\n", (endTime - startTime) );
}
Exemple #15
0
void sysBpHandler(){
	saveStateIn(sysbp_old, &currentProcess->p_s);
	unsigned int cause = CAUSE_EXCCODE_GET(sysbp_old->CP15_Cause);
	unsigned int a0 = (*sysbp_old).a1;
	unsigned int a1 = (*sysbp_old).a2;
	unsigned int a2 = (*sysbp_old).a3;
	unsigned int a3 = (*sysbp_old).a4;
	/* Se l'eccezione è di tipo System call */
	if(cause==EXC_SYSCALL){
    	/* Se il processo è in kernel mode gestisce adeguatamente */
    	if( (currentProcess->p_s.cpsr & STATUS_SYS_MODE) == STATUS_SYS_MODE){
			/* Se è fra SYS1 e SYS8 richiama le funzioni adeguate */
			switch(a0){
			    case CREATEPROCESS:
			        createProcess((state_t *) a1);
			        break;
			    case TERMINATEPROCESS:
			        terminateProcess(currentProcess);
			        break;
		        case VERHOGEN:
		            verhogen((int *) a1);
			        break;
		        case PASSEREN:
		            passeren((int *) a1);
			        break;
		        case SPECTRAPVEC:
		            specExStVec((int) a1, (state_t *) a2, (state_t *) a3);
			        break;
		        case GETCPUTIME:
		            getCPUTime();
			        break;
		        case WAITCLOCK:
		            waitForClock();
			        break;
		        case WAITIO:
		            waitForIO((int) a1, (int) a2, (int) a3);
			        break;
			    /* Altrimenti la gestione viene passata in alto */
			    default:
			        useExStVec(SPECSYSBP);
				break;            
			}
			
		    /* Richiamo lo scheduler */
		    scheduler();
		/* Se invece è in user mode */
		} else if((currentProcess->p_s.cpsr & STATUS_USER_MODE) == STATUS_USER_MODE){
			/* Se è una system call */
			if(a0 >= CREATEPROCESS && a0 <= WAITIO){
			    /* Gestisco come fosse una program trap */
			    saveStateIn(sysbp_old, pgmtrap_old);
			    /* Setto il registro cause a Reserved Instruction */
			    pgmtrap_old->CP15_Cause = CAUSE_EXCCODE_SET(pgmtrap_old->CP15_Cause, EXC_RESERVEDINSTR);
			    /* Richiamo l'handler per le pgmtrap */
			    pgmHandler();
			} else {
				useExStVec(SPECSYSBP);
			}
		}
	/* Altrimenti se l'eccezione è di tipo BreakPoint */
	} else if(cause == EXC_BREAKPOINT){
		useExStVec(SPECSYSBP);
	}

	PANIC();
}
Exemple #16
0
int outer_decoding(FILE* orifp, FILE* parifp, FILE *output, FILE* tempfp, decoded_blocks *db)
{
	int i,j,stripes,fileLen,index;
	int* prp_table;
	int* reverse_prp_table;
	char message[k];
	char codeword[n];

	//unsigned char decodedfile[stripes][k];
	int erasure[1];
	//FILE* tempfp = fopen("tempfile", "w+b");
	if (tempfp  == NULL){
 		printf("couldn't open temperory file for writing.\n");
 		return -1;
    	}

	//find the number of stripes in the file 
	fseek(parifp,0,SEEK_END);
	fileLen = ftell(parifp);
	printf("display fileLen of parity %d\n",fileLen);
	//if(fileLen % n==0) 
		stripes = fileLen/d; 
	//else
		//stripes = fileLen/n+1;
	printf("number of stripes for outer decoding %d\n",stripes);
	fflush(stdout);
	unsigned char ** parity;//[stripes][d]; 
	parity = (unsigned char **) malloc(stripes*sizeof(unsigned char *));  
	for (i = 0; i < stripes; i++) {
   	parity[i] = (unsigned char *) malloc(d*sizeof(unsigned char));  
   	}
	//call prp
	prp_table =malloc(sizeof(int)*stripes);
	reverse_prp_table = malloc(sizeof(int)*stripes);
	
	//perform reverse prp
	prp_table = prp(stripes, k_ecc_perm);
	reverseprp(stripes,prp_table,reverse_prp_table);
	/*for(i=0;i<stripes;i++){
		printf("prp %d: %d\n",i,prp_table[i]);
		printf("rev prp %d: %d\n",i,reverse_prp_table[i]);
	}*/
	//free(prp_table);
	printf("check1\n");
	enc_init(k_ecc_enc);
	
	//decrypt parity part
	rewind(parifp);
	rewind(orifp);
	///number of parity blocks = stripes/2
	//read parity parts directly

	//int parity_start = fileLen-(stripes/2)*d;
	//fseek(temp_fp,parity_start,SEEK_SET);
	unsigned char paritybytes[stripes][d];
	for (i=0;i<stripes;i++) {
		unsigned char ct[d];
		//unsigned char pt[d];	
		
		fread(ct,sizeof(ct),1,parifp);
		
		decrypt(ct,paritybytes[prp_table[i]],sizeof(ct)); 
		//printf("prp rev for %d: ",i);
		//displayCharArray(paritybytes[i],sizeof(ct));
		//for(j=0;j<d;j++){
		//	parity[i][j]=ct[j];
		//}
	}
	for (i=0;i<stripes;i++) {
		printf("prp rev for %d: ",i);
		displayCharArray(paritybytes[i],sizeof(paritybytes[i]));
	}
	free(reverse_prp_table);
	reverse_prp_table = malloc(sizeof(int)*m);
	prp_table =malloc(sizeof(int)*m);
	prp_table = prp(m, k_file_perm);
	reverseprp(m,prp_table,reverse_prp_table);
	//get the message and the parity, create codeword and decode it
	//rewind(temp_fp);
	FILE * prp = fopen("prp","w+b");
	for(i=0;i<m;i++) {
		unsigned char prpbuf[BLOCK_SIZE];
		fseek(orifp,prp_table[i]*32,SEEK_SET);
		size_t br = fread(prpbuf,1,BLOCK_SIZE,orifp);
		fwrite(prpbuf,1,BLOCK_SIZE,prp);
	}
	fclose(prp);
	prp = fopen("prp","r+b");
	for(i=0;i<stripes;i++) {
		index=0;
		unsigned char code[n];

		size_t br = fread(code,1,k,prp);
		int pad = k-br;
		int ii;
		for (ii=0;ii<pad;ii++)
			code[br+ii] = 0;
			
		for(j=0;j<d;j++) {
			code[k+j] = paritybytes[i][j]; 
		}
		printf("whole code %d: ",i);
		displayCharArray(code,n);
		decode_data(code, n);
		int syn = check_syndrome ();
		printf("syndrome: %d\n",syn);
		if (syn != 0) {
			correct_errors_erasures(code,n,0,erasure);
		}
		printf("decoded code %d: ",i);
		displayCharArray(code,n);
		//calculate block index of the parity part
		fwrite(code,1,br,tempfp);
	}
	fclose(tempfp);
	for (i = 0; i < stripes; i++){  
   	free(parity[i]);  
	}  
	free(parity);
	if ((tempfp = fopen("tempfile", "r+b")) == NULL){
 		printf("couldn't open temperory file for writing.\n");
 		return -1;
    	}
	// write data to the file by applying second level of permutation
	//free(prp_table);
	//free(reverse_prp_table);
	//printf("display m = %lu\n",m);

	rewind(tempfp);
	rewind(output);
	unsigned char buf[BLOCK_SIZE];
	for(i=0;i<m;i++) {
		readStartTime = getCPUTime();
		fseek(tempfp,reverse_prp_table[i]*32,SEEK_SET);
		fread(buf, BLOCK_SIZE, 1, tempfp);
		readEndTime = getCPUTime();
		readTime += readEndTime-readStartTime;
		writeStartTime = getCPUTime();
   	fwrite(buf,BLOCK_SIZE,1,output);
      	writeEndTime = getCPUTime();
		writeTime += writeEndTime-writeStartTime;		
	}
	printf("check4\n");
	fclose(tempfp);
	fclose(output);
	fclose(orifp);
	fclose(parifp);
	printf("check5\n");
	//delete(temp_fp);
	return 0;
}
Exemple #17
0
int main(int argc, char* argv[])
{
    totalStartTime = getCPUTime();
    printf("%lf\n",totalStartTime);
	int i;
	FILE* fp = fopen(argv[1],"a+b");
	if (fp==NULL) {
		printf("fopen error: cannot open file\n");
		exit(1);
	}
	int* prptable;
	unsigned char mac[MAXBLOCKSIZE];
    unsigned long fileLen1,fileLen2;
    // get the file size
	fseek(fp,0,SEEK_END);
	fileLen1 = ftell(fp);
    // generate keys
	master_keygen(argv[2]);

	printf("key for file permutation: ");
	displayCharArray(k_file_perm,16);

	printf("key for ecc permutation: ");
	displayCharArray(k_ecc_perm,16);

	printf("key for ecc encryption: ");
	displayCharArray(k_ecc_enc,16);

	printf("key for challenge generation: ");
	displayCharArray(k_chal,16);

	printf("key for random index generation: ");
	displayCharArray(k_ind,16);

	printf("key for response encryption: ");
	displayCharArray(k_enc,16);

	printf("key for MAC computation: ");
	displayCharArray(k_mac,16);	
	
    // blockize the file
	int blocks = blockize(fp);
	t = blocks;
	fclose(fp);
    fp = fopen(argv[1],"a+b");
    
    // computing MAC
	printf("\nComputing file's MAC...\n");
		printf("\nmac size %lu\n",sizeof(mac));
    macStartTime = getCPUTime();
	hmac(argv[1],mac,k_mac);
    macTime = getCPUTime() - macStartTime;
	printf("\nMAC = ");
	displayCharArray(mac,16);	
	
    // perform a file level PRP
	printf("\nSRF PRP for the entire file...\n");
    prpStartTime = getCPUTime();
	prptable = prp(blocks, k_file_perm);
    prpTime += getCPUTime() - prpStartTime;
    eccStartTime = getCPUTime();
	initialize_ecc();
	inc_encoding(fp,prptable);
    eccTime = getCPUTime() - eccStartTime - readTime;
	
	printf("\nFile blocks after outer layer encoding: %lu\n",t);

    // precompute q challenge and responsess
	printf("\nPrecomputation for %d challenges and responses\n",q);
    chalStartTime = getCPUTime();
	Chal c[q];
	int j,p;
    // use k_chal to generate kjc
	keygen_init();
	seeding(k_chal);
	unsigned char * kjc[q];
	for(j=0;j<q;j++) {
		kjc[j] = malloc(16*sizeof(unsigned char *));
		keygen(kjc[j], 16);
	}
    // use kjc to generate random indices
	for(j=0;j<q;j++) {
		keygen_init();
		seeding(kjc[j]);
		for(p=0;p<v;p++) {
			unsigned long randomIndex;
			char rand[8];
			keygen(rand, 8);
			randomIndex = *(unsigned long *)rand;	
			c[j].s[p] = randomIndex % t;
		}
	}
    // use k_ind to generate random index u
	keygen_init();
	seeding(k_ind);	
	for(j=0;j<q;j++) {
		unsigned int randomIndex;
		char rand[4];
		keygen(rand, 4);
		randomIndex = *(unsigned int *)rand;	
		c[j].u = randomIndex % w;
	}
	printf("Precomputation for challenges finishes\n");
    // precompute challenge responses
	precompute_response(fp,c,k_enc);
	printf("Precomputation for responses finishes\n");
    chalTime+=getCPUTime()-chalStartTime - write2Time;
    // append MAC at the end of the files
	printf("\nAppend MAC to the end of the file...\n");
    write2StartTime = getCPUTime();
    clock_gettime(CLOCK_MONOTONIC, &start);
	fwrite(mac,16,1,fp);
    clock_gettime(CLOCK_MONOTONIC, &finish);
    double addTime = finish.tv_sec - start.tv_sec;
    addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
    write2Time += getCPUTime() - write2StartTime+addTime;
    fseek(fp,0,SEEK_END);
	fileLen2 = ftell(fp);
	fclose(fp);

	printf("\nPOR encoding done\n");

	// display time performance
    totalTime = getCPUTime() - totalStartTime;
    printf("#RESULT#\n");
    printf("%lu\n",fileLen1);
    printf("%lu\n",fileLen2);
    printf("%lf\n",totalTime);
    printf("%lf\n",readTime);
    printf("%lf\n",prpTime);
    printf("%lf\n",eccTime);
    printf("%lf\n",macTime);
    printf("%lf\n",chalTime);
    printf("%lf\n",write1Time+write2Time);
    printf("%lf\n",encTime);


}
int main()
{

  double startTime;
  double endTime;
  double ElapsedTime;

    sorter_data_t data[NUM_ELE];
    sorter_data_t out_data[NUM_ELE];
    sorter_data_t orig_data[NUM_ELE];
    sorter_data_t *data_p;
    bool i_state  = 0;


     for (int itn = 0; itn < NUM_ITR; itn++) {
        if (itn == 0) {
            for(int i=0;i<NUM_ELE;++i)
            {
                if (i == (NUM_ELE-1)) {
                    orig_data[i] = 111.32;
                } else if (i == 0) {
                    orig_data[i] = -55.45;
                } else {
                    if (i_state) {
                        orig_data[i] = ((float)i/2.3);
                    } else {
                        orig_data[i] = ((float)i/-2.3);
                    }
                }
                data[i] = orig_data[i];
                out_data[i] = 0; 
                i_state = not i_state;
            }
        } else {
            for(int i=0;i<NUM_ELE;++i)
            {
                if (i == (NUM_ELE-1)) {
                    orig_data[i] = 111.32;
                } else if (i == 0) {
                    orig_data[i] = -55.45;
                } else {
                    if (i_state) {
                        orig_data[i] = ((float)i*itn)/2.3;
                    } else {
                        orig_data[i] = ((float)i*itn)/-2.3;
                    }
                }
                data[i] = orig_data[i];
                out_data[i] = 0; 
                i_state = not i_state;
            }
        }
        //my_bubble_sorter.bubble_sort(data, out_data);
        startTime = getCPUTime();
        //-----------------------------------------------
        bubble_sort_wrapper(data, out_data);
        printf("In ascending order: \n");
        //-----------------------------------------------
        endTime = getCPUTime();
        ElapsedTime = (endTime - startTime);
        for(int i=0;i<NUM_ELE;++i)
             printf("%f :: %f \n",(float)orig_data[i], (float)out_data[i]);
             printf("\n");
        printf (" Elapsed Time for algorithm = %1f sec\n", ElapsedTime);
    }
    return 0;
}
Exemple #19
0
// outer layer ECC using incremental encoding
int inc_encoding (FILE* fp,int* prptable)
{
	printf("\nIncremental encoding starts...\n");
	int i,j,enc_blocks,d=n-k;
	// get file length
	fseek(fp,0,SEEK_END);
	fileLen = ftell(fp);
	// divide by message length k, get number of encoding blocks
	if(fileLen % k==0) 
		enc_blocks = fileLen/k;
	else
		enc_blocks = fileLen/k+1;
	printf("There are %d encoding blocks\n",enc_blocks);
	unsigned char message[k];
	unsigned char codeword[n];
	unsigned char ** code; // used to store parity part
	
	long filecounter = 0;
	int blockcounter = 0;
	int round = 0;

	// code is enc_blocks * d
	code = (unsigned char **) malloc(enc_blocks*sizeof(unsigned char *));  
	for (i = 0; i < enc_blocks; i++) {
   	code[i] = (unsigned char *) malloc(d*sizeof(unsigned char)); 
   	int ii;
   	for (ii=0;ii<d;ii++)
   		code[i][ii]=0; 
   	}
   	

   rewind(fp);
	while (!feof(fp))
	{
		unsigned char * buf; 
		if ((buf = malloc(sizeof(unsigned char)*readLen))==NULL) {
			printf("malloc error: inc_encoding\n");
			exit(1);
		}
		// incremental encoding, read reaLen each time
		readStartTime = getCPUTime();
		clock_gettime(CLOCK_MONOTONIC, &start);
		printf("max read in %d bytes\n",readLen);
		size_t br = fread(buf, 1, readLen, fp);
		printf("Read in %lu bytes\n",br);
		fflush(stdout);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		readTime += getCPUTime() - readStartTime+addTime;
		// keep a counter to know where the file pointer up to
		filecounter = filecounter + br;
		if (br!=0) {
			printf("round %d\n",round);
			printf("filecounter = %lu\n",filecounter);
			for(i=0;i<enc_blocks;i++) {
				for(j=0;j<k;j++) {
					// for each byte in each message, compute index
					int index = i*k+j;
					// get block and byte index
					int block_index = index/BLOCK_SIZE;
					int byte_index = index%BLOCK_SIZE;
					// if reach the end, padding 0s
					if (index>=fileLen) {
						int a;
						for(a=j;a<k;a++)
							message[a]=0;
						break;
					}
					// compute the PRPed index in the file
					unsigned long file_index = prptable[block_index]*BLOCK_SIZE+byte_index;
					
					// check if this byte is read in the memory or not, copy if yes, put 0 otherwise
					if(file_index<filecounter && file_index>=(filecounter-br)) {
						unsigned long newind = file_index-filecounter+br;
						message[j] = buf[newind];
					}
					else 
						message[j] = 0;
				}
				//printf("msg for block %d: ",i);
				//displayCharArray(message,k);
				// do a partial encoding on the message
				encode_data(message,k,codeword);
				// concatenate with previous code to get a whole
				/*printf("code for block %d: ",i);
				displayCharArray(codeword,n);
				printf("parity (before) for block %d: ",i);
				displayCharArray(code[i],n-k);*/
				for(j=0;j<d;j++)
					code[i][j] = code[i][j] ^ codeword[k+j];
				//printf("parity for block %d: ",i);
				//displayCharArray(code[i],n-k);
				//printf("\n");
			}
			round = round + 1;
		}
		free(buf);
	}
	/*// ------------- for debugging
	unsigned char a[fileLen],r[fileLen];
	unsigned char newc[n],newm[k];
	rewind(fp);
	fread(a, 1, fileLen, fp);
	printf("original:\n");
	for (i=0;i<fileLen;i++) {
		printf("%02x",a[i]);
	}
	printf("\n");
	for (i=0;i<fileLen/32;i++) {
		for (j=0;j<32;j++) {
			r[i*32+j] = a[prptable[i]*32+j];
		}
	}
	printf("prped:\n");
	for (i=0;i<fileLen;i++) {
		printf("%02x",r[i]);
	}
	printf("\n");
	for (i=0;i<enc_blocks;i++) {
		printf("parity part %d: ",i);
		displayCharArray(code[i],d);

		unsigned char newcode[n];
		int iii;
		int ii;
		for(ii=0;ii<k;ii++) {
			if (i*k+ii>=fileLen)
				break;
			newcode[ii] = r[i*k+ii];
			newm[ii] = r[i*k+ii];
		}
		if (i==enc_blocks-1) {
			for(ii=0;ii<k-fileLen%k;ii++){
				newm[fileLen%k+ii]=0;
				newcode[fileLen%k+ii] = 0;
			}
		}
		encode_data(newm,k,newc);
		printf("actual code %d: ",i);
		displayCharArray(newc,n);
		for(iii=0;iii<d;iii++) {
			newcode[k+iii] = code[i][iii];
		}
		newcode[0] = 99;
		printf("whole code %d: ",i);
		displayCharArray(newcode,n);
		decode_data(newcode, n);
		int erasure[1];
		int syn = check_syndrome ();
		printf("syndrome: %d\n",syn);
		if (syn != 0) {
			correct_errors_erasures(newcode,n,0,erasure);
		}
		printf("decode %d: ",i);
		displayCharArray(newcode,n);
	}
	//--------------- for debugging */
	free(prptable);
	prptable = NULL;
	// perform another PRP for parity part
	prptable = malloc(sizeof(int)*(enc_blocks));
	printf("\nSRF PRP for the outer layer ECC...\n");
   prpStartTime = getCPUTime();
	prptable = prp(enc_blocks, k_ecc_perm);
   prpTime += getCPUTime() - prpStartTime;
   
   // encrypt parity part and append to the file with PRPed order
	enc_init(k_ecc_enc);
	for (i=0;i<enc_blocks;i++) {
		unsigned char ct[d];

    	clock_gettime(CLOCK_MONOTONIC, &start);
    	encStartTime = getCPUTime();
		encrypt(ct,code[prptable[i]],sizeof(ct));
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		encTime += getCPUTime()-encStartTime+addTime;

		//printf("encrypted for %d: ",i);
		//displayCharArray(ct,sizeof(ct));
		//unsigned char pt[d];
		//decrypt(ct,pt,sizeof(ct));
		//printf("decrypted for %d: ",i);
		//displayCharArray(pt,sizeof(ct));
    	clock_gettime(CLOCK_MONOTONIC, &start);
		write1StartTime = getCPUTime();
		fwrite(ct,d,1,fp);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
    	write1Time += getCPUTime()-write1StartTime;
	}
	// update t for later challenge computation
	t = t+enc_blocks;
	printf("\nIncremental encoding finishes...\n");
	free(prptable);
	for (i = 0; i < enc_blocks; i++){  
   	free(code[i]);  
	}  
	free(code); 
	return 0;
}
Exemple #20
0
double checkOutCPUTime( void )
{
    double curCPUTime = getCPUTime();
    return ( curCPUTime - startCPUTime );
}
void startTimer_CPU( MTime* mtime )
{
  mtime->type = CPU_CLOCK_TIME;
  mtime->start = getCPUTime();
}
double Game_Engine::Evaluate_Players(int num_repeats, int num_games, int output_depth, Player_Engine** players, bool rotate_starting_player, int return_score_player_num, Tom_Sample_Storage<double>** score_output, int intermediate_output, const int measure_time_per_move, double* winDraw_output_new)
{

	int nextMove, feedback, bestPlayer, multipleWinners;
	double bestOutcome;
	int output_interval, next_output;
	double cpu_time;
	double cpu_time1;
	double scr_out_time;

	//check if players are correctly linked to game, otherwise exit procedure
	players = Validate_Players(players);
	if(players == NULL)
		return -1;

	//assign player IDs
	for (int i = 0; i < number_players; i++){
		players[i]->player_number = i;
	}

	//output depth 1
	if(output_depth >= TOMGAME_OUTPUT_DEPTH1){		
		gmp->Print("\nEval on game %s [%d repeats %d games]", game_name.c_str(), num_repeats, num_games);
		for(int i = 0; i < this->number_players; i++)
			gmp->Print(", Player %d: %s", i+1, players[i]->player_name.c_str());
		gmp->Print(" |");
		if(output_depth == TOMGAME_OUTPUT_DEPTH1){
			output_interval = (int)(num_games*num_repeats/10);
			next_output = output_interval;
		}
	}

	//allocate counters
	int* win_count_total = new int[number_players+1];	//total counter for: draws | player1 | player2 | ...
	int* win_count_local = new int[number_players+1];	//single repeat counter for: draws | player1 | player2 | ...
	double* score_count_total = new double[number_players];
	double* score_count_local = new double[number_players];
	double* players_move_time_sum = new double[number_players];
	int* players_move_count = new int[number_players];

	//initialize counter values
	win_count_total[0] = 0;
	for(int i = 0; i < number_players; i++){
		win_count_total[i+1] = 0;
		score_count_total[i] = 0.0;
		players_move_time_sum[i] = 0.0;
		players_move_count[i] = 0;
	}

	//measure time
	cpu_time = getCPUTime();
	scr_out_time = getCPUTime();

	//execute repeats
	for(batch_repeat_index = 0; batch_repeat_index < num_repeats; batch_repeat_index++){
		
		//reset counter values
		win_count_local[0] = 0;
		for(int i = 0; i < number_players; i++){
			win_count_local[i+1] = 0;
			score_count_local[i] = 0.0;
		}

		//reset players
		for(int i = 0; i < number_players; i++)
			if(players[i]->external_reset_enabled)
				players[i]->Reset();

		//execute games
		for(game_repeat_index = 0; game_repeat_index < num_games; game_repeat_index++){

			//reset game state (start new game)
			Game_New();

			//call new-game procedure for players 
			for(int i = 0; i < number_players; i++)
				players[i]->New_Game();

			//play game until end is signaled
			feedback = game_ended;
			while(feedback == 0){

				//measure move time
				cpu_time1 = getCPUTime();

				//current player selects next move
				nextMove = players[current_player]->Get_Move();
				players_move_count[current_player]++;

				//call before-move procedure for all players
				for(int i = 0; i < number_players; i++){
					players[i]->Before_Move(nextMove);
				}

				//remember cpu time (cumulative sum)
				players_move_time_sum[current_player] += ( getCPUTime()-cpu_time1 );

				//simulate game dynamics with selected move
#if(TOM_DEBUG)
				feedback = Play_Move(nextMove);
#else
				feedback = Play_Move_Unsafe(nextMove);
#endif
				//call after-move procedure for all players
				cpu_time1 = getCPUTime();
				for(int i = 0; i < number_players; i++){
					players[i]->After_Move(nextMove);
				}
				players_move_time_sum[current_player] += ( getCPUTime()-cpu_time1 );
			}

			//calculate score
			Calculate_Score();

			//call end-game procedure for players, game must not be resetted before this call
			for(int i = 0; i < number_players; i++)
				players[i]->End_Game();

			// --- update evaluation statistics ---

			//store score to external data structure
			if(score_output != NULL){			
				score_output[0]->Add_Sample(score[0]);
				score_output[1]->Add_Sample(score[1]);
			}

			//find winning player
			if(number_players == 1){	//single player game
				score_count_total[0] += score[0];
				score_count_local[0] += score[0];
			}else{
				bestOutcome = -DBL_MAX;
				bestPlayer = 0;
				multipleWinners = 1;
				for(int i = 0; i < number_players; i++){
					if(score[i] > bestOutcome){
						bestOutcome = score[i];
						bestPlayer = i;
						multipleWinners = 1;
					}else if(score[i] == bestOutcome){
						multipleWinners++;
					}

					//save score statistics
					score_count_total[i] += score[i];
					score_count_local[i] += score[i];
				}

				//single winner
				if(multipleWinners == 1){
					win_count_total[bestPlayer+1]++;
					win_count_local[bestPlayer+1]++;

				//multiple players with equal highest score
				}else{
					//game ended in draw (all players have equal score)
					if(multipleWinners == number_players){
						win_count_total[0]++;
						win_count_local[0]++;

					//multiple winners
					}else{
						for(int i = 0; i < number_players; i++){
							if(score[i] == bestOutcome){
								win_count_total[i+1]++;
								win_count_local[i+1]++;
							}
						}
					}
				}
			}

			//output depth 3: after each game
			if(output_depth >= TOMGAME_OUTPUT_DEPTH3){
				if(number_players == 1){
					gmp->Print("\nL3 game   | %d\t score %6.5f", game_repeat_index+1, score[0]);
				}else{
					gmp->Print("\nL3 game   | %d\t draws %4d\t wins", game_repeat_index+1, win_count_local[0]);
					for(int i = 0; i < number_players; i++)
						gmp->Print(" %4d", win_count_local[i+1]);
					gmp->Print("\t     scores");
					for(int i = 0; i < number_players; i++)
						gmp->Print(" %6.3f", score[i]);
				}
			}else if(output_depth == TOMGAME_OUTPUT_DEPTH1){
				if(batch_repeat_index*num_games+game_repeat_index >= next_output){
					gmp->Print(".");
					next_output += output_interval;
				}
			}

			if(score_output != NULL){	
				if(intermediate_output > 0){
					if(((score_output[return_score_player_num]->n) % intermediate_output) == 0){
						score_output[return_score_player_num]->Calc_AvgDev();
						score_output[return_score_player_num]->Calc_Confidence();
						gmp->Print("%8d  %6.2f  %6.2f  %6.2f  %9.3f\n",
							score_output[return_score_player_num]->n,
							score_output[return_score_player_num]->avg*100,
							score_output[return_score_player_num]->Calc_Confidence()*100,
							score_output[return_score_player_num]->dev*100,
							getCPUTime()-cpu_time
						);
						if((scr_out_time < 0) || (scr_out_time > TOMGAME_OUTPUT_EVALUATE_INTERMEDIATE_FLUSH_TIMEINTERVAL)){
							gmp->Flush();
						}
						scr_out_time = getCPUTime();
					}
				}
			}
		}
		// END - games

		//output depth 2: after series of games
		if(output_depth >= TOMGAME_OUTPUT_DEPTH2){
			if(number_players == 1){
				gmp->Print("\nL2 REPEAT | %d\t average score %6.5f", batch_repeat_index+1, score_count_local[0] / num_games);
			}else{
				gmp->Print("\nL2 REPEAT | %d\t draws %4d\t wins", batch_repeat_index+1, win_count_local[0]);
				for(int i = 0; i < number_players; i++)
					gmp->Print(" %4d", win_count_local[i+1]);
				gmp->Print("\t sum-scores");
				for(int i = 0; i < number_players; i++)
					gmp->Print(" %6.3f", score_count_local[i]);
				gmp->Print("\t relative");
				for(int i = 0; i < number_players+1; i++)
					gmp->Print(" %5.3f", (float)win_count_local[i]/num_games);
			}
		}
		
		//calculate avgerage and deviation in external score storing structure
		if(score_output != NULL){	
			score_output[0]->Calc_AvgDev();
			score_output[0]->Calc_Confidence();
			score_output[1]->Calc_AvgDev();
			score_output[1]->Calc_Confidence();
		}
	}
	// END - repeats

	//output depth 0: after all repeats, final results, players outputs
	if(output_depth >= TOMGAME_OUTPUT_DEPTH0){
		cpu_time = getCPUTime()-cpu_time;
		if(number_players == 1){
			gmp->Print("\naverage score %6.5f\t | Player: %s", score_count_total[0] / num_games / num_repeats, players[0]->player_name.c_str());
		}else{
			gmp->Print("\nPlayers: %s",players[0]->player_name.c_str());
			for(int i = 1; i < this->number_players; i++)
				gmp->Print(" vs %s", players[i]->player_name.c_str());
			gmp->Print(":\t draws %4d\t wins", win_count_total[0]);
			for(int i = 0; i < number_players; i++)
				gmp->Print(" %4d", win_count_total[i+1]);
			gmp->Print("\t sum-scores");
			for(int i = 0; i < number_players; i++)
				gmp->Print(" %6.3f", score_count_total[i]);
			gmp->Print("\t relative");
			for(int i = 0; i < number_players+1; i++)
				gmp->Print(" %5.3f", (float)win_count_total[i]/num_games/num_repeats);
			
		}
		gmp->Print("\t[%d repeats %d games]\t Runtime: %9.3f s", num_repeats, num_games, cpu_time);

		//output players info
		for(int i = 0; i < number_players; i++)
			if(players[i]->final_output_enabled)
				players[i]->Output();
	}

	//output average time per move
	if(measure_time_per_move){
		for(int i = 0; i < number_players; i++)
			gmp->Print("\nTIME P%d:   %6.1lf ms/game   %6.2lf ms/move  (games %d moves %d totalTime %lf s)",i,players_move_time_sum[i] / (double)(num_repeats*num_games) * 1000.0, players_move_time_sum[i] / (double)(num_repeats*num_games*players_move_count[i]) * 1000.0 , num_repeats*num_games, players_move_count[i],players_move_time_sum[i]);
		gmp->Print("\n\n");
	}

	if (winDraw_output_new != NULL){
		winDraw_output_new[0] = (double)(win_count_total[0]);	//num draws
		winDraw_output_new[1] = (double)(win_count_total[1]);	//num wins player 1
		winDraw_output_new[2] = (double)(win_count_total[2]);	//num wins player 2
	}

	//save return value
	double tmpReturn = score_count_total[return_score_player_num];

	//clean up
	delete[] win_count_total;
	delete[] win_count_local;
	delete[] score_count_total;
	delete[] score_count_local;
	delete[] players_move_time_sum;
	delete[] players_move_count;

	//return score
	return tmpReturn;
}
/**
Procedure executes given number of games with specified players, for player learning purpose.

@param output_depth sets how detailed is the output/visualization
*/
void Game_Engine::Learn_Players(int num_games, int output_depth, Player_Engine** players)
{

	int nextMove, feedback;
	int output_interval, next_output;
	double cpu_time;

	//check if players are correctly linked to game, otherwise exit procedure
	players = Validate_Players(players);
	if(players == NULL)
		return;

	//output depth 0
#if(!TOM_OUTPUT_TO_MATLAB)
	if(output_depth >= TOMGAME_OUTPUT_DEPTH0){		
		gmp->Print("\nLearning game %s [%d games]", game_name.c_str(), num_games);
		for(int i = 0; i < this->number_players; i++)
			gmp->Print(", Player %d: %s", i+1, players[i]->player_name.c_str());
		gmp->Print(" |");
		if(output_depth == TOMGAME_OUTPUT_DEPTH0){
			output_interval = (int)(num_games/10);
			next_output = output_interval;
		}
	}
#endif

	//measure time
	cpu_time = getCPUTime();

	//execute games
	for(int g = 0; g < num_games; g++){

		//reset game state (start new game)
		Game_New();

		//call new-game procedure for players 
		for(int i = 0; i < number_players; i++)
			players[i]->New_Game();

		//play game until end is signaled
		feedback = game_ended;
		while(feedback == 0){

			//current player selects next move
			nextMove = players[current_player]->Get_Move();

			//call before-move procedure for all players
			for(int i = 0; i < number_players; i++){
				players[i]->Before_Move(nextMove);
			}

			//simulate game dynamics with selected move
#if(TOM_DEBUG)
			feedback = Play_Move(nextMove);
#else
			feedback = Play_Move_Unsafe(nextMove);
#endif
			//call after-move procedure for all players
			for(int i = 0; i < number_players; i++){
				players[i]->After_Move(nextMove);
			}

		}

		//calculate score
		Calculate_Score();

		//call end-game procedure for players, game must not be resetted before this call
		for(int i = 0; i < number_players; i++)
			players[i]->End_Game();

		//output depth 1
#if(!TOM_OUTPUT_TO_MATLAB)
		if(output_depth == TOMGAME_OUTPUT_DEPTH0){
			if(g >= next_output){
				gmp->Print(".");
				next_output += output_interval;
			}
		}else if(output_depth >= TOMGAME_OUTPUT_DEPTH1){
			gmp->Print("\nL1 Game num %3d \t plys %2d \t score",g+1,current_plys);
			for(int i = 0; i < number_players; i++)
				gmp->Print("  %3.1f", score[i]);
		}
#endif

	}

	//output depth 0, with players final output
#if(!TOM_OUTPUT_TO_MATLAB)
	if(output_depth >= TOMGAME_OUTPUT_DEPTH0){
		cpu_time = getCPUTime()-cpu_time;
		if(output_depth > TOMGAME_OUTPUT_DEPTH0)
			gmp->Print("\n");
		else
			gmp->Print("\t ");
		gmp->Print("Runtime: %9.3f s",cpu_time);
		for(int i = 0; i < number_players; i++)
			if(players[i]->final_output_enabled)
				players[i]->Output();
	}
#endif
}