#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/io.h>

#include <sys/utsname.h>

#include "../../api.h"


#define IOCTL_KTAPI_DRV_IO_BLOCK 100

char OS_String[0x100];


int fd_KTAPI;

void TextOut(char * Text)
{
	printf("%s",Text);
}
int OS_Init(void)
{
	struct utsname ver;
	

	if ((fd_KTAPI=open("/dev/ktapi", O_RDWR))==-1)
	{
    	printf("Error : Can't open /dev/ktapi\n");
        return 0;
	}

	// Proc_DebugOut=&TextOut;
	
	uname(&ver);
	
	/*
	printf("sysname  %s\n",ver.sysname);
	printf("nodename %s\n",ver.nodename);
	printf("release  %s\n",ver.release);
	printf("version  %s\n",ver.version);
	printf("machine  %s\n",ver.machine);
	*/
	
	sprintf(OS_String,"%s %s",ver.sysname,ver.release);
	return 1;
}

void OS_Deinit(void)
{

	close(fd_KTAPI);

}


void * OS_Alloc_Execute_Read_Write(unsigned int Size)
{
void * Temp;

	Temp=(void *)mmap(NULL,Size,PROT_EXEC | PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE ,-1,0);
	
//	printf("OS_Alloc_Execute_Read_Write %08x @ %08x \n",Size,Temp);

	return Temp;
	
}

void   OS_Free_Execute_Read_Write(void * Adr,unsigned int Size)
{
//	printf("OS_Free_Execute_Read_Write %08x @ %08x\n",Size,Adr);
	munmap(Adr,Size);
}


void * OS_Memory_Allocate(unsigned long Size)
{
void * Temp;

	Temp=(void *) malloc(Size);
	
//	printf("OS_Memory_Allocate %08x @ %08x \n",Size,Temp);
	
	return Temp;
}

void   OS_Memory_Free(void * Adr,unsigned long Size)
{
//	printf("OS_Memory_Free %08x @ %08x\n",Size,Adr);
	Size;
	free(Adr);
}

void * OS_Physical_Memory_Map(void * Adr,unsigned long Size)
{

	#ifdef KTAPI_32
	return (void *)mmap(NULL,Size,PROT_READ | PROT_WRITE , MAP_SHARED ,fd_KTAPI,(unsigned long)Adr);
	#else
	return (void *)mmap(NULL,Size,PROT_READ | PROT_WRITE , MAP_SHARED ,fd_KTAPI,(unsigned long long)Adr);
	#endif

}

void  OS_Physical_Memory_Unmap(void * Adr,unsigned long Size)
{
	munmap((void *)Adr,Size);
}


unsigned int OS_Execute_IO_Block(_API_IO_Struct * IO_Block,unsigned int Size)
{

unsigned int Status;


	Status=ioctl(fd_KTAPI,IOCTL_KTAPI_DRV_IO_BLOCK,(unsigned char*)IO_Block,10);


	return Status;
}



int stricmp(const char *s1, const char *s2)
{
	return strcasecmp(s1,s2);
}


int OS_Microsecond_Delay(unsigned int DelayCount)
{
	return _API_se_Error;
}

int OS_CPUID(_API_ASM_REGS_Struct * _API_ASM_REGS)
{
	_API_ASM_REGS->_EAX=0;
	_API_ASM_REGS->_EBX=0;
	_API_ASM_REGS->_ECX=0;
	_API_ASM_REGS->_EDX=0;
	return _API_se_Error;
}
int OS_Read_MSR(_API_ASM_REGS_Struct * _API_ASM_REGS)
{
	_API_ASM_REGS->_EAX=0;
	_API_ASM_REGS->_EBX=0;
	_API_ASM_REGS->_ECX=0;
	_API_ASM_REGS->_EDX=0;
	return _API_se_Error;
}

int OS_Write_MSR(_API_ASM_REGS_Struct * _API_ASM_REGS)
{
	_API_ASM_REGS->_EAX=0;
	_API_ASM_REGS->_EBX=0;
	_API_ASM_REGS->_ECX=0;
	_API_ASM_REGS->_EDX=0;
	return _API_se_Error;
}
