Why do gcc and clang place custom-sectioned const-funcptr symbols into writable sections when compiling with -fpic?

181 Views Asked by At

The program below demonstrates the issue:

void f(void){}

__attribute((section("mysect"),used))
void (* const fp)(void)=&f; //const fn ptr placed in a WR segment iff compiled with -fpic AND a custom section is used

//__attribute((section("mysect2"))) int const x=42; //var stays in a RO segment even if placed in a custom section

int main()
{
    extern char __start_mysect,__start_mysect2;
    __start_mysect = 0; //succeeds iff the custom section is used and the program is compiled with -fpic
    //I would expect (and like) a segmentation violation

    /*__start_mysect2 = 0; //segfaults as expected */
}

Why does -fpic cause the section that the const funcptr is in to become writable?

I was told it's because of runtime relocations but without the custom section, the const-variable gets runtime-relocated at load time just fine.

I'm trying to use a custom section so that I can iterate over a bunch of const function pointers aggregated from different places into a single section. Can I do so without causing the section to become writable?

0

There are 0 best solutions below