https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107010
Bug ID: 107010
Summary: iterate section("mysection") struct mystruct fails if
first node is const and compiling with O2 or greater
Product: gcc
Version: 12.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: stian.skjelstad at gmail dot com
Target Milestone: ---
Created attachment 53612
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=53612&action=edit
example setup compiled with both working and non-working flags
I have a use-case where plugins can be be compiled built in, and they are
detected by having some meta-data added to a section, and in runtime they can
be iterated.
#define SECTION __attribute__ ((section ("plugin_list")))
#define USED __attribute__ ((used))
Core code:
SECTION const struct plugindata first = {"dummy", 0, 0};
Each plugin (many copies):
SECTION USED static const struct plugindata = {"pluginname", foo, bar};
Last file linked contains a terminator
SECTION USED static const struct plugindata end = {0, 0, 0};
During linking they will gathered and can iterated using code like this:
void show_plugin_names(void)
{
const struct plugindata *iterator = &first;
while (iterator->name)
{
fprintf (stderr, "name=%s\n", iterator->name);
iterator++;
}
}
This works as long as you do not combine "first" being const and using gcc -O2
Tested with:
gcc-9 (Ubuntu 9.4.0-5ubuntu1) 9.4.0
gcc-10 (Ubuntu 10.3.0-15ubuntu1) 10.3.0
gcc-11 (Ubuntu 11.2.0-19ubuntu1) 11.2.0
gcc-12 (Ubuntu 12.1.0-2ubuntu1~22.04) 12.1.0
(using clang works)
I have also tested -fno-strict-aliasing -fwrapv and it didn't change the
behaviour.
I do accept that the use-case is probably a bit unorthodox and that it might be
dismissed as compiler-abuse.