Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

346
Views
How to append to __preinit_array_start on Linux?

On Linux with GCC if I define

__attribute__((constructor)) static void myfunc(void) {}

, then the address of myfunc will be appended to __init_array_start in the .ctors section. But how can I append a function pointer to __preinit_array_start?

Is __preinit_array_start relevant in a statically linked binary?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As there's no __attribute__((preconstructor)), you can just mush the code into the relevant section using some section attributes e.g.

#include <stdio.h>

int v;
int w;
int x;

__attribute__((constructor)) static void
foo(void)
{
    printf("Foo %d %d %d\n", v, w, x);
}

static void
bar(void)
{
    v = 3;
}

static void
bar1(void)
{
    w = 2;
}

static void
bar2(void)
{
    x = 1;
}

__attribute__((section(".preinit_array"))) static void (*y[])(void) = { &bar, &bar1, &bar2 };

int
main(int argc, char **argv)
{
    printf("Hello World\n");
}

File dumped into foo.c, compiled using: gcc -o foo foo.c, and then run yields an output of:

Foo 3 2 1
Hello World

File compiled using gcc -static -o foo foo.c, and then run yields the same output, so it does appear to work with statically linked binaries.

It will not work with .so files, though; the linker complains with:

/usr/bin/ld: /tmp/ccI0lMgd.o: .preinit_array section is not allowed in DSO
/usr/bin/ld: failed to set dynamic section sizes: Nonrepresentable section on output

I'd be inclined to avoid it, as code run in that section precedes all other initialization routines. If you're trying to perform some 'this is supposed to run first' initialization, then it's really not a good idea - you're just fighting a race condition which should be solved by some other mechanism.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!