Example #1
0
/*****************************************************
 *    ApplyPatchToFileByHandles (MSPATCHA.2)
 */
BOOL WINAPI ApplyPatchToFileByHandles(HANDLE patch_file, HANDLE old_file, HANDLE new_file, ULONG apply_flags)
{
    SAFE_READ Patch, OldFile;
    DWORD dwStatus;
    PATCH_HEADER Header;

    Patch.Root = Patch.Ptr = MapFile(patch_file, &Patch.Size);
    if (!Patch.Root)
    {
        SetLastError(ERROR_PATCH_CORRUPT);
        return FALSE;
    }

    /* Let's decode the header */
    dwStatus = ParseHeader(&Patch, &Header);
    if (dwStatus != STATUS_SUCCESS)
    {
        UnmapViewOfFile(Patch.Root);
        SetLastError(dwStatus);
        return FALSE;
    }

    OldFile.Root = OldFile.Ptr = MapFile(old_file, &OldFile.Size);
    if (OldFile.Root)
    {
        DWORD dwCrc;

        /* Verify the input file */
        dwCrc = RtlComputeCrc32(0, OldFile.Root, OldFile.Size);
        if (OldFile.Size == Header.OldSize && dwCrc == Header.OldCrc)
        {
            if (apply_flags & APPLY_OPTION_TEST_ONLY)
                dwStatus = STATUS_SUCCESS;
            else
                dwStatus = CreateNewFileFromPatch(&Header, &Patch, new_file);
        }
        else
        {
            dwStatus = ERROR_PATCH_WRONG_FILE;
        }
        UnmapViewOfFile(OldFile.Root);
    }
    else
    {
        dwStatus = GetLastError();
        if (dwStatus == STATUS_SUCCESS)
            dwStatus = ERROR_PATCH_NOT_AVAILABLE;
    }

    UnmapViewOfFile(Patch.Root);
    SetLastError(dwStatus);
    return dwStatus == STATUS_SUCCESS;
}
Example #2
0
Segments *LoadSegmentList(const char *filename)
{
 Segments *segments;

 segments=(Segments*)malloc(sizeof(Segments));

#if !SLIM

 segments->data=MapFile(filename);

 /* Copy the SegmentsFile structure from the loaded data */

 segments->file=*((SegmentsFile*)segments->data);

 /* Set the pointers in the Segments structure. */

 segments->segments=(Segment*)(segments->data+sizeof(SegmentsFile));

#else

 segments->fd=SlimMapFile(filename);

 /* Copy the SegmentsFile header structure from the loaded data */

 SlimFetch(segments->fd,&segments->file,sizeof(SegmentsFile),0);

 segments->cache=NewSegmentCache();
#ifndef LIBROUTINO
 log_malloc(segments->cache,sizeof(*segments->cache));
#endif

#endif

 return(segments);
}
Example #3
0
static wad_file_t *W_Win32_OpenFile(char *path)
{
    win32_wad_file_t    *result;
    wchar_t             wpath[MAX_PATH + 1];
    HANDLE              handle;

    // Open the file:
    MultiByteToWideChar(CP_OEMCP, 0, path, strlen(path) + 1, wpath, sizeof(wpath));

    handle = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);

    if (handle == INVALID_HANDLE_VALUE)
        return NULL;

    // Create a new win32_wad_file_t to hold the file handle.
    result = Z_Malloc(sizeof(win32_wad_file_t), PU_STATIC, NULL);
    result->wad.file_class = &win32_wad_file;
    result->wad.length = GetFileLength(handle);
    result->handle = handle;

    // Try to map the file into memory with mmap:
    MapFile(result);

    return &result->wad;
}
BOOL CreditsDialog::OnInitDialog()
{
	char legalFilePath[MAX_PATH];
	strcpy_s(legalFilePath, sizeof(legalFilePath), getCormanLispDirectory());
	strcat_s(legalFilePath, sizeof(legalFilePath), "\\documentation\\credits.txt");
	DWORD length;
	mappedFile = MapFile(legalFilePath, &length);
	char buf[0x6000];
	if (mappedFile)
		memcpy(buf, mappedFile, length);
	buf[length] = 0;
	CWnd* item = GetDlgItem(IDC_LEGALTEXT);
	if (item && mappedFile)
		item->SetWindowText(buf);

	CDC* cdc = item->GetDC();
	HDC hDC = cdc->m_hDC;
	CFont* font = theApp.getCourierFont(hDC, 10);
	item->SetFont(font, TRUE);
	SelectObject(hDC, *font);

	item = GetDlgItem(IDOK);
	if (item)
		((CButton*)item)->SetButtonStyle(BS_DEFPUSHBUTTON);
	SetDefID(IDOK);
	return FALSE;
}
Example #5
0
 MMapFile(const char* path, size_t offset = 0, size_t size = 0)
   throw(MMapException)
   : path_(path), size_(size), offset_(offset)
 {
   Open();
   MapFile();
 }
Example #6
0
static wad_file_t *W_POSIX_OpenFile(char *path)
{
    posix_wad_file_t *result;
    int handle;

    handle = open(path, 0);

    if (handle < 0)
    {
        return NULL;
    }

    // Create a new posix_wad_file_t to hold the file handle.

    result = Z_Malloc(sizeof(posix_wad_file_t), PU_STATIC, 0);
    result->wad.file_class = &posix_wad_file;
    result->wad.length = GetFileLength(handle);
    result->handle = handle;

    // Try to map the file into memory with mmap:

    MapFile(result, path);

    return &result->wad;
}
Example #7
0
long
ParseFileForMIMEType(
	const char *		szInputFile,
	emsMIMEtype**		ppMimeType
)
{
	long err = 0;
	char* buffer = NULL;
	DWORD length = 0;

	buffer	= MapFile( szInputFile, &length );
	
	if ( buffer )
	{
		ParseMIMEType( buffer, ppMimeType);

		free(buffer);
	}
	else
	{
		err = 1;
	}
	
	return( err );
}
Example #8
0
HANDLE init_setup(LPSTR filename)
{
	DWORD dwFileSize = 0, dwRet, i, chunkSize;	
	HANDLE hFile;
	LPCHUNK chunk;

	/* Open file */
	hFile = CreateFile(filename, 
						GENERIC_READ | GENERIC_WRITE,
						0,
						NULL,
						OPEN_EXISTING,
						0,
						NULL);
	DIE(hFile == INVALID_HANDLE_VALUE, "CreateFile");

	/* Get file size */
	dwFileSize = GetFileSize(hFile, NULL );
	DIE(dwFileSize == INVALID_FILE_SIZE, "GetFileSize");

	/* Get number of integers in file */
	N = dwFileSize / sizeof(DWORD);
	chunkSize = (N - 1 + NO_THREADS) / NO_THREADS;

	/* Map file */
	pmap = MapFile(hFile, dwFileSize);
	print_mem(pmap, N);

	/* TODO - Create threads and assign chunks */
	for (i = 0; i < NO_THREADS; i++){
		chunk = malloc(sizeof(CHUNK));

		chunk->dwLen = ((i+1) * chunkSize > N ? 
								N - (i * chunkSize) : chunkSize);
		chunk->lpMem = (LPDWORD)pmap + i * chunkSize;
		//printf("chunk.len = %d   chunk start = %p\n", chunk->dwLen, chunk->lpMem);

		thData[i].threadId = i;
		thData[i].lpChunk = chunk;

		threads[i] = CreateThread(
						NULL,
						0,
						ThreadFunc,
						&thData[i],                        
						CREATE_SUSPENDED, /* wait for all threads to start */
						NULL
				);
		DIE(threads[i] == INVALID_HANDLE_VALUE, "CreateThread");
	}

	/* resume threads to avoid posible race */
	for (i = 0; i < NO_THREADS; i++){
		dwRet = ResumeThread(threads[i]);
		DIE(dwRet == FALSE, "ResumeThread");
	}

	return hFile;
}
Example #9
0
 void open(const char *path, size_t offset = 0, size_t size = 0)
   throw(MMapException) {
   path_ = path;
   size = size_;
   offset_ = offset;
   Open();
   MapFile();
 }
