blocksds / sdk

Main BlocksDS SDK repository
https://blocksds.github.io/docs/
164 stars 11 forks source link

Thread-safe local static initialisation causes link failure in some cases #213

Closed Qdoit closed 3 weeks ago

Qdoit commented 3 weeks ago

GCC by default attempts to make the initialization of local statics thread-safe.

To do this it calls __cxa_lock_acquire (in cases where it can't prove thread-safeness at compile time, that is). Similarly to the __cxa_* functions responsible for exceptions, this isn't supported on this platform.

As threading is quite limited on the DS, I believe turning this feature off entirely shouldn't pose any issues. So, my proposed fix is adding -fno-threadsafe-statics to the C++ options of the templates.

This issue was encountered on the ARM9 processor and I am not sure if it occurs on the ARM7 as well, but it seems likely.

AntonioND commented 3 weeks ago

Thanks for the report (and the potential fix)!

This is only a problem in the ARM9, multithreading is currently not used in the ARM7.

I think adding that option to the specs file of the ARM9 would be a reasonable fix, but I'll let @asiekierka check this before doing anything.

asiekierka commented 3 weeks ago

While it is a reasonable workaround, it is not a valid solution.

-fno-threadsafe-statics disables C++ guards which prevent recursively using static variables inside a function when the function is called recursively, or by another thread. This case can happen even under our cooperative threading model. As such, we probably have to implement __cxa_guard_acquire and __cxa_guard_release.

asiekierka commented 3 weeks ago

@AntonioND You're more C++ than I am; could you please come up with simple example and add it to tests/ as a regression test? It need not compile yet, but I'll be able to test if my implementation works at all with it.

Qdoit commented 3 weeks ago

Sorry, I came back to this and tried to make a minimum issue causing example and I think it turns out the issue was on my end.

My build setup was a little convoluted and at one point the linking didn't include libstdc++, causing the build issue. When actually linking against the C++ stdlib at all points, no issues arises and it seems __cxa_guards are implemented.

Sorry for wasting your time again!

asiekierka commented 3 weeks ago

Very well. (But it was nice to learn about how the __cxa_guards work internally.)

AntonioND commented 3 weeks ago

Ah, good to know, and no worries for the report!