"""
name: Remap sections Physical <=> Virtual 
category: pe
filetype: PE
author: malcat
icon: wxART_FILE_COMPARE

Set all section physical offsets and size to their virtual counterparts. Run this script if your sample has been badly dumped.

"""

def align(val, what, down=False):
    if val % what:
        if down:
            val -= val % what
        else:
            val += what - (val % what)
    return val

if not analysis.type == "PE":
    raise ValueError("Only works for PE files")

done = 0
section_align = analysis.struct["OptionalHeader"]["SectionAlignment"]
for section in analysis.struct["Sections"]:
    if section["VirtualAddress"] and section["VirtualSize"]:
        if section["PointerToRawData"] != section["VirtualAddress"]:
            section["PointerToRawData"] = section["VirtualAddress"]
            section["SizeOfRawData"] = align(section["VirtualSize"], section_align)
            done += 1

print(f"{done} sections remapped!")