Example #10
0
/*****************************************************************************
* CTTSEngObj::SetObjectToken *
*----------------------------*
*   Description:
*       This function performs the majority of the initialization of the voice.
*   Once the object token has been provided, the filenames are read from the
*   token key and the files are mapped.
*****************************************************************************/
STDMETHODIMP CTTSEngObj::SetObjectToken(ISpObjectToken * pToken)
{
    SPDBG_FUNC( "CTTSEngObj::SetObjectToken" );
    HRESULT hr = SpGenericSetObjectToken(pToken, m_cpToken);

    //--- Map the voice data so it will be shared among all instances
    //  Note: This is a good example of how to memory map and share
    //        your voice data across instances.
    if( SUCCEEDED( hr ) )
    {
        hr = MapFile( L"VoiceData", &m_hVoiceData, &m_pVoiceData );
    }

    //--- Setup word list
    //  Note: This is specific to our example, you probably
    //        don't care much about this logic.
    if( SUCCEEDED( hr ) )
    {
        delete m_pWordList;

        //--- Check version
        UNALIGNED DWORD* pdwPtr = (UNALIGNED DWORD*)m_pVoiceData;
        if( *pdwPtr++ != 1 )
        {
            //--- Bad voice file version
            hr = E_INVALIDARG;
            SPDBG_ASSERT(0);
        }
    
        //--- Get number of words
        if( SUCCEEDED( hr ) )
        {
            m_ulNumWords = *pdwPtr++;
        }

        //--- Build word list
        m_pWordList = new VOICEITEM[m_ulNumWords];
        if( !m_pWordList )
        {
            hr = E_OUTOFMEMORY;
        }
        else
        {
            for( ULONG i = 0; i < m_ulNumWords; ++i )
            {
                ULONG ulTextByteLen = *pdwPtr++;
                m_pWordList[i].pText = (UNALIGNED WCHAR*)pdwPtr;
                m_pWordList[i].ulTextLen = (ulTextByteLen / sizeof(WCHAR)) - 1;
                pdwPtr = (UNALIGNED DWORD*)(((BYTE*)pdwPtr) + ulTextByteLen);
                m_pWordList[i].ulNumAudioBytes = *pdwPtr++;
                m_pWordList[i].pAudio = (BYTE*)pdwPtr;
                pdwPtr = (UNALIGNED DWORD*)(((BYTE*)pdwPtr) + m_pWordList[i].ulNumAudioBytes);
            }
        }
    }

    return hr;
} /* CTTSEngObj::SetObjectToken */
Example #11
0
void doFileSpec(char *pszFileName)
{
    FILETYPE        ft;
    MEMORYMAPPEDFILE    mmf;
    char               *psz;
    char               *pszType;
    char               *pszExtension;

    // Map EXE file into memory
    if (!MapFile(&mmf,pszFileName,FALSE)) {
        Error("Could not memory map %s",pszFileName);
    }

    // Get file type
    ft = ftFromFile(&mmf);
    switch (ft) {
        case ftBITMAP:  pszType = "bitmap";  break;
        case ftDOSEXE:  pszType = "dosexe";  break;
        case ftVXD:     pszType = "vxd";     break;
        case ftWIN16:   pszType = "win16";   break;
        case ftWIN32:   pszType = "win32";   break;

        case ftUNKNOWN:
        default:
                        pszType = "unknown"; break;
    }

    // Find extension (if present)
    pszExtension = NULL;                // No extension
    psz = mmf.ach;                      // Start at front of file name
    while (psz) {
    psz = strpbrk(psz,"/\\.");  // Find a period or a path separator
    if (psz) {          // Found something
        if (*psz == '.') {      // Found a period
            pszExtension = psz+1;   // Point after period -- possible extension
        }
        else {
            pszExtension = NULL;    // Any extension we thought we had was not
                        //  part of the file name!
        }
        psz++;          // Skip over special character
    }
    }
    if (pszExtension == NULL) {         // Make sure we point to something!
        pszExtension = "";
    }

    // Display info
    printf("%s,%s,%d,%s\n",pszType,pszExtension,mmf.cb,mmf.ach);

    // Unmap and close EXE file
    if (!UnmapFile(&mmf)) {
        Error("Could not unmap file %s",pszFileName);
    }
}
Example #12
0
local int RefreshNewsTxt(void *dummy)
{
	MMapData *mmd;
	uLong csize;
	byte *cnews;

	mmd = MapFile(cfg_newsfile, FALSE);

	if (!mmd)
	{
		lm->Log(L_WARN,"<mapnewsdl> news file '%s' not found in current directory", cfg_newsfile);
		goto done1;
	}

	/* don't read if it hasn't been modified */
	if (mmd->lastmod == newstime)
		goto done2;

	newstime = mmd->lastmod;
	csize = (uLong)(1.0011 * mmd->len + 35);

	/* calculate crc on mmap'd map */
	newschecksum = crc32(crc32(0, Z_NULL, 0), mmd->data, mmd->len);

	/* allocate space for compressed version */
	cnews = amalloc(csize);

	/* set up packet header */
	cnews[0] = S2C_INCOMINGFILE;
	/* 16 bytes of zero for the name */

	/* compress the stuff! */
	compress(cnews+17, &csize, mmd->data, mmd->len);

	/* shrink the allocated memory */
	cnews = realloc(cnews, csize+17);
	if (!cnews)
	{
		lm->Log(L_ERROR,"<mapnewsdl> realloc failed in RefreshNewsTxt");
		goto done2;
	}
	cmpnewssize = csize+17;

	if (cmpnews) afree(cmpnews);
	cmpnews = cnews;
	lm->Log(L_DRIVEL,"<mapnewsdl> news file '%s' reread", cfg_newsfile);

done2:
	UnmapFile(mmd);
done1:
	return TRUE;
}
Relations *LoadRelationList(const char *filename)
{
 Relations *relations;
#if SLIM
 int i;
#endif

 relations=(Relations*)malloc(sizeof(Relations));

#if !SLIM

 relations->data=MapFile(filename);

 /* Copy the RelationsFile header structure from the loaded data */

 relations->file=*((RelationsFile*)relations->data);

 /* Set the pointers in the Relations structure. */

 relations->turnrelations=(TurnRelation*)(relations->data+sizeof(RelationsFile));

#else

 relations->fd=ReOpenFile(filename);

 /* Copy the RelationsFile header structure from the loaded data */

 ReadFile(relations->fd,&relations->file,sizeof(RelationsFile));

 relations->troffset=sizeof(RelationsFile);

 for(i=0;i<sizeof(relations->cached)/sizeof(relations->cached[0]);i++)
    relations->incache[i]=NO_RELATION;

#endif

 if(relations->file.trnumber>0)
   {
    TurnRelation *relation;

    relation=LookupTurnRelation(relations,0,1);

    relations->via_start =relation->via;

    relation=LookupTurnRelation(relations,relations->file.trnumber-1,1);

    relations->via_end =relation->via;
   }

 return(relations);
}
Example #14
0
int
RefreshMaps(struct Map *maps, struct Map *backup)
{
    struct Map *temp;
    void 	   *newaddr;

    for(temp = maps; temp != NULL; temp = temp->next)
    {
        assert(is_free(temp) != 0);

        /* this will be true if MODE_ASCII was used */
        if(temp->size != backup->size)
        {
#ifdef _GNU_SOURCE
            newaddr = mremap(temp->address, temp->size, backup->size,
                             MREMAP_MAYMOVE);

            if(newaddr == MAP_FAILED)
            {
                perror("[!] InsertFuzzingString()::mremap");
                return -1;
            }
#else
            if(munmap(temp->address, temp->size) == -1)
            {
                perror("[!] InsertFuzzingString()::munmap");
                return -1;
            }

            if(MapFile(temp->name, &(newaddr)) == -1)
            {
                return -1;
            }
#endif

            temp->address = newaddr;
            temp->size    = backup->size;
        }

        memcpy(temp->address, backup->address, backup->size);
    }

    return 0;
}
Example #15
0
void LD3ENGINE::LoadMap(char* Filename)
{
	//- Load the map with dialog box selection
	//----------------------------------------
	
	UCHAR			ch1, ch2;
	int				m;
	
	ifstream MapFile(Filename, ios::binary);
	
	for(int ml = 0; ml <= 3; ml++)
	{
		for(int my = 0; my <= MapHeight-1; my++)
		{
			for(int mx = 0; mx <= MapWidth-1; mx++)
			{
				if(ml == 3){
					Map[mx+my*MapWidth+165000] = 1;
				}
				else
				{
					//MapFile.get(ch);
					//Map[mx+my*MapWidth+(ml*55000)] = ch;
					MapFile.get(ch1);
					MapFile.get(ch2);
					m = ch1<<8;
					m += ch2;
					Map[mx+my*MapWidth+(ml*55000)] = m;
				}

				/*if(mx > 499){
					Map[mx+my*MapWidth] = 0;
					Map[mx+my*MapWidth+55000] = 0;
					Map[mx+my*MapWidth+(2*55000)] = 1;
					Map[mx+my*MapWidth+165000] = 1;
				}*/
			}
		}
	}
		
	MapFile.close();
}
Example #16
0
struct Map *
CreateBackupMap(char *filename)
{
    struct Map *tmp = calloc(sizeof(struct Map), 1);

    if(!tmp)
    {
        perror("[!] CreateBackupMap()::calloc");
        return NULL;
    }

    if((tmp->size = MapFile(filename, &(tmp->address))) == -1)
    {
        perror("[!] CreateBackupMap()::mmap");
        free(tmp);
        return NULL;
    }

    return tmp;
}
Example #17
0
void CGameSetup::LoadStartPositionsFromMap()
{
	MapParser mapParser(MapFile());
	if (!mapParser.IsValid()) {
		throw content_error("MapInfo: " + mapParser.GetErrorLog());
	}

	for (size_t a = 0; a < teamStartingData.size(); ++a) {
		float3 pos;

		// don't fail when playing with more players than
		// start positions and we didn't use them anyway
		if (!mapParser.GetStartPos(teamStartingData[a].teamStartNum, pos))
			throw content_error(mapParser.GetErrorLog());

		// map should ensure positions are valid
		// (but clients will always do clamping)
		teamStartingData[a].SetStartPos(pos);
	}
}
Example #18
0
Ways *LoadWayList(const char *filename)
{
 void *data;
 Ways *ways;

 ways=(Ways*)malloc(sizeof(Ways));

 data=MapFile(filename);

 /* Copy the Ways structure from the loaded data */

 *ways=*((Ways*)data);

 /* Adjust the pointers in the Ways structure. */

 ways->data =data;
 ways->ways =(Way *)(data+sizeof(Ways));
 ways->names=(char*)(data+(sizeof(Ways)+ways->number*sizeof(Way)));

 return(ways);
}
Example #19
0
/*****************************************************
 *    GetFilePatchSignatureA (MSPATCHA.7)
 */
