Commit 0c18d91
authored
Fix unaligned memory access in librt internal helper function _write_short (#20474)
Fixes: #20473
This PR replaces the static upcasting in the helper macros `_READ` and
`_WRITE` with a `memcpy` call.
Some of the functions in `librt_internal.c` use these macros to write 16
or 32 bit integer values, while the `data->ptr` is byte-aligned and may
point to a memory address that is not divisible by 2 or 4.
This leads to a crash (with SIGBUS) on CPU architectures that have
strict memory alignment, or possibly a performance penalty on others.
By replacing the direct assignment with `memcpy`, the compiler will
figure out the most optimal method to access the unaligned memory.
I analyzed the resulting machine code generated by gcc 15 on amd64 and
sparc64: The `memcpy` call was in fact optimized away, with instructions
that avoided the crash on sparc64. On amd64, it made no difference
performance-wise (compared to the original code).1 parent 9dc9fc3 commit 0c18d91
1 file changed
Lines changed: 4 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
| 6 | + | |
6 | 7 | | |
7 | 8 | | |
8 | 9 | | |
| |||
39 | 40 | | |
40 | 41 | | |
41 | 42 | | |
42 | | - | |
| 43 | + | |
43 | 44 | | |
44 | 45 | | |
45 | 46 | | |
46 | 47 | | |
47 | 48 | | |
48 | | - | |
| 49 | + | |
| 50 | + | |
49 | 51 | | |
50 | 52 | | |
51 | 53 | | |
| |||
0 commit comments