FPC generates thread-unsafe code for DLLs
Original Reporter info from Mantis: skidder
-
Reporter name: Nikolay Samofatov
Original Reporter info from Mantis: skidder
- Reporter name: Nikolay Samofatov
Description:
Pretty much any FPC built DLL which is used in threaded environment, but does not create threads on its own is thread unsafe. Try doing some AnsiString manipulations from multiple external threads in parallel on a 2-core system, for example. The crash is 100% reproducible in Win32 and Win64 environment in a matter of milliseconds of run-time. I didn't analyze/test other platforms.
The problem is that DLL does not respond to DLL_THREAD_ATTACH notifications, and as such TLS subsystem, memory allocator, strings manager, exceptions and stdio subsystems are left unaware of threads presence (TlsKey value is left 0). Setting IsMultiThread from library initialization code like prescribed for some versions of Delphi, does not help with the stability of FPC produced binaries.
Additional information:
Attached patch against current 2.3.1 fixes the problem described above, adding necessary initialization code in DLL_Entry routine for Win32 and Win64 targets. Note: stack overflow handling is probably implemented incorrectly in this patch, so it may need review/fixing by an FPC expert. Thanks!