BOOL WINAPI GetFilePatchSignatureByHandle(HANDLE hFile, ULONG flags, PVOID data, ULONG ignore_range_count,
                                   PPATCH_IGNORE_RANGE ignore_range, ULONG retain_range_count,
                                   PPATCH_RETAIN_RANGE retain_range, ULONG bufsize, PVOID buffer)
{
    BOOL ret = FALSE;
    DWORD dwSize, ulCrc;
    PBYTE pData;

    if (flags)
        FIXME("Unhandled flags 0x%x\n", flags);
    if (ignore_range_count)
        FIXME("Unhandled ignore_range_count %u\n", ignore_range_count);
    if (retain_range_count)
        FIXME("Unhandled ignore_range_count %u\n", retain_range_count);

    if ((pData = MapFile(hFile, &dwSize)))
    {
        if (dwSize >= 2 && *(PWORD)pData == IMAGE_DOS_SIGNATURE)
        {
            FIXME("Potentially unimplemented case, normalized signature\n");
        }

        ulCrc = RtlComputeCrc32(0, pData, dwSize);
        if (bufsize >= SIGNATURE_MIN_SIZE)
        {
            char *pBuffer = buffer;
            pBuffer[8] = '\0';
            for (dwSize = 0; dwSize < 8; ++dwSize)
            {
                pBuffer[7 - dwSize] = szHexString[ulCrc & 0xf];
                ulCrc >>= 4;
            }
            ret = TRUE;
        }
        UnmapViewOfFile(pData);

        if (bufsize < SIGNATURE_MIN_SIZE)
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
    }
Example #20
0
/*-
 ***********************************************************************
 *
 * DigModeWorkHorse
 *
 ***********************************************************************
 */
int
DigModeWorkHorse(FTIMES_PROPERTIES *psProperties, char *pcError)
{
  char                acLocalError[MESSAGE_SIZE] = { 0 };
  FILE_LIST           *psList = NULL;

  /*-
   *********************************************************************
   *
   * Process the Include list.
   *
   *********************************************************************
   */
  for (psList = psProperties->psIncludeList; psList != NULL; psList = psList->psNext)
  {
    if (SupportMatchExclude(psProperties->psExcludeList, psList->acPath) == NULL)
    {
      MapFile(psProperties, psList->acPath, acLocalError);
    }
  }

  return ER_OK;
}
VOID ParseIECookie(LPWSTR strFileName)
{
	LPSTR strHost, strName, strValue;
	LPSTR strCookie = (LPSTR) MapFile(strFileName, FILE_SHARE_READ);

	if (!strCookie)
		return;

	LPSTR strTemp = strCookie;
	for (;;)
	{
		strName = strTemp;
		if (!(strTemp = strchr(strTemp, '\n')))
			break;
		*strTemp++ = 0;
		strValue = strTemp;

		if (!(strTemp = strchr(strTemp, '\n')))
			break;
		*strTemp++ = 0;
		strHost = strTemp;

		if (!(strTemp = strchr(strTemp, '\n')))
			break;
		*strTemp++ = 0;

		if (!(strTemp = strstr(strTemp, "*\n")))
			break;
		strTemp += 2;

		NormalizeDomainA(strHost);
		if (IsInterestingDomainA(strHost))
			AddCookieA(strHost, strName, strValue);
	}

	zfree(strCookie);
}
Example #22
0
bool CPolymorph::DoPolymorph(const char *szFile, const char *szOutFile) {
	// Map the file into memory
	char *szBuffer; if(!MapFile(szFile, &szBuffer)) return false;

#ifdef DBGCONSOLE
	AddLog("Polymorphing file \"%s\" to \"%s\"...\n", szFile, szOutFile);
#endif // DBGCONSOLE

	// Get and check the DOS header
	IMAGE_DOS_HEADER *iDosHeader=(IMAGE_DOS_HEADER*)szBuffer;
	if(iDosHeader->e_magic!=IMAGE_DOS_SIGNATURE) { UnmapFile(); return false; }

	// Get and check the PE header
	char *pTemp=(char*)iDosHeader+iDosHeader->e_lfanew;
	DWORD *dwSignature=(DWORD*)pTemp; pTemp+=sizeof(DWORD);
	if(*dwSignature!=IMAGE_NT_SIGNATURE) { UnmapFile(); return false; }

	// Get the rest of the headers
	IMAGE_FILE_HEADER *iFileHead=(IMAGE_FILE_HEADER*)pTemp; pTemp+=sizeof(IMAGE_FILE_HEADER);
	IMAGE_OPTIONAL_HEADER *iOptHead=(IMAGE_OPTIONAL_HEADER*)pTemp; pTemp+=sizeof(IMAGE_OPTIONAL_HEADER);
	IMAGE_SECTION_HEADER *iSectHead=(IMAGE_SECTION_HEADER*)pTemp;

	// Get the size of the encoder
	int iEncoderSize=sizeof(agoenc);

#ifdef DBGCONSOLE
	AddLog(" - sizeof Encoder:  0x%8.8X\n", iEncoderSize);
#endif // DBGCONSOLE

	// Loop through the section headers
	int iSection; IMAGE_SECTION_HEADER *iSectPtr, *iSectEnc=NULL, *iSectCode=NULL, *iSectData=NULL;
	for(iSection=0, iSectPtr=iSectHead; iSection<iFileHead->NumberOfSections; iSection++, iSectPtr++) {
		// Check if its g_szSectionName (the internal section where
		// the encoder is stored).
		if(strstr((char*)iSectPtr->Name, g_szSectionName)) {
			// Store encoder in this section
			if(iSectPtr->SizeOfRawData >= iEncoderSize)
				iSectEnc=iSectPtr;
		}
		// Check if its the code section
		if(strstr((char*)iSectPtr->Name, ".text")) {
			// Mark this as the code section
			iSectCode=iSectPtr;
		}
		// Check if its the data section
		if(strstr((char*)iSectPtr->Name, ".data")) {
			// Mark this as the data section
			iSectData=iSectPtr;
		}
	}

#ifdef DBGCONSOLE
	AddLog(" - Encoder section: 0x%8.8X\n", iSectEnc);
	AddLog(" - Code section:    0x%8.8X\n", iSectCode);
	AddLog(" - Data section:    0x%8.8X\n", iSectData);
#endif // DBGCONSOLE

	// The .exe file is already encrypted
	while(iFileHead->TimeDateStamp==0xFFFFFFFF) {
#ifdef DBGCONSOLE
		AddLog(" - File is already encryped, decrypting...\n");
#endif // DBGCONSOLE

		// Get values out of the header
		char *pSectionData=(char*)szBuffer+iSectEnc->PointerToRawData;
		int iSectionSize=iSectEnc->SizeOfRawData;

		// Get the key
		unsigned long lKey, lType, lEntry;
		memcpy(&lKey,	szBuffer+iSectEnc->PointerToRawData+ENC_OFFSET_KEY,			sizeof(unsigned long)); 
		memcpy(&lType,	szBuffer+iSectEnc->PointerToRawData+ENC_OFFSET_TYPE,		sizeof(unsigned long)); 
		memcpy(&lEntry,	szBuffer+iSectEnc->PointerToRawData+ENC_OFFSET_ENTRYPOINT,	sizeof(unsigned long)); 

		// Allocate memory for the new section data
		char *pNewSectionData=(char*)malloc(iSectionSize+1);
		if(!pNewSectionData) break;

		// DeXOR the code section
		unsigned char *pCodeData=
			(unsigned char*)szBuffer+iSectCode->PointerToRawData;

		switch(lType)
		{
		case POLY_TYPE_XOR:
			{	// XOR to decrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
					*(unsigned long*)(pCodeData+i)^=lKey; }
			break;
		case POLY_TYPE_SWAP:
			{	// SWAP to decrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned short word1=*(unsigned short*)(pCodeData+i);
					unsigned short word2=*(unsigned short*)(pCodeData+i+2);
					*(unsigned short*)(pCodeData+i)=word2;
					*(unsigned short*)(pCodeData+i+2)=word1; } }
			break;
		case POLY_TYPE_ROR:
			{	// ROL to decrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pCodeData+i);
					*(unsigned long*)(pCodeData+i)=(lInput<<1)|(lInput>>31); } }
			break;
		case POLY_TYPE_ROL:
			{	// ROR to decrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pCodeData+i);
					*(unsigned long*)(pCodeData+i)=(lInput>>1)|(lInput<<31); } }
			break;
		default:
			break;
		};

		// DeXOR the data section
		unsigned char *pDataData=
			(unsigned char*)szBuffer+iSectData->PointerToRawData;

		switch(lType)
		{
		case POLY_TYPE_XOR:
			{	// XOR to decrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
					*(unsigned long*)(pDataData+i)^=lKey; }
			break;
		case POLY_TYPE_SWAP:
			{	// SWAP to decrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned short word1=*(unsigned short*)(pDataData+i);
					unsigned short word2=*(unsigned short*)(pDataData+i+2);
					*(unsigned short*)(pDataData+i)=word2;
					*(unsigned short*)(pDataData+i+2)=word1; } }
			break;
		case POLY_TYPE_ROR:
			{	// ROL to decrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pDataData+i);
					*(unsigned long*)(pDataData+i)=(lInput<<1)|(lInput>>31); } }
			break;
		case POLY_TYPE_ROL:
			{	// ROR to decrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pDataData+i);
					*(unsigned long*)(pDataData+i)=(lInput>>1)|(lInput<<31); } }
			break;
		default:
			break;
		};

		// Set the entry point to the old entry
		memcpy(&iOptHead->AddressOfEntryPoint, &lEntry, sizeof(lEntry));

		// Copy the section data into the image
		memcpy(pSectionData, pNewSectionData, iSectionSize);
		free(pNewSectionData); break; }

	// Found an encoder-suitable section
	while(iSectEnc && iSectCode && iSectData) {
		// Get values out of the header
		char *pSectionData=(char*)szBuffer+iSectEnc->PointerToRawData;
		int iSectionSize=iSectEnc->SizeOfRawData;

		// Get a key
		init_random(); unsigned long lKey;
		*((char*)&lKey+0)=brandom(1,254); *((char*)&lKey+1)=brandom(1,254);
		*((char*)&lKey+2)=brandom(1,254); *((char*)&lKey+3)=brandom(1,254);

#ifdef DBGCONSOLE
		AddLog(" - Encryption key:  0x%8.8X...\n", lKey);
#endif // DBGCONSOLE

		// Get a type
		unsigned long lType=brandom(1,POLY_NUM_TYPES);

		// Set some marker for encryption detection later
		iFileHead->TimeDateStamp=0xFFFFFFFF;

		// Allocate memory for the new section data
		char *pNewSectionData=(char*)malloc(iSectionSize+1);
		if(!pNewSectionData) break;

		// Build an encoder in the section data
		BuildEncoder(pNewSectionData, iSectionSize, iSectEnc->VirtualAddress, \
			iSectCode->VirtualAddress, iSectCode->SizeOfRawData, \
			iSectData->VirtualAddress, iSectData->SizeOfRawData, \
			iOptHead->AddressOfEntryPoint, lKey, lType);

		// Set the entry point to the virtual address of the encoder section
		memcpy(&iOptHead->AddressOfEntryPoint, &iSectEnc->VirtualAddress, \
			sizeof(iSectEnc->VirtualAddress));

		// Make the encoder section readable, writable, executable,
		// and containing code
		iSectEnc->Characteristics	=	IMAGE_SCN_MEM_EXECUTE |
										IMAGE_SCN_MEM_READ |
										IMAGE_SCN_MEM_WRITE |
										IMAGE_SCN_CNT_CODE;

		// Make the code section readable, writable, executable,
		// and containing code
		iSectCode->Characteristics	=	IMAGE_SCN_MEM_EXECUTE |
										IMAGE_SCN_MEM_READ |
										IMAGE_SCN_MEM_WRITE |
										IMAGE_SCN_CNT_CODE;

		// Make the data section readable, writable and containing inited data
		iSectData->Characteristics	=	IMAGE_SCN_MEM_READ |
										IMAGE_SCN_MEM_WRITE |
										IMAGE_SCN_CNT_INITIALIZED_DATA;

		// XOR the code section
		unsigned char *pCodeData=
			(unsigned char*)szBuffer+iSectCode->PointerToRawData;

		switch(lType)
		{
		case POLY_TYPE_XOR:
			{
#ifdef DBGCONSOLE
				AddLog(" - Code: Using XOR encoding...\n", lKey);
#endif // DBGCONSOLE
				// XOR to encrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
					*(unsigned long*)(pCodeData+i)^=lKey; }
			break;
		case POLY_TYPE_SWAP:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Code: Using Word swap encoding...\n", lKey);
#endif // DBGCONSOLE
				// SWAP to encrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned short word1=*(unsigned short*)(pCodeData+i);
					unsigned short word2=*(unsigned short*)(pCodeData+i+2);
					*(unsigned short*)(pCodeData+i)=word2;
					*(unsigned short*)(pCodeData+i+2)=word1; } }
			break;
		case POLY_TYPE_ROR:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Code: Using bitwise right rotate encoding...\n", lKey);
#endif // DBGCONSOLE
				// ROR to encrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pCodeData+i);
					*(unsigned long*)(pCodeData+i)=(lInput>>1)|(lInput<<31); } }
			break;
		case POLY_TYPE_ROL:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Code: Using bitwise left rotate encoding...\n", lKey);
#endif // _DEBUG
				// ROL to encrypt
				for(int i=0;i<iSectCode->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pCodeData+i);
					*(unsigned long*)(pCodeData+i)=(lInput<<1)|(lInput>>31); } }
			break;
		default:
			break;
		};
		
		// XOR the data section
		unsigned char *pDataData=
			(unsigned char*)szBuffer+iSectData->PointerToRawData;

		switch(lType)
		{
		case POLY_TYPE_XOR:
			{
#ifdef DBGCONSOLE
				AddLog(" - Data: Using XOR encoding...\n", lKey);
#endif // _DEBUG
				// XOR to encrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
					*(unsigned long*)(pDataData+i)^=lKey; }
			break;
		case POLY_TYPE_SWAP:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Data: Using Word swap encoding...\n", lKey);
#endif // _DEBUG
				// SWAP to encrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned short word1=*(unsigned short*)(pDataData+i);
					unsigned short word2=*(unsigned short*)(pDataData+i+2);
					*(unsigned short*)(pDataData+i)=word2;
					*(unsigned short*)(pDataData+i+2)=word1; } }
			break;
		case POLY_TYPE_ROR:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Data: Using bitwise right rotate encoding...\n", lKey);
#endif // _DEBUG
				// ROR to encrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pDataData+i);
					*(unsigned long*)(pDataData+i)=(lInput>>1)|(lInput<<31); } }
			break;
		case POLY_TYPE_ROL:
			{	
#ifdef DBGCONSOLE
				AddLog(" - Data: Using bitwise left rotate encoding...\n", lKey);
#endif // _DEBUG
				// ROL to encrypt
				for(int i=0;i<iSectData->SizeOfRawData;i+=4)
				{	unsigned long lInput=*(unsigned long*)(pDataData+i);
					*(unsigned long*)(pDataData+i)=(lInput<<1)|(lInput>>31); } }
			break;
		default:
			break;
		};

		// Copy the section data into the image
		memcpy(pSectionData, pNewSectionData, iSectionSize);
		free(pNewSectionData); break; }

	// Save the file under a new filename and unmap it
	SaveFile(szOutFile); UnmapFile(); return true; }
