makeelf icon indicating copy to clipboard operation
makeelf copied to clipboard

Link program headers to sections

Open fenkes-ibm opened this issue 3 years ago • 5 comments

Allow the caller to specify a section to associate a program header to. This will allow the ELF writer to determine a correct file offset for the program header (the file offset of the lowest associated section).

fenkes-ibm avatar Sep 15 '21 11:09 fenkes-ibm

This is the minimal change needed to solve a problem of mine, which was to generate core dump files from scratch. If you'd like some testcase, example usage or fancier implementation I'm open to suggestions of course :) (I also noticed the similar but more fully featured PR that's also open; while that is stewing maybe this is a more lightweight change just to scratch this one itch :) )

fenkes-ibm avatar Sep 15 '21 11:09 fenkes-ibm

Yes, would be great if you provide some test vector for that. I am not developing this project actively, so I guess it would be easier for you than for me at the moment.

v3l0c1r4pt0r avatar Sep 16 '21 11:09 v3l0c1r4pt0r

Been a while, sorry for the long wait - here's a test :) Let me know what you think.

fenkes-ibm avatar Oct 28 '21 17:10 fenkes-ibm

I also suggest to add function that maps sections to segments to allow changing sizes of sections without segments offsets breaking.

It makes "one allocated section -> one loaded segment" assumption though

    ## Try to find a mapping from sections to segments to allow to move them around
    def map_sections_to_segments(self):
        def intersects(a, b):
            a1, a2 = a
            b1, b2 = b
            res = a2 > b1 and b2 > a1
            return res

        sec: Elf32_Shdr
        seg: Elf32_Phdr
        for i, sec in enumerate(self.Elf.Shdr_table[1:], 1):
            if sec.sh_flags & SHF.SHF_ALLOC == 0:
                continue
            sec_rg = (sec.sh_addr, sec.sh_addr + sec.sh_size)
            for j, seg in enumerate(self.Elf.Phdr_table[1:], 1):
                if seg.p_type != PT.PT_LOAD:
                    continue
                seg_rg = (seg.p_vaddr, seg.p_vaddr + seg.p_memsz)
                if not intersects(sec_rg, seg_rg):
                    continue
                assert sec_rg[0] >= seg_rg[0] and sec_rg[1] <= seg_rg[1], "Sections cannot span multiple segments!"
                
                seg.sections.append(i)
                break

DCNick3 avatar Dec 01 '21 16:12 DCNick3

I also suggest to add function that maps sections to segments to allow changing sizes of sections without segments offsets breaking.

May I ask you to add that via a PR of your own? I'm glad I had the time to add test vectors for my change, and I have a feeling @v3l0c1r4pt0r will be (rightfully) asking for test vectors for your function as well :)

fenkes-ibm avatar Dec 01 '21 20:12 fenkes-ibm