Skip to content

Commit fb9bca9

Browse files
Manually preserve rbx across cpuid instruction (#851)
* Manually preserve rbx across cpuid instruction This fixes an issue observed when using __cpuid and __cpuid_count with Address Sanitizer enabled: the generated code uses the rbx register to access ASAN tracking information without reloading it after cpuid, resulting in a segfault since the rbx register is overwritten by cpuid (https://crbug.com/1072045). This seems like a compiler backend bug, and indeed there is a long-standing LLVM bug report about a very similar issue: https://bugs.llvm.org/show_bug.cgi?id=17907 To work around this issue, we can manually preserve the rbx register contents in the inline assembly. This is the approach taken by LLVM's own host cpuid detection code (lib/Host/Support.cpp). The original rbx value is stashed in rsi, which is then swapped with rbx to restore the original value as well as keep the output ebx value from the CPUID instruction to be used as an output of the inline assembly. The rbx clobber is also removed; this seems ineffective, and it conflicts with the ebx output of the inline assembly (ebx is a subregister of rbx): "Note that clobbering named registers that are also present in output constraints is not legal." (https://llvm.org/docs/LangRef.html#clobber-constraints) * Add link to LLVM bug in cpuid workaround comment
1 parent d10eefc commit fb9bca9

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

crates/core_arch/src/x86/cpuid.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,16 @@ pub unsafe fn __cpuid_count(leaf: u32, sub_leaf: u32) -> CpuidResult {
6565
#[cfg(target_arch = "x86_64")]
6666
{
6767
// x86-64 uses %rbx as the base register, so preserve it.
68-
llvm_asm!("cpuid"
69-
: "={eax}"(eax), "={ebx}"(ebx), "={ecx}"(ecx), "={edx}"(edx)
68+
// This works around a bug in LLVM with ASAN enabled:
69+
// https://bugs.llvm.org/show_bug.cgi?id=17907
70+
llvm_asm!(r#"
71+
mov %rbx, %rsi
72+
cpuid
73+
xchg %rbx, %rsi
74+
"#
75+
: "={eax}"(eax), "={esi}"(ebx), "={ecx}"(ecx), "={edx}"(edx)
7076
: "{eax}"(leaf), "{ecx}"(sub_leaf)
71-
: "rbx" :);
77+
: :);
7278
}
7379
CpuidResult { eax, ebx, ecx, edx }
7480
}

0 commit comments

Comments
 (0)