How to start the constructor even if the -nostdlib option is defined

I have a dynamic library containing a constructor.

__attribute__ ((constructor))
void construct() {
    // This is initialization code
}

The library is compiled with an option -nostdlib, and I cannot change it. As a result, the library has no .ctorand sections .dtor, and the constructor does not work on loading the library.

As written there, there must be special measures that allow you to run the constructor even in this case. Could you advise me what and how to do it?

+3
source share
3 answers

? , , , , , main. , , - OpenAL, , , . , , , - ALSA ALSA .

, , . , , , . - , , pthread_once .

0

.init_array/.fini_array /. .

0

, , .ctor .dtor... .

#include <stdio.h>
#include <stdint.h>

typedef void (*func)(void);

__attribute__((constructor))
void func1(void) {
     printf("func1\n");
}

__attribute__((constructor))
void func2(void) {
     printf("func2\n");
}

extern func* __init_array_start;

int main(int argc, char **argv)
{
     func *funcarr = (func*)&__init_array_start;
     func f;
     int idx;

     printf("start %p\n", *funcarr);

     // iterate over the array
     for (idx = 0; ; ++idx) {
          f = funcarr[idx];

          // skip the end of array marker (0xFFFFFFFF) on 64 bit it twice as long ;)
          if (f == (void*)~0)
               continue;

          // till f is NULL which indicates the start of the array
          if (f == NULL)
               break;

          printf("constructor %p\n", *f);
          f();
     }

     return 0;
}

:

Compilation started at Fri Mar  9 09:28:29

make test && ./test
 cc     test.c   -o test
 func2
 func1
 start 0xffffffff
 constructor 0x80483f4
 func1
 constructor 0x8048408
 func2

, , Big Endian, .

But just like R .. declared using static constructors in libraries is not so good for developers using your library: p

0
source

Source: https://habr.com/ru/post/1786941/


All Articles