Swift 5 Read binary file ( problem with unsafe mutable pointers)

[I see, reading your [other thread]ref, that you’re already past this roadblock, but I want to follow up here just so that other folks don’t get tripped up by this. My recommendation is that you not respond here, but instead continue to follow-up on your other thread, because that captures a bunch more details about your specific requirements.]

You wrote:

which works for unaligned Floats with swiftc -O but not in debug mode.

Right. The problem here is that unsafe pointers must be aligned (per the doc I referenced back on 28 Nov). This isn’t a requirement of the current crop of CPUs but rather a requirement of Swift. If you don’t follow this rule, you run the risk of trapping, or other misbehaviour, on future CPUs that don’t allow misaligned access. Such problems may only show up under obscure circumstances [1], so the Swift compiler inserts a check in the debug build to avoid you accidentally shipping code that might trigger it in the field.

The approach you posted in the other thread — using a byte-by-byte copy to extract the value from the buffer into a local Float — is the direction I’d recommend.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

[1] I once helped a developer debug a problem that hung a single core on specific multicore PowerPC systems. It turned out that they were reading a misaligned floating point value that crossed a 16 MiB boundary (known as a segment in the PowerPC architecture, although that has nothing to do with segments are you might understand them from x86). The CPU would trap on such accesses, and for compatibility reasons the microkernel would handle that trap and emulate the correct result. This emulation had a bug that crashed the microkernel on that core, with the end result being that the microkernel would get stuck in a crash loop that hung the core. Weirdly, other cores on the CPU would continue to run just fine, so the Mac would keep working, just with one core pinned in a crash loop.

1 Like