Search code examples
assemblygcclinker

Writing an __attribute((constructor)) function in assembly - can it be done?


I have been writing a Forth in assembly and now want to give users the option of loading modules and not have the whole thing as one monolithic lump of code.

There seem to be several options for this, but I am looking at having the modules as shared libraries and as such they need initialisation code to plug their Forth words into the dictionary.

I am using GNU tools - but how do I write an __attributes((constructor)) function in assembly? As I understand it this construct (ie __attributes((constructor))) isn't the name of the function but something that gives a function the attribute of being called on initialisation (eg https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html).

But I cannot find any resources that say what the function itself is called/how it's named, never mind how to use this construct in assembly: can it be done at all?


Solution

  • You need to create an SHT_INIT_ARRAY section containing the array of function pointers to run. (I'm assuming this is for a current ELF target.) This is described in the ELF specification:

    As a starting point, you can examine gcc -S output.