Linker : Make a map of typeinfo to vtable

Frederick Virchanza Gotham cauldwell.thomas@gmail.com
Sat Jan 27 10:56:44 GMT 2024


On Thu, Jan 25, 2024 at 11:02 PM Frederick Virchanza Gotham wrote:
>
> So then after I call 'ldwrite' and have produced the final binary file, I
> re-open the binary file and I scan through it until I find my magic
> number (i.e. 3c1fed6f74bb6c814173c5409cb7d0aa), and I replace it with
> the correct data.


I wasn't able to get much help with how 'ld' or 'libbfd' works so I
had to get creative. I have gotten my new feature for the GNU bfd
linker working, here's my latest code:

    https://github.com/bminor/binutils-gdb/compare/8409b75...healytpk:linker-vtable:e4adc46

Here's what I had to do:

(1) In 'main', I add another string to the end of 'argv' for another
object file (e.g. "/tmp/linker_9821421740127.c.o"). This object file
doesn't exist yet.
(2) In '_bfd_generic_link_add_one_symbol', I keep a record of all
typeinfo's and vtables encountered. I keep a count of matching pairs.
(3) In 'load_symbols', I keep a watch out for
"/tmp/linker_9821421740127.c.o", and I generate this object file at
the point it's requested by using 'gcc' to compile a simple C source
file which contains a definition for the array
'__map_typeinfo_vtable'. The size of this array depends upon the count
of matching pairs.
(4) The newly-generated object file contains the symbol
'__map_typeinfo_vtable' inside the section ".data.rel.ro", but the
array is all zeroes.
(5) After 'ldwrite' is called and the final output file has been
written, I then check what the offset of each symbol is by looking at
"link_info.output_bfd". I make an array of these offsets and I sort
it.
(6) I re-open the output file in binary mode, and I seek to the
location of '__map_typeinfo_vtable', and I write the real array
contents to the file.

I have this tested and working. I've written a C++ program that does a
binary search through '__map_typeinfo_vtable' in order to map a
typeinfo to a vtable, and I can then use that to convert a virtual
function pointer into a direct function pointer.

It's cool that I've gotten this working but it's a little bit
Frankensteinish in places. Instead of appending a new object file to
the end of the command line, it would be nice if I could just call a
function in 'libbfd' to manually add the symbol
'__map_typeinfo_vtable' -- but I don't know how to do this. And
instead of re-opening the output file and overwriting the zeroed-out
array, it would be nice if I could write it correctly the first time.

If anyone has any pointers here, please help me out. Here's my latest
post on the C++ proposals mailing list showing my C++ code:

    https://lists.isocpp.org/std-proposals/2024/01/8948.php

I'm hoping to either put this linker up on GodBolt or to host it on my
own webspace if I can.


More information about the Binutils mailing list