Skip to content

Constructors, Destructors, Managed Lists

Stefan "Bebbo" Franke edited this page Nov 1, 2022 · 2 revisions

Intro

C-Compiler are using lists of data to perform various tasks to perform automatic intialization etc. The https://github.com/bebbo/libnix library is also using some lists, which now differ from the old format, which is still used in newlib and clib2.

Reasons

  • the constructors do only exist in few targets, they don't exist in elf.
  • constructors require the stab debug format, switching to the modern/better dwarf format is not possible.
  • using sections per function or c++ sometimes ended up with bogus constructors since the constructors hack is not aware of that many sections.
  • lists can't be but into the data segment.

Old Format

A constructor contains long word list looked like

list:
   .long <N = count of longs>
   .long value1
   ...
   .long valueN
   .long 0

Most code relies on the terminating zero.

New Format

list1:
   .long 0
   .long value1
   ...
   .long valueN
list2:
   .long 0
   ...
end_of_lists:
   .long 0

By concatenating all lists and adding a single terminating zero, the new format is almost the same. Only the count vanished.

New Format for LIB_LIST

Since lists now can be put into the data segment, there is no longer a need to put an additional list of pointers into the .text segment. Also no workaround is needed to reference the correct data segment in baserel or resident programs.

The LIB_LIST was a list of pointers to the pairs of base and name. It was replaced by a list of base and name. To get it work together with the zero detection, all bases are set to -1. There is no zero in the list.

The code to use the LIB_LIST is found here https://github.com/bebbo/libnix/blob/master/sources/nix/misc/__initlibraries.c

section names and linking

All members of a list are using the same section name:

  • lists for the .text segment are using a section name starting with .list_
  • lists for the .data segment are using a section name starting with .dlist_

To create the leading zero for a list you may use the feature that the section names are sorted by name. This is e.g. used to collect the exception handling stuff:

  • all list stuff is placed into the section .list___EH_FRAME_BEGINS__
  • the leading zero is placed into the section .list___EH_FRAME_BEGIN

The sorting puts the mandatory leading zero right in front of the values.