#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <signal.h>
//#include "testccnew.h"
void* omalloc(int x) {
fprintf(stderr,"\nin omalloc %d\n",x);
void *ret = malloc(x);
return ret;//malloc(10);;
}

void omalloctest(int x) {
fprintf(stderr,"\nin omalloctest %d\n",x);
}

int omalloc2(int *x) {
fprintf(stderr,"\nin omalloc2 %d\n",*x);
return *x+*x;//malloc(10);;
}
int stoploop = 0;

void instrumentmyfunc(int x)
{
	fprintf(stderr,"\ninside instrumentthisfunc is %d\n",x);
}
void *inc_x(void *x_void_ptr)
{
	while(!stoploop)
	{
	instrumentmyfunc(2);	
		int *ptr = (int*)omalloc(5); 
		if(!ptr)
		{
			fprintf(stderr,"\nptr NULL\n"); 
		}
		else
		{
			fprintf(stderr,"\nptr not NULL\n"); 
		

			*ptr = 4;
			int ptrvalue = (int*)omalloc2(ptr); 
			fprintf(stderr,"\nptr value %d\n",ptrvalue); 
		}
		printf("sleeping --------------\n\n");
		sleep(2);
	}
	fprintf(stderr,"\nstopping process\n"); 
}

void siginthandler(int signum) {
   printf("Caught SIGINT %d shutting down \n", signum);
   stoploop = 1;
}
void sigtermhandler(int signum) {
   printf("Caught SIGTERM %d shutting down \n", signum);
   stoploop = 1;
}

int main(int argc, char *argv[]) {
	fprintf(stderr,"\nin main\n"); 
	//echo.new
signal(SIGINT, siginthandler);
signal(SIGTERM, sigtermhandler);
pthread_t inc_x_thread;
if(pthread_create(&inc_x_thread, NULL, inc_x, NULL)) {

fprintf(stderr, "Error creating thread\n");
return 1;

}

if(pthread_join(inc_x_thread, NULL)) {

fprintf(stderr, "Error joining thread\n");
return 2;

}

printf("main end \n");	
	  return 0;
}

//DynModifyCallCommand
//1. copy orignal func  cmalloc
//2. put jump in omalloc to wmalloc
//3. look for callq instruction to omalloc in wmalloc and change it to call cmalloc
//dynamic_cast<func_instance*>(cmalloc)
//write override classes
//compile without using -g
//replace a function call with parameter. ALso check the return value of replaced function

//wrap function cannot be instrumented. Can we instrument any function in wrap function?
//which so needs to use shared or plugin?

//different types of parameters in golang, structure for input & return value
//write wmalloc in another so file
//also do wrapping in running process

//plt jump instruction
//in memory