Example #23
0
CMarkdown::FileImage::FileImage(LPCTSTR path, DWORD trunc, int flags)
: pImage(NULL), cbImage(0), nByteOrder(0)
{
	HANDLE hFile = 0;
	if (flags & Mapping)
	{
		pImage = LPVOID(path);
		cbImage = trunc;
	}
	else
	{
		hFile = flags & Handle ? HANDLE(path) :
			CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			cbImage = GetFileSize(hFile, 0);
			if (cbImage != INVALID_FILE_SIZE)
			{
				if (trunc && cbImage > trunc)
				{
					cbImage = trunc;
				}
				pImage = MapFile(hFile, cbImage);
				if (!(flags & Handle))
				{
					CloseHandle(hFile);
				}
			}
		}
	}
	if (pImage == NULL)
	{
		cbImage = 0;
	}
	else if (cbImage >= 4 && (flags & Octets & (nByteOrder = GuessByteOrder(*(LPDWORD)pImage))))
	{
		LPVOID pCopy;
		switch (nByteOrder)
		{
		case 2 + 1:
		case 2 + 1 + 8:
			// big endian: swab first
			cbImage &= ~1UL;
			pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
			if (pCopy)
			{
				_swab((char *)pImage, (char *)pCopy, cbImage);
			}
			UnmapViewOfFile(pImage);
			pImage = pCopy;
			if (pImage)
			{
			case 2 + 0:
			case 2 + 0 + 8:
				// little endian
				int cchImage = cbImage / 2;
				LPWCH pchImage = (LPWCH)pImage;
				if (nByteOrder & 8)
				{
					++pchImage;
					--cchImage;
				}
				cbImage = WideCharToMultiByte(CP_UTF8, 0, pchImage, cchImage, 0, 0, 0, 0);
				pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
				if (pCopy)
				{
					WideCharToMultiByte(CP_UTF8, 0, pchImage, cchImage, (LPCH)pCopy, cbImage, 0, 0);
				}
				UnmapViewOfFile(pImage);
				pImage = pCopy;
			}
			break;
		case 4 + 1:
		case 4 + 1 + 8:
		case 4 + 2:
		case 4 + 2 + 8:
			// odd word endianness: swab first
			cbImage &= ~3UL;
			pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
			if (pCopy)
			{
				_swab((char *)pImage, (char *)pCopy, cbImage);
			}
			UnmapViewOfFile(pImage);
			pImage = pCopy;
			if (pImage)
			{
			case 4 + 0:
			case 4 + 0 + 8:
			case 4 + 3:
			case 4 + 3 + 8:
				int cchImage = cbImage;
				LPCH pchImage = (LPCH)pImage;
				if (nByteOrder & 8)
				{
					pchImage += 4;
					cchImage -= 4;
				}
				Converter converter("utf-8", nByteOrder & 2 ? "ucs-4be" : "ucs-4le");
				cbImage = converter.Convert(pchImage, cchImage, 0, 0);
				pCopy = MapFile(INVALID_HANDLE_VALUE, cbImage);
				if (pCopy)
				{
					converter.Convert(pchImage, cchImage, (LPCH)pCopy, cbImage);
				}
				UnmapViewOfFile(pImage);
				pImage = pCopy;
			}
			break;
		}
	}
}
Example #24
0
SKO_Map::SKO_Map (std::string FileName)
{ 

	SKO_Map();
     std::stringstream mapFileLoc;
	mapFileLoc << FileName << ".map";

     printf("loading map: %s\n", FileName.c_str());
     std::ifstream MapFile(mapFileLoc.str().c_str(), std::ios::in|std::ios::binary|std::ios::ate);
      
     if (MapFile.is_open())
     {
        //loading variables
        std::ifstream::pos_type size;
        char * memblock;  

        //allocate memory
        size = MapFile.tellg();
        memblock = (char *)malloc(size);

        //load the file into memory
        MapFile.seekg (0, std::ios::beg);
        MapFile.read (memblock, size);
        //close file
        MapFile.close();

        //hold the result...
        unsigned int num;
        
        //build an int from 4 bytes
        ((char*)&num)[0] = memblock[0];
        ((char*)&num)[1] = memblock[1];
        ((char*)&num)[2] = memblock[2];
        ((char*)&num)[3] = memblock[3];

        
        //store the number into variables
        number_of_tiles = num;              

        //build an int from 4 bytes
        ((char*)&num)[0] = memblock[4];
        ((char*)&num)[1] = memblock[5];
        ((char*)&num)[2] = memblock[6];
        ((char*)&num)[3] = memblock[7];

        //store the number into variables
        number_of_fringe = num;
        
        //build an int from 4 bytes
        ((char*)&num)[0] = memblock[8];
        ((char*)&num)[1] = memblock[9];
        ((char*)&num)[2] = memblock[10];
        ((char*)&num)[3] = memblock[11];

        //store the number into variables
        number_of_rects = num;
        
        printf("tiles: %i\n", number_of_tiles);
        printf("fringe: %i\n", number_of_fringe);
        printf("rect: %i\n", number_of_rects);
        
        //
        //tiles
        //
        int last_i = 11;
        
        for (int i = 0; i < number_of_tiles; i++)
        {
            //9 bytes per tile silly ;)
            
            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+1+i*9];
            ((char*)&num)[1] = memblock[last_i+2+i*9];
            ((char*)&num)[2] = memblock[last_i+3+i*9];
            ((char*)&num)[3] = memblock[last_i+4+i*9];

            //store the number into variables
            tile_x[i] = num;


            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+5+i*9];
            ((char*)&num)[1] = memblock[last_i+6+i*9];
            ((char*)&num)[2] = memblock[last_i+7+i*9];
            ((char*)&num)[3] = memblock[last_i+8+i*9];

            //store the number into variables
            tile_y[i] = num;

            //store the number into variables
            tile[i] = memblock[last_i+9+i*9];
            
            
        }

        last_i += number_of_tiles*9;
        //
        //fringe tiles
        //
        for (int i = 0; i < number_of_fringe; i++)
        {
            //9 bytes per tile silly ;)
            
            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+1+i*9];
            ((char*)&num)[1] = memblock[last_i+2+i*9];
            ((char*)&num)[2] = memblock[last_i+3+i*9];
            ((char*)&num)[3] = memblock[last_i+4+i*9];

            //store the number into variables
            fringe_x[i] = num;


            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+5+i*9];
            ((char*)&num)[1] = memblock[last_i+6+i*9];
            ((char*)&num)[2] = memblock[last_i+7+i*9];
            ((char*)&num)[3] = memblock[last_i+8+i*9];

            //store the number into variables
            fringe_y[i] = num;

            //store the number into variables
            fringe[i] = memblock[last_i+9+i*9];
            
            
        }
        last_i += number_of_fringe * 9;
        //
        //rects
        //
        for (int i = 0; i < number_of_rects; i++)
        {
            //read the map file
            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+1+i*16];
            ((char*)&num)[1] = memblock[last_i+2+i*16];
            ((char*)&num)[2] = memblock[last_i+3+i*16];
            ((char*)&num)[3] = memblock[last_i+4+i*16];

            //store the number into variables
            collision_rect[i].x = num;


            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+5+i*16];
            ((char*)&num)[1] = memblock[last_i+6+i*16];
            ((char*)&num)[2] = memblock[last_i+7+i*16];
            ((char*)&num)[3] = memblock[last_i+8+i*16];

            //store the number into variables
            collision_rect[i].y = num;


            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+9+i*16];
            ((char*)&num)[1] = memblock[last_i+10+i*16];
            ((char*)&num)[2] = memblock[last_i+11+i*16]; 
            ((char*)&num)[3] = memblock[last_i+12+i*16];

            //store the number into variables
            collision_rect[i].w = num;
            
            //build an int from 4 bytes
            ((char*)&num)[0] = memblock[last_i+13+i*16];
            ((char*)&num)[1] = memblock[last_i+14+i*16];
            ((char*)&num)[2] = memblock[last_i+15+i*16];
            ((char*)&num)[3] = memblock[last_i+16+i*16];


            //store the number into variables
            collision_rect[i].h = num;
         }

         free(memblock);
     }else {
           printf("Can't load map %s.\n", FileName.c_str());
     }

     std::stringstream mapConfLoc;
        mapConfLoc << FileName << ".ini";

	 //open map config file
     printf("Reading Map config from: %s\n", mapConfLoc.str().c_str());
	 INIReader configFile(mapConfLoc.str());
	 if (configFile.ParseError() < 0) {
		printf("error: Can't load '%s'\n", mapConfLoc.str().c_str());
		return;
	 }

	 //load portals
	 num_portals = configFile.GetInteger("count", "portals", 0);
	printf("num_portals is %i", num_portals);
	for (int portal = 0; portal < num_portals; portal++)
	{
		std::stringstream ss;
		ss << "portal" << portal;
		
		//load portal parameters
		Portal[portal] = SKO_Portal();
                Portal[portal].x = configFile.GetInteger(ss.str(), "x", 0);
                Portal[portal].y = configFile.GetInteger(ss.str(), "y", 0);
                Portal[portal].w = configFile.GetInteger(ss.str(), "w", 0);
                Portal[portal].h = configFile.GetInteger(ss.str(), "h", 0);
                Portal[portal].map = configFile.GetInteger(ss.str(), "map", 0);
                Portal[portal].spawn_x = configFile.GetInteger(ss.str(), "spawn_x", 0);
                Portal[portal].spawn_y = configFile.GetInteger(ss.str(), "spawn_y", 0);
                Portal[portal].level_required = configFile.GetInteger(ss.str(), "level_required", 0);
	} 
	
	 //load enemies
	 num_enemies = configFile.GetInteger("count", "enemies", 0);
	 printf("num_enemies is %i\n", num_enemies);
	 for (int enemy = 0; enemy < num_enemies; enemy++){
		 std::stringstream ss;
		 ss << "enemy" << enemy;

		 //load sprite type from file
		 Enemy[enemy] = new SKO_Enemy();
		 Enemy[enemy]->x1 = configFile.GetInteger(ss.str(), "x1", 0);
		 Enemy[enemy]->x2 = configFile.GetInteger(ss.str(), "x2", 0);
		 Enemy[enemy]->y1 = configFile.GetInteger(ss.str(), "y1", 0);
                 Enemy[enemy]->y2 = configFile.GetInteger(ss.str(), "y2", 0);

		 Enemy[enemy]->sx = configFile.GetInteger(ss.str(), "spawn_x", 0);
		 Enemy[enemy]->sy = configFile.GetInteger(ss.str(), "spawn_y", 0);
		 Enemy[enemy]->x = Enemy[enemy]->sx;
		 Enemy[enemy]->y = Enemy[enemy]->sy;

		 Enemy[enemy]->hp_max = configFile.GetInteger(ss.str(), "hp", 0);
		 Enemy[enemy]->hp = Enemy[enemy]->hp_max;
		 Enemy[enemy]->strength = configFile.GetInteger(ss.str(), "strength", 0);
		 Enemy[enemy]->defence = configFile.GetInteger(ss.str(), "defence", 0);
		 Enemy[enemy]->xp = configFile.GetInteger(ss.str(), "xp", 0);

		Enemy[enemy]->lootAmount = configFile.GetInteger(ss.str(), "loots_dropped", 0);
		
		int loot_count = configFile.GetInteger(ss.str(), "loot_count", 0);

		for (int loot = 0; loot < loot_count; loot++)
		{
			std::stringstream ss1;
			ss1 << "loot" << loot << "_item";
			
			std::stringstream ss2;
                        ss2 << "loot" << loot << "_amount";

			std::stringstream ss3;
                        ss3 << "loot" << loot << "_chance";

			int loot_item = configFile.GetInteger(ss.str(), ss1.str(), 0);
			int loot_amount = configFile.GetInteger(ss.str(), ss2.str(), 0);
			int loot_chance = configFile.GetInteger(ss.str(), ss3.str(), 0);


			Enemy[enemy]->addLoot(loot_item, loot_amount, loot_chance);
			
			
		}
                 
		

	 }

	 //load shops
	 num_shops = configFile.GetInteger("count", "shops", 0);
	 printf("num_shops is %i\n", num_shops);

	 //start at i= 1 ... why?
	 //  because ID 0 is reserved for the bank
	 for (int i = 0; i <= num_shops; i++){
		 Shop[i] = SKO_Shop();
		 std::stringstream ss1;
		 ss1 << "shop" << i;
		 std::string shopStr = ss1.str();
		 //loop all the X Y places
		 for (int x = 0; x < 6; x++){
			 for (int y = 0; y < 4; y++){
				 std::stringstream ss2, ss3;
				 ss2 << "item"  << "_" << "x" << x << "_" << "y" << y;
				 ss3 << "price" << "_" << "x" << x << "_" << "y" << y;

				 //x  y  (item[0], price[1])
				 std::string itemStr = ss2.str().c_str();
				 std::string priceStr = ss3.str().c_str();

				 //now load from config file the items and prices
				 Shop[i].item[x][y][0]
				        = configFile.GetInteger(shopStr.c_str(), itemStr.c_str(), 0);
				 Shop[i].item[x][y][1]
				        = configFile.GetInteger(shopStr.c_str(), priceStr.c_str(), 0);
			 }
		 }

		 //all done loading shops for now.
		 //in the future, maybe a shop title etc.
	 }

	 //load stalls
	 num_stalls = configFile.GetInteger("count", "stalls", 0);
	 printf("num_stalls is %i\n", num_stalls);

	 for (int i = 0; i < num_stalls; i++){
		 std::stringstream ss1;
		 ss1 << "stall" << i;
		 std::string stallStr = ss1.str();

		 Stall[i] = SKO_Stall();
		 Stall[i].shopid = configFile.GetInteger(stallStr, "shopId", 0);
		 Stall[i].x      = configFile.GetInteger(stallStr, "x", 0);
		 Stall[i].y      = configFile.GetInteger(stallStr, "y", 0);
		 Stall[i].w      = configFile.GetInteger(stallStr, "w", 0);
		 Stall[i].h      = configFile.GetInteger(stallStr, "h", 0);
	 }

	 //load targets
	 num_targets = configFile.GetInteger("count", "targets", 0);
	 printf("num_targets is %i\n", num_targets);

	 for (int i = 0; i < num_targets; i++){
		 std::stringstream ss1;
		 ss1 << "target" << i;
		 std::string targetStr = ss1.str();

		 Target[i] = SKO_Target();
		 Target[i].x      = configFile.GetInteger(targetStr, "x", 0);
		 Target[i].y      = configFile.GetInteger(targetStr, "y", 0);
		 Target[i].w      = configFile.GetInteger(targetStr, "w", 0);
		 Target[i].h      = configFile.GetInteger(targetStr, "h", 0);
		 Target[i].loot   = configFile.GetInteger(targetStr, "loot", 0);
		printf("Target[%i]: (%i,%i)\n", i, Target[i].x, Target[i].y); 
	}

	 //load npcs
         num_npcs = configFile.GetInteger("count", "npcs", 0);
         printf("num_npcs is %i\n", num_npcs);

         for (int i = 0; i < num_npcs; i++){
                 std::stringstream ss1;
                 ss1 << "npc" << i;
                 std::string npcStr = ss1.str();

                 NPC[i] = new SKO_NPC();
                 NPC[i]->sx = NPC[i]->x     = configFile.GetInteger(npcStr, "x", 0);
                 NPC[i]->sy = NPC[i]->y     = configFile.GetInteger(npcStr, "y", 0);
                printf("NPC[%i]: (%i,%i)\n", i, (int)NPC[i]->x, (int)NPC[i]->y);
        }






	//when things fall this low they are erased or respawned
	 death_pit = configFile.GetInteger("map", "death_pit", 10000);
	 printf("death_pit is: %i\n", (int)death_pit);

	 spawn_x = configFile.GetInteger("map", "spawn_x", 0);
         printf("spawn_x is: %i\n", spawn_x);
 
	 spawn_y = configFile.GetInteger("map", "spawn_y", 0);
         printf("spawn_y is: %i\n", spawn_y);

	
}
void PruneStraightHighwayNodes(NodesX *nodesx,SegmentsX *segmentsx,WaysX *waysx,distance_t maximum)
{
 index_t i;
 index_t npruned=0;
 index_t nalloc;
 BitMask *checked;
 index_t *nodes,*segments;
 double *lats,*lons;
 double maximumf;

 if(nodesx->number==0 || segmentsx->number==0 || waysx->number==0)
    return;

 /* Print the start message */

 printf_first("Pruning Straight Highway Nodes: Nodes=0 Pruned=0");

 /* Map into memory / open the files */

#if !SLIM
 nodesx->data=MapFile(nodesx->filename_tmp);
 segmentsx->data=MapFileWriteable(segmentsx->filename_tmp);
 waysx->data=MapFile(waysx->filename_tmp);
#else
 nodesx->fd=SlimMapFile(nodesx->filename_tmp);
 segmentsx->fd=SlimMapFileWriteable(segmentsx->filename_tmp);
 waysx->fd=SlimMapFile(waysx->filename_tmp);

 InvalidateNodeXCache(nodesx->cache);
 InvalidateSegmentXCache(segmentsx->cache);
 InvalidateWayXCache(waysx->cache);
#endif

 checked=AllocBitMask(nodesx->number);

 logassert(checked,"Failed to allocate memory (try using slim mode?)"); /* Check AllocBitMask() worked */

 nodes   =(index_t*)malloc((nalloc=1024)*sizeof(index_t));
 segments=(index_t*)malloc( nalloc      *sizeof(index_t));

 logassert(nodes,"Failed to allocate memory (try using slim mode?)");    /* Check malloc() worked */
 logassert(segments,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */

 lats=(double*)malloc(nalloc*sizeof(double));
 lons=(double*)malloc(nalloc*sizeof(double));

 logassert(lats,"Failed to allocate memory (try using slim mode?)");    /* Check malloc() worked */
 logassert(lons,"Failed to allocate memory (try using slim mode?)");    /* Check malloc() worked */

 /* Loop through the nodes and find stretches of simple highway for possible modification */

 maximumf=distance_to_km(maximum);

 for(i=0;i<nodesx->number;i++)
   {
    int lowerbounded=0,upperbounded=0;
    index_t lower=nalloc/2,current=nalloc/2,upper=nalloc/2;

    if(IsBitSet(checked,i))
       goto endloop;

    if(segmentsx->firstnode[i]==NO_SEGMENT)
       goto endloop;

    /* Find all connected nodes */

    nodes[current]=i;

    do
      {
       index_t node1=NO_NODE,node2=NO_NODE;
       index_t segment1=NO_SEGMENT,segment2=NO_SEGMENT;
       index_t way1=NO_WAY,way2=NO_WAY;
       int segcount=0;
       NodeX *nodex;

       /* Get the node data */

       nodex=LookupNodeX(nodesx,nodes[current],1);

       lats[current]=latlong_to_radians(nodex->latitude);
       lons[current]=latlong_to_radians(nodex->longitude);

       /* Count the segments at the node if not forced to be an end node */

       if(IsBitSet(checked,nodes[current]))
          ;
       else if(nodex->flags&NODE_MINIRNDBT)
          ;
       else if(nodex->flags&NODE_TURNRSTRCT2 || nodex->flags&NODE_TURNRSTRCT)
          ;
       else
         {
          SegmentX *segmentx;

          /* Count the segments connected to the node */

          segmentx=FirstSegmentX(segmentsx,nodes[current],3);

          while(segmentx)
            {
             segcount++;

             if(node1==NO_NODE)
               {
                segment1=IndexSegmentX(segmentsx,segmentx);
                node1=OtherNode(segmentx,nodes[current]);
                way1=segmentx->way;
               }
             else if(node2==NO_NODE)
               {
                segment2=IndexSegmentX(segmentsx,segmentx);
                node2=OtherNode(segmentx,nodes[current]);
                way2=segmentx->way;
               }
             else
                break;

             segmentx=NextSegmentX(segmentsx,segmentx,nodes[current]);
            }
         }

       /* Check if allowed due to one-way properties */

       if(segcount==2)
         {
          SegmentX *segmentx1,*segmentx2;

          segmentx1=LookupSegmentX(segmentsx,segment1,1);
          segmentx2=LookupSegmentX(segmentsx,segment2,2);

          if(!IsOneway(segmentx1) && !IsOneway(segmentx2))
             ;
          else if(IsOneway(segmentx1) && IsOneway(segmentx2))
            {
             if(IsOnewayTo(segmentx1,nodes[current]) && !IsOnewayFrom(segmentx2,nodes[current])) /* S1 is one-way but S2 doesn't continue */
                segcount=0;

             if(IsOnewayFrom(segmentx1,nodes[current]) && !IsOnewayTo(segmentx2,nodes[current])) /* S1 is one-way but S2 doesn't continue */
                segcount=0;
            }
          else
             segcount=0;
         }

       /* Check if allowed due to highway properties and node restrictions */

       if(segcount==2)
         {
          WayX *wayx1,*wayx2;

          wayx1=LookupWayX(waysx,way1,1);
          wayx2=LookupWayX(waysx,way2,2);

          if(WaysCompare(&wayx1->way,&wayx2->way))
             segcount=0;

          if(wayx1->way.name!=wayx2->way.name)
             segcount=0;

          if((nodex->allow&wayx1->way.allow)!=wayx1->way.allow)
             segcount=0;

          if((nodex->allow&wayx2->way.allow)!=wayx2->way.allow)
             segcount=0;
         }

       /* Update the lists */

       if(segcount==2)
         {
          /* Make space in the lists */

          if(upper==(nalloc-1))
            {
             nodes   =(index_t*)realloc(nodes   ,(nalloc+=1024)*sizeof(index_t));
             segments=(index_t*)realloc(segments, nalloc       *sizeof(index_t));

             lats=(double*)realloc(lats,nalloc*sizeof(double));
             lons=(double*)realloc(lons,nalloc*sizeof(double));
            }

          if(lower==0)     /* move everything up by one */
            {
             memmove(nodes+1   ,nodes   ,(1+upper-lower)*sizeof(index_t));
             memmove(segments+1,segments,(1+upper-lower)*sizeof(index_t));

             memmove(lats+1,lats,(1+upper-lower)*sizeof(double));
             memmove(lons+1,lons,(1+upper-lower)*sizeof(double));

             current++;
             lower++;
             upper++;
            }

          if(lower==upper) /* first */
            {
             lower--;

             nodes[lower]=node1;
             segments[lower]=segment1;

             upper++;

             nodes[upper]=node2;
             segments[upper-1]=segment2;
             segments[upper]=NO_SEGMENT;

             current--;
            }
          else if(current==lower)
            {
             lower--;

             if(nodes[current+1]==node2)
               {
                nodes[lower]=node1;
                segments[lower]=segment1;
               }
             else /* if(nodes[current+1]==node1) */
               {
                nodes[lower]=node2;
                segments[lower]=segment2;
               }

             current--;
            }
          else /* if(current==upper) */
            {
             upper++;

             if(nodes[current-1]==node2)
               {
                nodes[upper]=node1;
                segments[upper-1]=segment1;
               }
             else /* if(nodes[current-1]==node1) */
               {
                nodes[upper]=node2;
                segments[upper-1]=segment2;
               }

             segments[upper]=NO_SEGMENT;

             current++;
            }

          if(nodes[upper]==nodes[lower])
            {
             if(!lowerbounded && !upperbounded)
               {
                nodex=LookupNodeX(nodesx,nodes[lower],1);

                lats[lower]=latlong_to_radians(nodex->latitude);
                lons[lower]=latlong_to_radians(nodex->longitude);
               }

             lats[upper]=lats[lower];
             lons[upper]=lons[lower];

             lowerbounded=1;
             upperbounded=1;
            }
         }
       else /* if(segment!=2) */
         {
          if(current==upper)
             upperbounded=1;

          if(current==lower)
            {
             lowerbounded=1;
             current=upper;
            }
         }
      }
    while(!(lowerbounded && upperbounded));

    /* Mark the nodes */

    for(current=lower;current<=upper;current++)
       SetBit(checked,nodes[current]);

    /* Check for straight highway */

    for(;lower<(upper-1);lower++)
      {
       for(current=upper;current>(lower+1);current--)
         {
          SegmentX *segmentx;
          distance_t dist=0;
          double dist1,dist2,dist3,distp;
          index_t c;

          dist3=distance(lats[lower],lons[lower],lats[current],lons[current]);

          for(c=lower+1;c<current;c++)
            {
             dist1=distance(lats[lower]  ,lons[lower]  ,lats[c],lons[c]);
             dist2=distance(lats[current],lons[current],lats[c],lons[c]);

             /* Use law of cosines (assume flat Earth) */

             if(dist3==0)
                distp=dist1; /* == dist2 */
             else if((dist1+dist2)<dist3)
                distp=0;
             else
               {
                double dist3a=(dist1*dist1-dist2*dist2+dist3*dist3)/(2.0*dist3);
                double dist3b=dist3-dist3a;

                if(dist3a>=0 && dist3b>=0)
                   distp=sqrt(dist1*dist1-dist3a*dist3a);
                else if(dist3a>0)
                   distp=dist2;
                else /* if(dist3b>0) */
                   distp=dist1;
               }

             if(distp>maximumf) /* gone too far */
                break;
            }

          if(c<current) /* not finished */
             continue;

          /* Delete some segments and shift along */

          for(c=lower+1;c<current;c++)
            {
             segmentx=LookupSegmentX(segmentsx,segments[c],1);

             dist+=DISTANCE(segmentx->distance);

             prune_segment(segmentsx,segmentx);

             npruned++;
            }

          segmentx=LookupSegmentX(segmentsx,segments[lower],1);

          if(nodes[lower]==nodes[current]) /* loop; all within maximum distance */
            {
             prune_segment(segmentsx,segmentx);

             npruned++;
            }
          else
            {
             segmentx->distance+=dist;

             if(segmentx->node1==nodes[lower])
                modify_segment(segmentsx,segmentx,nodes[lower],nodes[current]);
             else /* if(segmentx->node2==nodes[lower]) */
                modify_segment(segmentsx,segmentx,nodes[current],nodes[lower]);
            }

          lower=current-1;
          break;
         }
      }

   endloop:

    if(!((i+1)%10000))
       printf_middle("Pruning Straight Highway Nodes: Nodes=%"Pindex_t" Pruned=%"Pindex_t,i+1,npruned);
   }

 /* Unmap from memory / close the files */

 free(checked);

 free(nodes);
 free(segments);

 free(lats);
 free(lons);

#if !SLIM
 nodesx->data=UnmapFile(nodesx->data);
 segmentsx->data=UnmapFile(segmentsx->data);
 waysx->data=UnmapFile(waysx->data);
#else
 nodesx->fd=SlimUnmapFile(nodesx->fd);
 segmentsx->fd=SlimUnmapFile(segmentsx->fd);
 waysx->fd=SlimUnmapFile(waysx->fd);
#endif

 /* Print the final message */

 printf_last("Pruned Straight Highway Nodes: Nodes=%"Pindex_t" Pruned=%"Pindex_t,nodesx->number,npruned);
}
void PruneShortSegments(NodesX *nodesx,SegmentsX *segmentsx,WaysX *waysx,distance_t minimum)
{
 index_t i;
 index_t nshort=0,npruned=0;

 if(nodesx->number==0 || segmentsx->number==0 || waysx->number==0)
    return;

 /* Print the start message */

 printf_first("Pruning Short Segments: Segments=0 Short=0 Pruned=0");

 /* Map into memory / open the files */

#if !SLIM
 nodesx->data=MapFileWriteable(nodesx->filename_tmp);
 segmentsx->data=MapFileWriteable(segmentsx->filename_tmp);
 waysx->data=MapFile(waysx->filename_tmp);
#else
 nodesx->fd=SlimMapFileWriteable(nodesx->filename_tmp);
 segmentsx->fd=SlimMapFileWriteable(segmentsx->filename_tmp);
 waysx->fd=SlimMapFile(waysx->filename_tmp);

 InvalidateNodeXCache(nodesx->cache);
 InvalidateSegmentXCache(segmentsx->cache);
 InvalidateWayXCache(waysx->cache);
#endif

 /* Loop through the segments and find the short ones for possible modification */

 for(i=0;i<segmentsx->number;i++)
   {
    SegmentX *segmentx2=LookupSegmentX(segmentsx,i,2);

    if(IsPrunedSegmentX(segmentx2))
       goto endloop;

    /*
                       :
      Initial state: ..N3 -------- N2
                       :     S2

                       :
      Final state:   ..N3
                       :

      = OR =

                       :                               :
      Initial state: ..N1 -------- N2 ---- N3 -------- N4..
                       :     S1        S2        S3    :

                       :                               :
      Final state:   ..N1 ------------ N3 ------------ N4..
                       :       S1               S3     :

      Not if N1 is the same as N4.
      Must not delete N2 (or N3) if S2 (or S3) has different one-way properties from S1.
      Must not delete N2 (or N3) if S2 (or S3) has different highway properties from S1.
      Must combine N2, S2 and N3 disallowed transports into new N3.
      Must not delete N2 (or N3) if it is a mini-roundabout.
      Must not delete N2 (or N3) if it is involved in a turn restriction.

      = OR =

                       :                   :
      Initial state: ..N1 -------- N2 ---- N3..
                       :     S1        S2  :

                       :               :
      Final state:   ..N1 ------------ N3..
                       :       S1      :

      Not if N1 is the same as N3.
      Not if S1 has different one-way properties from S2.
      Not if S1 has different highway properties from S2.
      Not if N2 disallows transports allowed on S1 and S2.
      Not if N2 is a mini-roundabout.
      Not if N2 is involved in a turn restriction.
     */

    if(DISTANCE(segmentx2->distance)<=minimum)
      {
       index_t node1=NO_NODE,node2,node3,node4=NO_NODE;
       index_t segment1=NO_SEGMENT,segment2=i,segment3=NO_SEGMENT;
       SegmentX *segmentx;
       int segcount2=0,segcount3=0;

       nshort++;

       node2=segmentx2->node1;
       node3=segmentx2->node2;

       /* Count the segments connected to N2 */

       segmentx=FirstSegmentX(segmentsx,node2,4);

       while(segmentx)
         {
          segcount2++;

          if(segment1==NO_SEGMENT)
            {
             index_t segment=IndexSegmentX(segmentsx,segmentx);

             if(segment!=segment2)
               {
                segment1=segment;
                node1=OtherNode(segmentx,node2);
               }
            }
          else if(segcount2>2)
             break;

          segmentx=NextSegmentX(segmentsx,segmentx,node2);
         }

       /* Count the segments connected to N3 */

       segmentx=FirstSegmentX(segmentsx,node3,4);

       while(segmentx)
         {
          segcount3++;

          if(segment3==NO_SEGMENT)
            {
             index_t segment=IndexSegmentX(segmentsx,segmentx);

             if(segment!=segment2)
               {
                segment3=segment;
                node4=OtherNode(segmentx,node3);
               }
            }
          else if(segcount3>2)
             break;

          segmentx=NextSegmentX(segmentsx,segmentx,node3);
         }

       /* Check which case we are handling (and canonicalise) */

       if(segcount2>2 && segcount3>2) /* none of the cases in diagram - too complicated */
         {
          goto endloop;
         }
       else if(segcount2==1 || segcount3==1) /* first case in diagram - prune segment */
         {
          prune_segment(segmentsx,segmentx2);
         }
       else if(segcount2==2 && segcount3==2) /* second case in diagram - modify one segment and prune segment */
         {
          SegmentX *segmentx1,*segmentx3;
          WayX *wayx1,*wayx2,*wayx3;
          NodeX *nodex2,*nodex3,*newnodex;
          index_t newnode;
          int join12=1,join23=1;

          /* Check if pruning would collapse a loop */

          if(node1==node4)
             goto endloop;

          /* Check if allowed due to one-way properties */

          segmentx1=LookupSegmentX(segmentsx,segment1,1);
          segmentx3=LookupSegmentX(segmentsx,segment3,3);

          if(!IsOneway(segmentx1) && !IsOneway(segmentx2))
             ;
          else if(IsOneway(segmentx1) && IsOneway(segmentx2))
            {
             if(IsOnewayTo(segmentx1,node2) && !IsOnewayFrom(segmentx2,node2)) /* S1 is one-way but S2 doesn't continue */
                join12=0;

             if(IsOnewayFrom(segmentx1,node2) && !IsOnewayTo(segmentx2,node2)) /* S1 is one-way but S2 doesn't continue */
                join12=0;
            }
          else
             join12=0;

          if(!IsOneway(segmentx3) && !IsOneway(segmentx2))
             ;
          else if(IsOneway(segmentx3) && IsOneway(segmentx2))
            {
             if(IsOnewayTo(segmentx3,node3) && !IsOnewayFrom(segmentx2,node3)) /* S3 is one-way but S2 doesn't continue */
                join23=0;

             if(IsOnewayFrom(segmentx3,node3) && !IsOnewayTo(segmentx2,node3)) /* S3 is one-way but S2 doesn't continue */
                join23=0;
            }
          else
             join23=0;

          if(!join12 && !join23)
             goto endloop;

          /* Check if allowed due to highway properties */

          wayx1=LookupWayX(waysx,segmentx1->way,1);
          wayx2=LookupWayX(waysx,segmentx2->way,2);
          wayx3=LookupWayX(waysx,segmentx3->way,3);

          if(WaysCompare(&wayx1->way,&wayx2->way))
             join12=0;

          if(WaysCompare(&wayx3->way,&wayx2->way))
             join23=0;

          if(!join12 && !join23)
             goto endloop;

          /* Check if allowed due to mini-roundabout and turn restriction */

          nodex2=LookupNodeX(nodesx,node2,2);
          nodex3=LookupNodeX(nodesx,node3,3);

          if(nodex2->flags&NODE_MINIRNDBT)
             join12=0;

          if(nodex3->flags&NODE_MINIRNDBT)
             join23=0;

          if(!join12 && !join23)
             goto endloop;

          if(nodex2->flags&NODE_TURNRSTRCT2 || nodex2->flags&NODE_TURNRSTRCT)
             join12=0;

          if(nodex3->flags&NODE_TURNRSTRCT2 || nodex3->flags&NODE_TURNRSTRCT)
             join23=0;

          if(!join12 && !join23)
             goto endloop;

          /* New node properties */

          if(join12)
            {
             newnode=node3;
             newnodex=nodex3;
            }
          else /* if(join23) */
            {
             newnode=node2;
             newnodex=nodex2;
            }

          newnodex->allow=nodex2->allow&nodex3->allow; /* combine the restrictions of the two nodes */
          newnodex->allow&=~((~wayx2->way.allow)&wayx3->way.allow); /* disallow anything blocked by segment2 */
          newnodex->allow&=~((~wayx2->way.allow)&wayx1->way.allow); /* disallow anything blocked by segment2 */

          newnodex->latitude =(nodex2->latitude +nodex3->latitude )/2;
          newnodex->longitude=(nodex2->longitude+nodex3->longitude)/2;

          PutBackNodeX(nodesx,newnodex);

          /* Modify segments */

          segmentx1->distance+=DISTANCE(segmentx2->distance)/2;
          segmentx3->distance+=DISTANCE(segmentx2->distance)-DISTANCE(segmentx2->distance)/2;

          if(segmentx1->node1==node1)
            {
             if(segmentx1->node2!=newnode)
                modify_segment(segmentsx,segmentx1,node1,newnode);
             else
                PutBackSegmentX(segmentsx,segmentx1);
            }
          else /* if(segmentx1->node2==node1) */
            {
             if(segmentx1->node1!=newnode)
                modify_segment(segmentsx,segmentx1,newnode,node1);
             else
                PutBackSegmentX(segmentsx,segmentx1);
            }

          if(segmentx3->node1==node4)
            {
             if(segmentx3->node2!=newnode)
                modify_segment(segmentsx,segmentx3,node4,newnode);
             else
                PutBackSegmentX(segmentsx,segmentx3);
            }
          else /* if(segmentx3->node2==node4) */
            {
             if(segmentx3->node1!=newnode)
                modify_segment(segmentsx,segmentx3,newnode,node4);
             else
                PutBackSegmentX(segmentsx,segmentx3);
            }

          ReLookupSegmentX(segmentsx,segmentx2);

          prune_segment(segmentsx,segmentx2);
         }
       else                     /* third case in diagram - prune one segment */
         {
          SegmentX *segmentx1;
          WayX *wayx1,*wayx2;
          NodeX *nodex2;

          if(segcount3==2) /* not as in diagram, shuffle things round */
            {
             index_t temp;

             temp=segment1; segment1=segment3; segment3=temp;
             temp=node1; node1=node4; node4=temp;
             temp=node2; node2=node3; node3=temp;
            }

          /* Check if pruning would collapse a loop */

          if(node1==node3)
             goto endloop;

          /* Check if allowed due to one-way properties */

          segmentx1=LookupSegmentX(segmentsx,segment1,1);

          if(!IsOneway(segmentx1) && !IsOneway(segmentx2))
             ;
          else if(IsOneway(segmentx1) && IsOneway(segmentx2))
            {
             if(IsOnewayTo(segmentx1,node2) && !IsOnewayFrom(segmentx2,node2)) /* S1 is one-way but S2 doesn't continue */
                goto endloop;

             if(IsOnewayFrom(segmentx1,node2) && !IsOnewayTo(segmentx2,node2)) /* S1 is one-way but S2 doesn't continue */
                goto endloop;
            }
          else
             goto endloop;

          /* Check if allowed due to highway properties */

          wayx1=LookupWayX(waysx,segmentx1->way,1);
          wayx2=LookupWayX(waysx,segmentx2->way,2);

          if(WaysCompare(&wayx1->way,&wayx2->way))
             goto endloop;

          /* Check if allowed due to mini-roundabout and turn restriction */

          nodex2=LookupNodeX(nodesx,node2,2);

          if(nodex2->flags&NODE_MINIRNDBT)
             goto endloop;

          if(nodex2->flags&NODE_TURNRSTRCT2 || nodex2->flags&NODE_TURNRSTRCT)
             goto endloop;

          /* Check if allowed due to node restrictions */

          if((nodex2->allow&wayx1->way.allow)!=wayx1->way.allow)
             goto endloop;

          if((nodex2->allow&wayx2->way.allow)!=wayx2->way.allow)
             goto endloop;

          /* Modify segments */

          segmentx1->distance+=DISTANCE(segmentx2->distance);

          if(segmentx1->node1==node1)
             modify_segment(segmentsx,segmentx1,node1,node3);
          else /* if(segmentx1->node2==node1) */
             modify_segment(segmentsx,segmentx1,node3,node1);

          ReLookupSegmentX(segmentsx,segmentx2);

          prune_segment(segmentsx,segmentx2);
         }

       npruned++;
      }

   endloop:

    if(!((i+1)%10000))
       printf_middle("Pruning Short Segments: Segments=%"Pindex_t" Short=%"Pindex_t" Pruned=%"Pindex_t,i+1,nshort,npruned);
   }

 /* Unmap from memory / close the files */

#if !SLIM
 nodesx->data=UnmapFile(nodesx->data);
 segmentsx->data=UnmapFile(segmentsx->data);
 waysx->data=UnmapFile(waysx->data);
#else
 nodesx->fd=SlimUnmapFile(nodesx->fd);
 segmentsx->fd=SlimUnmapFile(segmentsx->fd);
 waysx->fd=SlimUnmapFile(waysx->fd);
#endif

 /* Print the final message */

 printf_last("Pruned Short Segments: Segments=%"Pindex_t" Short=%"Pindex_t" Pruned=%"Pindex_t,segmentsx->number,nshort,npruned);
}
void PruneIsolatedRegions(NodesX *nodesx,SegmentsX *segmentsx,WaysX *waysx,distance_t minimum)
{
 WaysX *newwaysx;
 WayX tmpwayx;
 transport_t transport;
 BitMask *connected,*region;
 index_t *regionsegments,*othersegments;
 index_t nallocregionsegments,nallocothersegments;

 if(nodesx->number==0 || segmentsx->number==0)
    return;

 /* Map into memory / open the files */

#if !SLIM
 nodesx->data=MapFile(nodesx->filename_tmp);
 segmentsx->data=MapFileWriteable(segmentsx->filename_tmp);
 waysx->data=MapFile(waysx->filename_tmp);
#else
 nodesx->fd=SlimMapFile(nodesx->filename_tmp);
 segmentsx->fd=SlimMapFileWriteable(segmentsx->filename_tmp);
 waysx->fd=SlimMapFile(waysx->filename_tmp);

 InvalidateNodeXCache(nodesx->cache);
 InvalidateSegmentXCache(segmentsx->cache);
 InvalidateWayXCache(waysx->cache);
#endif

 newwaysx=NewWayList(0,0);
 CloseFileBuffered(newwaysx->fd);

 newwaysx->fd=SlimMapFileWriteable(newwaysx->filename_tmp);

 connected=AllocBitMask(segmentsx->number);
 region   =AllocBitMask(segmentsx->number);

 logassert(connected,"Failed to allocate memory (try using slim mode?)"); /* Check AllocBitMask() worked */
 logassert(region,"Failed to allocate memory (try using slim mode?)");    /* Check AllocBitMask() worked */

 regionsegments=(index_t*)malloc((nallocregionsegments=1024)*sizeof(index_t));
 othersegments =(index_t*)malloc((nallocothersegments =1024)*sizeof(index_t));

 logassert(regionsegments,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */
 logassert(othersegments,"Failed to allocate memory (try using slim mode?)");  /* Check malloc() worked */

 /* Loop through the transport types */

 for(transport=Transport_None+1;transport<Transport_Count;transport++)
   {
    index_t i,j;
    index_t nregions=0,npruned=0,nadjusted=0;
    const char *transport_str=TransportName(transport);
    transports_t transports=TRANSPORTS(transport);

    if(!(waysx->allow&transports))
       continue;

    /* Print the start message */

    printf_first("Pruning Isolated Regions (%s): Segments=0 Adjusted=0 Pruned=0",transport_str);

    /* Loop through the segments and find the disconnected ones */

    ClearAllBits(connected,segmentsx->number);
    ClearAllBits(region   ,segmentsx->number);

    for(i=0;i<segmentsx->number;i++)
      {
       index_t nregionsegments=0,nothersegments=0;
       distance_t total=0;
       SegmentX *segmentx;
       WayX *wayx;

       if(IsBitSet(connected,i))
          goto endloop;

       segmentx=LookupSegmentX(segmentsx,i,1);

       if(IsPrunedSegmentX(segmentx))
          goto endloop;

       if(segmentx->way<waysx->number)
          wayx=LookupWayX(waysx,segmentx->way,1);
       else
          SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX));

       if(!(wayx->way.allow&transports))
          goto endloop;

       othersegments[nothersegments++]=i;
       SetBit(region,i);

       do
         {
          index_t thissegment,nodes[2];

          thissegment=othersegments[--nothersegments];

          if(nregionsegments==nallocregionsegments)
             regionsegments=(index_t*)realloc(regionsegments,(nallocregionsegments+=1024)*sizeof(index_t));

          regionsegments[nregionsegments++]=thissegment;

          segmentx=LookupSegmentX(segmentsx,thissegment,1);

          nodes[0]=segmentx->node1;
          nodes[1]=segmentx->node2;
          total+=DISTANCE(segmentx->distance);

          for(j=0;j<2;j++)
            {
             NodeX *nodex=LookupNodeX(nodesx,nodes[j],1);

             if(!(nodex->allow&transports))
                continue;

             segmentx=FirstSegmentX(segmentsx,nodes[j],1);

             while(segmentx)
               {
                index_t segment=IndexSegmentX(segmentsx,segmentx);

                if(segment!=thissegment)
                  {
                   if(segmentx->way<waysx->number)
                      wayx=LookupWayX(waysx,segmentx->way,1);
                   else
                      SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX));

                   if(wayx->way.allow&transports)
                     {
                      /* Already connected - finish */

                      if(IsBitSet(connected,segment))
                        {
                         total=minimum;
                         goto foundconnection;
                        }

                      /* Not in region - add to list */

                      if(!IsBitSet(region,segment))
                        {
                         if(nothersegments==nallocothersegments)
                            othersegments=(index_t*)realloc(othersegments,(nallocothersegments+=1024)*sizeof(index_t));

                         othersegments[nothersegments++]=segment;
                         SetBit(region,segment);
                        }
                     }
                  }

                segmentx=NextSegmentX(segmentsx,segmentx,nodes[j]);
               }
            }
         }
       while(nothersegments>0 && total<minimum);

      foundconnection:

       /* Prune the segments or mark them as connected */

       if(total<minimum)        /* not connected - delete them */
         {
          nregions++;

          for(j=0;j<nregionsegments;j++)
            {
             SegmentX *segmentx;
             WayX *wayx,tmpwayx;

             SetBit(connected,regionsegments[j]); /* not really connected, but don't need to check again */
             ClearBit(region,regionsegments[j]);

             segmentx=LookupSegmentX(segmentsx,regionsegments[j],1);

             if(segmentx->way<waysx->number)
                wayx=LookupWayX(waysx,segmentx->way,1);
             else
                SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX));

             if(wayx->way.allow==transports)
               {
                prune_segment(segmentsx,segmentx);

                npruned++;
               }
             else
               {
                if(segmentx->way<waysx->number) /* create a new way */
                  {
                   tmpwayx=*wayx;

                   tmpwayx.way.allow&=~transports;

                   segmentx->way=waysx->number+newwaysx->number;

                   SlimReplace(newwaysx->fd,&tmpwayx,sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX));

                   newwaysx->number++;

                   PutBackSegmentX(segmentsx,segmentx);
                  }
                else            /* modify the existing one */
                  {
                   tmpwayx.way.allow&=~transports;

                   SlimReplace(newwaysx->fd,&tmpwayx,sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX));
                  }

                nadjusted++;
               }
            }
         }
       else                     /* connected - mark as part of the main region */
         {
          for(j=0;j<nregionsegments;j++)
            {
             SetBit(connected,regionsegments[j]);
             ClearBit(region,regionsegments[j]);
            }

          for(j=0;j<nothersegments;j++)
            {
             SetBit(connected,othersegments[j]);
             ClearBit(region,othersegments[j]);
            }
         }

      endloop:

       if(!((i+1)%10000))
          printf_middle("Pruning Isolated Regions (%s): Segments=%"Pindex_t" Adjusted=%"Pindex_t" Pruned=%"Pindex_t" (%"Pindex_t" Regions)",transport_str,i+1,nadjusted,npruned,nregions);
      }

    /* Print the final message */

    printf_last("Pruned Isolated Regions (%s): Segments=%"Pindex_t" Adjusted=%"Pindex_t" Pruned=%"Pindex_t" (%"Pindex_t" Regions)",transport_str,segmentsx->number,nadjusted,npruned,nregions);
   }

 /* Unmap from memory / close the files */

 free(region);
 free(connected);

 free(regionsegments);
 free(othersegments);

