Search code examples
cwindowsx86portable-executable

Is there a way to find addresses of the code sections (.data, .text, etc) at runtime?


I want to write some code that will print the addresses and lengths of each of the code sections in its own process when run. Is there an easy way to do this? I know it is relatively easy to find the location of functions like main using code like void* main_address = main;, but I want to find sections like .data and .text and I don't know if I can do the same thing with them when I compile. I am writing this experiment on a Windows system and compiling for the x86 architecture. I know a little x86 assembly if that is necessary for the solution. I would really appreciate any help or advice. Thanks!


Solution

  • simply walk by PIMAGE_SECTION_HEADER s

    void DumpSections()
    {
        //PIMAGE_NT_HEADERS pinth = (PIMAGE_NT_HEADERS)((PBYTE)&__ImageBase + reinterpret_cast<PIMAGE_DOS_HEADER>(&__ImageBase)->e_lfanew);
        if (PIMAGE_NT_HEADERS pinth = RtlImageNtHeader(&__ImageBase))
        {
            if (ULONG NumberOfSections = pinth->FileHeader.NumberOfSections)
            {
                PIMAGE_SECTION_HEADER pish = IMAGE_FIRST_SECTION(pinth);
    
                do 
                {
                    DbgPrint("%p %08x %.8s\n", (PBYTE)&__ImageBase + pish->VirtualAddress, pish->Misc.VirtualSize, pish->Name);
                } while (pish++, --NumberOfSections);
            }
        }
    }