Random segfaults at runtime on macOS Mojave caused by GHC linker misaligning sections
GHC-built binaries sometimes crash at runtime on Mojave. The crash is caused by the incorrect practice of loading static archives directly into memory. The align
field of the various sections in the __TEXT
segment is not respected; instead the entire file is mapped directly in using mmap()
, which results in sections often loading at addresses which are only 8-byte aligned. The files on disk are not properly aligned, since ld
was never given the opportunity to correctly arrange them. In turn, this causes any SSE instructions which load from memory (as found in, especially, crypto algorithms implemented in C) to raise #GP
faults - SSE memory loads require 16-byte alignment. It's essentially blind luck that this has been working for any length of time in the past.
This technique of loading static archives directly into memory at runtime is problematic at best; this crash is far from the only issue. With no involvement by ld
and dyld
, no symbols or debug information were available. There was absolutely no evidence anywhere in the crash logs to even make a start at tracking down the issue; only the presence of a consistent repro case and a lot of examining memory regions by hand made finding the root cause possible. MH_OBJECT
files are not intended to be treated as final executable code. And to add insult to injury, the technique is fundamentally incompatible with code signing. Re-implementing parts of dyld
by hand like this is not a replacement for macOS not supporting static linking.
In the absence of switching to a supported behavior (e.g. dynamic loading), an appropriate fix consists of:
- Disable the
mmap()
codepath in the Mach-O loader. It prevents correct alignment handling and does not provide a significant performance benefit. - Teach the loader to handle alignment on a section-by-section (not segment!) basis and to correctly apply the appropriate relocations. The existing "align the entire file" codepath is not sufficient.
- Remove the conceit that there will be only one segment to load.
Trac metadata
Trac field | Value |
---|---|
Version | 8.6.3 |
Type | Bug |
TypeOfFailure | OtherFailure |
Priority | normal |
Resolution | Unresolved |
Component | Compiler (Linking) |
Test case | |
Differential revisions | |
BlockedBy | |
Related | |
Blocking | |
CC | |
Operating system | |
Architecture |