<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/62936>62936</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
-fsanitize=kcfi can cause alignment faults due to Arm/Thumb interworking
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
statham-arm
</td>
</tr>
</table>
<pre>
The option `-fsanitize=kcfi` causes clang to emit code that (in 32-bit Arm) loads a 32-bit word from offset -4 relative to a function pointer it's about to call through. But in 32-bit Arm, function pointers may have the low bit set to indicate that they should be entered in Thumb state (and calling through the pointer via the `BX` or `BLX` instruction will automatically do that). So loading from (pointer-4) will cause an alignment fault if the pointer is Thumb.
For example:
```
typedef int functype(int);
int call_with_42(functype *funcptr) { return funcptr(42); }
```
Compiled with this command (as of commit 12648492998bd22d268eb1d4d476c6c3acc6c43d):
```
clang --target=arm-none-eabi -O1 -fsanitize=kcfi -S -o - test.c
```
the generated code looks like this:
```
mov r1, r0
ldr r0, [r0, #-4] # load from just before the function
ldr r2, .LCPI0_0 # load a constant containing expected value
cmp r0, r2 # check if they're equal
bne .LBB0_2 # and go and take a trap if they're not
mov r0, #42
bx r1 # otherwise, tailcall the function
```
and if r0 on entry to the function had had an address with bit 0 set, then the first `LDR` instruction would cause an alignment fault (or, if unaligned access is enabled in the CPU, load incorrect data).
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJx0VUGP2zgP_TXKhXDgyI7jHHJoJhjgAwb4im0X2NtAluhYjSxlJXrS7K9fUE66TadjzMSyJD4-PpGUSskePeJOrPdifVioiYYQd4kUDWosVBwXXTDX3dcBIZzJBg-iKYs-KW_J_oOiOpx0b0VTglZTwgTaKX8ECoCjJdDBINCgCIRsrYdKFp0l-BRHIbfggjIJ1H32EqKBPoYRQt8nJChqiOgU2TdkRAX95HUmcQ7WE0awJOQmgerCRLxFK-e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