Skip to content

Do not access memory on misaligned addresses

Hanicef requested to merge Hanicef/SRB2:fix-misaligned-access into next

This is an interesting discovery I ended up doing while trying to diagnose #1153. While running the game with UBSan in an attempt to rule out undefined behavior as a cause, I noticed that there was a lot of misaligned address issues that fired off, similar to this:

lzf.c:359:12: runtime error: load of misaligned address 0x5580e19f7f85 for type 'const u16', which requires 2 byte alignment
0x5580e19f7f85: note: pointer points here
 55 4c 4c 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00
             ^ 

(Note: this is not addressed by this patch, but only used as an example to illustrate)

Originally, I thought this was unrelated since I always tend to run debug builds, where UB tends to behave consistently, but I decided to fix it anyway after looking into it since it seemed like an easy fix. While I haven't really properly tested if it actually fixes the issue or not, there was one bug that I knew of besides this that seemed to happen on FreeBSD when running a dedicated server on certain (UDMF?) maps.

This GIF illustrates it best:

srb20004

Essentially, every time a player passes through an FOF, positioning would completely break server-side, and the player would be teleported randomly between planes. In this case, I was teleported downstairs again, bringing me back to where I started the GIF.

To my surprise, though, after applying this patch, I got a different behavior:

srb20005

Somehow, this was fixed by this patch despite the fact that it was running on a debug build. And, yes, UB essentially means that the compiler can do whatever it wants, but it normally doesn't change behavior on debug builds like this, which is why this baffles me so much. Either way, this is still a finding worth fixing.

Merge request reports