@@ -157,12 +157,18 @@ set_bits(uint32_t *loc, uint8_t loc_start, uint64_t value, uint8_t value_start,
157
157
uint8_t width )
158
158
{
159
159
assert (loc_start + width <= 32 );
160
+ uint32_t temp_val ;
161
+ // Use memcpy to safely read the value, avoiding potential alignment
162
+ // issues and strict aliasing violations.
163
+ memcpy (& temp_val , loc , sizeof (temp_val ));
160
164
// Clear the bits we're about to patch:
161
- * loc &= ~(((1ULL << width ) - 1 ) << loc_start );
162
- assert (get_bits (* loc , loc_start , width ) == 0 );
165
+ temp_val &= ~(((1ULL << width ) - 1 ) << loc_start );
166
+ assert (get_bits (temp_val , loc_start , width ) == 0 );
163
167
// Patch the bits:
164
- * loc |= get_bits (value , value_start , width ) << loc_start ;
165
- assert (get_bits (* loc , loc_start , width ) == get_bits (value , value_start , width ));
168
+ temp_val |= get_bits (value , value_start , width ) << loc_start ;
169
+ assert (get_bits (temp_val , loc_start , width ) == get_bits (value , value_start , width ));
170
+ // Safely write the modified value back to memory.
171
+ memcpy (loc , & temp_val , sizeof (temp_val ));
166
172
}
167
173
168
174
// See https://developer.arm.com/documentation/ddi0602/2023-09/Base-Instructions
0 commit comments