#if !SLIM
 nodesx->data=UnmapFile(nodesx->data);
 segmentsx->data=UnmapFile(segmentsx->data);
 waysx->data=UnmapFile(waysx->data);
#else
 nodesx->fd=SlimUnmapFile(nodesx->fd);
 segmentsx->fd=SlimUnmapFile(segmentsx->fd);
 waysx->fd=SlimUnmapFile(waysx->fd);
#endif

 SlimUnmapFile(newwaysx->fd);

 waysx->number+=newwaysx->number;

 waysx->fd=OpenFileBufferedAppend(waysx->filename_tmp);

 newwaysx->fd=ReOpenFileBuffered(newwaysx->filename_tmp);

 while(!ReadFileBuffered(newwaysx->fd,&tmpwayx,sizeof(WayX)))
    WriteFileBuffered(waysx->fd,&tmpwayx,sizeof(WayX));

 CloseFileBuffered(waysx->fd);
 CloseFileBuffered(newwaysx->fd);

 FreeWayList(newwaysx,0);
}
Example #28
0
local struct MapDownloadData * compress_map(const char *fname, int docomp)
{
	byte *cmap;
	uLong csize;
	const char *mapname;
	struct MapDownloadData *data;
	MMapData *mmd;

	data = amalloc(sizeof(*data));

	/* get basename */
	mapname = strrchr(fname, '/');
	if (!mapname)
		mapname = fname;
	else
		mapname++;
	astrncpy(data->filename, mapname, 20);

	mmd = MapFile(fname, FALSE);
	if (!mmd)
		goto fail1;

	/* calculate crc on mmap'd map */
	data->checksum = crc32(crc32(0, Z_NULL, 0), mmd->data, mmd->len);
	data->uncmplen = mmd->len;

	/* allocate space for compressed version */
	if (docomp)
		csize = (uLong)(1.0011 * mmd->len + 35);
	else
		csize = mmd->len + 17;

	cmap = malloc(csize);
	if (!cmap)
	{
		lm->Log(L_ERROR, "<mapnewsdl> malloc failed in compress_map for %s", fname);
		goto fail2;
	}

	/* set up packet header */
	cmap[0] = S2C_MAPDATA;
	strncpy((char*)(cmap+1), mapname, 16);

	if (docomp)
	{
		/* compress the stuff! */
		compress(cmap+17, &csize, mmd->data, mmd->len);
		csize += 17;

		/* shrink the allocated memory */
		data->cmpmap = realloc(cmap, csize);
		if (data->cmpmap == NULL)
		{
			lm->Log(L_ERROR, "<mapnewsdl> realloc failed in compress_map for %s", fname);
			goto fail3;
		}
	}
	else
	{
		/* just copy */
		memcpy(cmap+17, mmd->data, mmd->len);
		data->cmpmap = cmap;
	}

	data->cmplen = csize;

	if (csize > 256*1024)
		lm->Log(L_WARN, "<mapnewsdl> compressed map/lvz is bigger than 256k: %s", fname);

	UnmapFile(mmd);

	return data;

fail3:
	free(cmap);
fail2:
	UnmapFile(mmd);
fail1:
	afree(data);
	return NULL;
}
Example #29
0
int
CreateMaps(struct Session *s, unsigned int number)
{
    int i;
    struct Map *temp;
    char       *filename = s->input;

    temp        = NULL;
    s->maps     = NULL;

    for(i = 0; i < number; i++)
    {
        if(!(temp = (struct Map *) calloc(1, sizeof(struct Map))))
        {
            perror("[!]	CreateMaps()::malloc");
            goto err;
        }

        temp->next = s->maps;
        s->maps    = temp;

        set_id(temp, i);

        /* Build a map name */
        if((temp->name = GetMapName(temp, filename)) == NULL)
        {
            fprintf(stderr, "[!] Cannot get the map name\n");
            goto err;
        }

        /* Duplicate the file */
        if(CopyFile(filename, temp->name) != 0)
        {
            fprintf(stderr, "[!] Cannot copy from map\n");
            free(temp->name);
            goto err;
        }

        /* Do the real mmap */
        if((temp->size = MapFile(temp->name, &(temp->address))) <= 0)
        {
            fprintf(stderr, "[!] Error mapping file\n");
            free(temp->name);
            goto err;
        }
    }

    return 0;

err:

    /* FIXME: just wrong, lazzy ... :| */
    if(temp != NULL)
    {
        s->maps = temp->next;
    }

    /* Free the memory mapped files */
    FreeMaps(s->maps);

    /* Free the linked list of mappings */
    FreeMapList(s->maps);

    free(temp);

    return -1;
}
Example #30
0
/*++

Routine Description:
  Main entry point to SEC for Unix. This is a unix program

Arguments:
  Argc - Number of command line arguments
  Argv - Array of command line argument strings
  Envp - Array of environment variable strings

Returns:
  0 - Normal exit
  1 - Abnormal exit

**/
int
main (
  IN  int   Argc,
  IN  char  **Argv,
  IN  char  **Envp
  )
{
  EFI_STATUS            Status;
  EFI_PHYSICAL_ADDRESS  InitialStackMemory;
  UINT64                InitialStackMemorySize;
  UINTN                 Index;
  UINTN                 Index1;
  UINTN                 Index2;
  UINTN                 PeiIndex;
  CHAR8                 *FileName;
  BOOLEAN               Done;
  EFI_PEI_FILE_HANDLE   FileHandle;
  VOID                  *SecFile;
  CHAR16                *MemorySizeStr;
  CHAR16                *FirmwareVolumesStr;
  UINTN                 *StackPointer;
  FILE                  *GdbTempFile;

  //
  // Xcode does not support sourcing gdb scripts directly, so the Xcode XML
  // has a break point script to source the GdbRun script.
  //
  SecGdbConfigBreak ();

  //
  // If dlopen doesn't work, then we build a gdb script to allow the
  // symbols to be loaded.
  //
  Index = strlen (*Argv);
  gGdbWorkingFileName = AllocatePool (Index + strlen(".gdb") + 1);
  strcpy (gGdbWorkingFileName, *Argv);
  strcat (gGdbWorkingFileName, ".gdb");

  //
  // Empty out the gdb symbols script file.
  //
  GdbTempFile = fopen (gGdbWorkingFileName, "w");
  if (GdbTempFile != NULL) {
    fclose (GdbTempFile);
  }

  printf ("\nEDK II UNIX Host Emulation Environment from http://www.tianocore.org/edk2/\n");

  setbuf (stdout, 0);
  setbuf (stderr, 0);

  MemorySizeStr      = (CHAR16 *) PcdGetPtr (PcdEmuMemorySize);
  FirmwareVolumesStr = (CHAR16 *) PcdGetPtr (PcdEmuFirmwareVolume);

  //
  // PPIs pased into PEI_CORE
  //
  AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, &mSecEmuThunkPpi);

  SecInitThunkProtocol ();

  //
  // Emulator Bus Driver Thunks
  //
  AddThunkProtocol (&gX11ThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuGop), TRUE);
  AddThunkProtocol (&gPosixFileSystemThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuFileSystem), TRUE);
  AddThunkProtocol (&gBlockIoThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuVirtualDisk), TRUE);
  AddThunkProtocol (&gSnpThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuNetworkInterface), TRUE);

  //
  // Emulator other Thunks
  //
  AddThunkProtocol (&gPthreadThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuApCount), FALSE);

  // EmuSecLibConstructor ();

  gPpiList = GetThunkPpiList ();

  //
  // Allocate space for gSystemMemory Array
  //
  gSystemMemoryCount  = CountSeparatorsInString (MemorySizeStr, '!') + 1;
  gSystemMemory       = AllocateZeroPool (gSystemMemoryCount * sizeof (EMU_SYSTEM_MEMORY));
  if (gSystemMemory == NULL) {
    printf ("ERROR : Can not allocate memory for system.  Exiting.\n");
    exit (1);
  }
  //
  // Allocate space for gSystemMemory Array
  //
  gFdInfoCount  = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;
  gFdInfo       = AllocateZeroPool (gFdInfoCount * sizeof (EMU_FD_INFO));
  if (gFdInfo == NULL) {
    printf ("ERROR : Can not allocate memory for fd info.  Exiting.\n");
    exit (1);
  }

  printf ("  BootMode 0x%02x\n", (unsigned int)PcdGet32 (PcdEmuBootMode));

  //
  // Open up a 128K file to emulate temp memory for SEC.
  //  on a real platform this would be SRAM, or using the cache as RAM.
  //  Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
  //
  InitialStackMemorySize  = STACK_SIZE;
  InitialStackMemory = (UINTN)MapMemory (
                                0, (UINT32) InitialStackMemorySize,
                                PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE
                                );
  if (InitialStackMemory == 0) {
    printf ("ERROR : Can not open SecStack Exiting\n");
    exit (1);
  }

  printf ("  OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n",
    (unsigned int)(InitialStackMemorySize / 1024),
    (unsigned long)InitialStackMemory
    );

  for (StackPointer = (UINTN*) (UINTN) InitialStackMemory;
     StackPointer < (UINTN*)(UINTN)((UINTN) InitialStackMemory + (UINT64) InitialStackMemorySize);
     StackPointer ++) {
    *StackPointer = 0x5AA55AA5;
  }

  //
  // Open All the firmware volumes and remember the info in the gFdInfo global
  //
  FileName = (CHAR8 *) AllocatePool (StrLen (FirmwareVolumesStr) + 1);
  if (FileName == NULL) {
    printf ("ERROR : Can not allocate memory for firmware volume string\n");
    exit (1);
  }

  Index2 = 0;
  for (Done = FALSE, Index = 0, PeiIndex = 0, SecFile = NULL;
       FirmwareVolumesStr[Index2] != 0;
       Index++) {
    for (Index1 = 0; (FirmwareVolumesStr[Index2] != '!') && (FirmwareVolumesStr[Index2] != 0); Index2++) {
      FileName[Index1++] = FirmwareVolumesStr[Index2];
    }
    if (FirmwareVolumesStr[Index2] == '!') {
      Index2++;
    }
    FileName[Index1]  = '\0';

    if (Index == 0) {
      // Map FV Recovery Read Only and other areas Read/Write
      Status = MapFd0 (
                FileName,
                &gFdInfo[0].Address,
                &gFdInfo[0].Size
                );
    } else {
      //
      // Open the FD and remember where it got mapped into our processes address space
      // Maps Read Only
      //
      Status = MapFile (
                FileName,
                &gFdInfo[Index].Address,
                &gFdInfo[Index].Size
                );
    }
    if (EFI_ERROR (Status)) {
      printf ("ERROR : Can not open Firmware Device File %s (%x).  Exiting.\n", FileName, (unsigned int)Status);
      exit (1);
    }

    printf ("  FD loaded from %s at 0x%08lx",FileName, (unsigned long)gFdInfo[Index].Address);

    if (SecFile == NULL) {
      //
      // Assume the beginning of the FD is an FV and look for the SEC Core.
      // Load the first one we find.
      //
      FileHandle = NULL;
      Status = PeiServicesFfsFindNextFile (
                  EFI_FV_FILETYPE_SECURITY_CORE,
                  (EFI_PEI_FV_HANDLE)(UINTN)gFdInfo[Index].Address,
                  &FileHandle
                  );
      if (!EFI_ERROR (Status)) {
        Status = PeiServicesFfsFindSectionData (EFI_SECTION_PE32, FileHandle, &SecFile);
        if (!EFI_ERROR (Status)) {
          PeiIndex = Index;
          printf (" contains SEC Core");
        }
      }
    }

    printf ("\n");
  }

  if (SecFile == NULL) {
    printf ("ERROR : SEC not found!\n");
    exit (1);
  }

  //
  // Calculate memory regions and store the information in the gSystemMemory
  //  global for later use. The autosizing code will use this data to
  //  map this memory into the SEC process memory space.
  //
  Index1 = 0;
  Index = 0;
  while (1) {
    UINTN val = 0;
    //
    // Save the size of the memory.
    //
    while (MemorySizeStr[Index1] >= '0' && MemorySizeStr[Index1] <= '9') {
      val = val * 10 + MemorySizeStr[Index1] - '0';
      Index1++;
    }
    gSystemMemory[Index++].Size = val * 0x100000;
    if (MemorySizeStr[Index1] == 0) {
      break;
    }
    Index1++;
  }

  printf ("\n");

  //
  // Hand off to SEC
  //
  SecLoadFromCore ((UINTN) InitialStackMemory, (UINTN) InitialStackMemorySize, (UINTN) gFdInfo[0].Address, SecFile);

  //
  // If we get here, then the SEC Core returned. This is an error as SEC should
  //  always hand off to PEI Core and then on to DXE Core.
  //
  printf ("ERROR : SEC returned\n");
  exit (1);
}