View Single Post
  #3  
Old 07-09-2004, 11:47
Lunar_Dust
 
Posts: n/a
I have source code that I use, looking thru it should help you understand at least a bit, it shows the structures you talk about:

Code:
// Converts an RVA virtual address to a file offset.
DWORD RvaToOffset(LPVOID dwFileBase, DWORD Rva)
{

	IMAGE_DOS_HEADER *DosHeader;
	IMAGE_NT_HEADERS * MainPEHeader;
	LPVOID PEHeader = NULL;
	LPVOID pSection = NULL;
	IMAGE_SECTION_HEADER* Section=NULL;
	long NumberOfSections;

	DosHeader = (IMAGE_DOS_HEADER*)dwFileBase;
	PEHeader = (LPVOID)((DWORD)dwFileBase + (DWORD)DosHeader->e_lfanew);

	MainPEHeader = (IMAGE_NT_HEADERS*)PEHeader;
	NumberOfSections = MainPEHeader->FileHeader.NumberOfSections;

	pSection = (LPVOID)((DWORD)PEHeader + sizeof(IMAGE_NT_HEADERS));

	for (int Count=0;Count <= NumberOfSections;Count++)
	{
		
		Section = (IMAGE_SECTION_HEADER*)pSection;
		if (Rva >= Section->VirtualAddress)
		{
			if (Rva < (Section->VirtualAddress + Section->SizeOfRawData))
			{
				// it's in this section..
				long AddressDiff = Rva - Section->VirtualAddress;
				return (Section->PointerToRawData + AddressDiff);

			}
		}
	
	pSection = (LPVOID)((DWORD)pSection + sizeof(IMAGE_SECTION_HEADER));

	}

	return 0;

}




// Converts a file offset to a RVA address
DWORD OffsetToRva(LPVOID dwFileBase, DWORD Offset)
{

	IMAGE_DOS_HEADER *DosHeader;
	IMAGE_NT_HEADERS * MainPEHeader;
	LPVOID PEHeader = NULL;
	LPVOID pSection = NULL;
	IMAGE_SECTION_HEADER* Section=NULL;
	long NumberOfSections;

	DosHeader = (IMAGE_DOS_HEADER*)dwFileBase;
	PEHeader = (LPVOID)((DWORD)dwFileBase + (DWORD)DosHeader->e_lfanew);

	MainPEHeader = (IMAGE_NT_HEADERS*)PEHeader;
	NumberOfSections = MainPEHeader->FileHeader.NumberOfSections;

	pSection = (LPVOID)((DWORD)PEHeader + sizeof(IMAGE_NT_HEADERS));

	for (int Count=0;Count <= NumberOfSections;Count++)
	{
		
		Section = (IMAGE_SECTION_HEADER*)pSection;
		if (Offset >= Section->PointerToRawData)
		{
			if (Offset < (Section->PointerToRawData + Section->SizeOfRawData))
			{
				// it's in this section..
				long AddressDiff = Offset - Section->PointerToRawData;
				return (Section->VirtualAddress + AddressDiff);

			}
		}
	
	pSection = (LPVOID)((DWORD)pSection + sizeof(IMAGE_SECTION_HEADER));

	}

	return 0;

}



-Lunar
Reply With Quote