Bug 96221 - Constructor attribute priority is ignored if additional prototypes omit attribute
Summary: Constructor attribute priority is ignored if additional prototypes omit attri...
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 8.3.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Keywords: wrong-code
Depends on:
Reported: 2020-07-16 15:16 UTC by Stephen Kell
Modified: 2020-07-17 06:50 UTC (History)
0 users

See Also:
Known to work:
Known to fail:
Last reconfirmed:

Minimal test case (456 bytes, application/gzip)
2020-07-16 15:16 UTC, Stephen Kell

Note You need to log in before you can comment on or make changes to this bug.
Description Stephen Kell 2020-07-16 15:16:06 UTC
Created attachment 48882 [details]
Minimal test case

I was surprised to find that my __attribute__((constructor(101))) on a function was not giving it priority over another constructor whose attribute used a higher number. It turns out this was owing to an additional prototype that did not mention the function as a constructor.

This caused a really subtle initialization bug in my code, and was tough to track down. At the least, I would expect a warning when the information is discarded.

I haven't tried on 8.4, but didn't see any relevant changelog entries.

Note that this is not a duplicate of 87592, which is about when the priority is specified multiple times.

$ cat test.c
// comment these for correct behaviour, i.e. 1 then 2
static void do_init1(void);
static void do_init2(void);

static void do_init2(void) __attribute__((constructor(102)));
static void do_init2(void)
        printf("Init 2!\n");

static void do_init1(void) __attribute__((constructor(101)));
static void do_init1(void)
        printf("Init 1!\n");

int main(void)
        return 0;

$ cc -save-temps    test.c   -o test
$ ./test
Init 2!
Init 1!
$ grep -B2 init_array test.s
        .size   do_init2, .-do_init2
        .section        .init_array,"aw"
        .size   do_init1, .-do_init1
        .section        .init_array

The attribute's priority argument is being discarded. It should be visible in the section name (".init_array.0101" etc.). If the extra prototypes are removed, the programmer-intended behaviour is restored.