Re: How to run code before global constructors?
From: David Schwartz (davids_at_webmaster.com)
Date: Thu, 24 Jul 2003 12:39:49 -0700
"Paul Pluzhnikov" <firstname.lastname@example.org> wrote in message
> "David Schwartz" <email@example.com> writes:
> > I have a program that needs to install a signal handler before any
> > global constructors are called. (The global constructors do things that
> > cause signals to be received that need to be properly handled.)
> Perhaps these constructors need to ensure that signals are handled
> properly, then?
Not easy. The constructors call low-level code that is heavily
micro-optimized. An extra test for initialization would destroy the whole
point of the signal handler. The code is designed to fault if it's not
initialized and the signal handler handles the fault by doing the
I can't do the initialization directly anyway because there's any number
of places that might need to be initialized and there's no way to find all
of them before global constructors finish running. So I've rigged it so that
uninitialized sections fault and the fault handler does the initialization.
An analogy that might help is if you imagine a program that has two
run-time modes. In one run mode, a piece of inline low-level assembly code
called from many places has to increment a variable and in the other run
mode it has to decrement it. So instead of an increment or decrement
instruction, you put an illegal opcode. In the SIGILL handler, you check
which run mode you're in and replace the illegal opcode with the correct
This works perfectly until a global constructor calls something that
uses this inline code.
> You could provide e.g. strrchr() implementation in your a.elf, and it
> will be called during libc.so initialization (very early in the process'
That's not a bad idea, actually.
> Beware: libc has not finished initializing itself yet, so be *very*
> restricted in using libc at that point. I think calling sigaction()
> is ok though.
If I had to, I could make the system call directly. This only has to
work on Linux right now, but ultimately would be nice to have on FreeBSD as
It now does work on Linux, using the gmon startup hook.