Washi1337 / AsmResolver

A library for creating, reading and editing PE files and .NET modules.
https://docs.washi.dev/asmresolver/
MIT License
848 stars 127 forks source link

How to get RVA of added section #409

Closed MMitsuha closed 1 year ago

MMitsuha commented 1 year ago

Description

I added a section with some content to a PEFile and I have to get the RVA of the section in order to set new AddressOfEntryPoint, but I found that both AddedContent.Rva and AddedSection.Rva are always 0x1000

Here is my code:

var AddedContent = /* Some content */
var AddedSection = new PESection(".hack", SectionFlags.ContentCode | SectionFlags.MemoryRead | SectionFlags.MemoryExecute);
AddedSection.Contents = AddedContent;

OriginalFile.Sections.Add(AddedSection);
OriginalFile.OptionalHeader.AddressOfEntryPoint = AddedContent.Rva + CodeEntryPointOffset;
// OriginalFile.OptionalHeader.AddressOfEntryPoint = AddedSection.Rva + CodeEntryPointOffset;
// Both always 0x1000

OriginalFile.Write(@".\Modified.exe");

image

Washi1337 commented 1 year ago

For performance reasons, AsmResolver does not calculate offsets and sizes unless you tell it to. Thus, make sure that you align all sections accordingly after adding the new section to the file, but before you retrieve their new RVAs. This can be done either by calling OriginalFile.UpdateHeaders() or OriginalFile.AlignSections(). Both of them calculate offsets, and have slightly different meanings. In short, UpdateHeaders aligns sections but also updates some fields in the PE headers accordingly. You can refer to the the xmldocs attached to these methods to figure out these differences.