A great comment on my answer describing how to use linker scripts to make a ctor-like function list pointed out that recent GNU ld has much开发者_StackOverflow社区 improved support for grafting new sections into system linker scripts with -Wl,-T...
and INSERT BEFORE
/INSERT AFTER
. This got me thinking about other linker script tricks.
For a network card firmware I modified the linker script to group together the runtime modules of the firmware so that they would all be in a contiguous block that could be in L1 cache without conflicts. To clean up stragglers (where I couldn't group by .o
) I used section attributes on individual functions. Performance counters verified that it actually worked (reduced L1 instruction cache misses to almost nothing).
What other clever things have you accomplished with linker scripts?
On a certain platform, for reasons I won't go into, I needed to have a section of executable which I could discard after load. Now unfortunately unmapping the memory for the executable was not possible so I was compelled to resort to linker trickery.
What I ended up doing was introducing a section of the executable which aliased the bss. That way, presuming I could sneak some code in early enough, I could copy the data out, reinitialize the bss, and so long as my aliased section was smaller than the total bss of the executable, paid no cost for the privilege. There are a couple of problems in that I couldn't really change the crt at all and the earliest point I could inject code was still after tls initialization (which used some bss), but nothing impossible to work around.
I'm still sort of surprised it worked, I would have thought that the bss was initialized by the crt after all the program sections were loaded. I haven't tried it on any platform where I have access to the loader or crt source.
精彩评论