几年前,我用下面的这个宏编写并更新了我们的 MASM 代码库来对抗 Spectre V2。
NOSPEC_JMP MACRO target:REQ
PUSH target
JMP x86_indirect_thunk
ENDM
NOSPEC_CALL MACRO target:REQ
LOCAL nospec_call_start
LOCAL nospec_call_end
JMP nospec_call_end
ALIGN 16
nospec_call_start:
PUSH target
JMP x86_indirect_thunk
ALIGN 16
nospec_call_end:
CALL nospec_call_start
ENDM
.CODE
;; This is a special sequence that prevents the CPU speculating for indirect calls.
ALIGN 16
x86_indirect_thunk:
CALL retpoline_call_target
;; No benefit from aligning the capture_speculation branch target, as it is only potentially speculatively executed.
capture_speculation:
PAUSE
JMP capture_speculation
ALIGN 16
retpoline_call_target:
IFDEF WIN64
LEA RSP,[RSP+8]
ELSE
LEA ESP,[ESP+4]
ENDIF
RET
例如,这里有一些启用了推测的汇编代码 (MST_QSPECTRE=1)
main PROC NEAR C
PUSH ESI
PUSH EDI
PUSH EBX
PUSH EBP
MOV EAX,OFFSET MyFun
;; Generated code to Call an indirect pointer without speculation.
IFDEF MST_QSPECTRE
NOSPEC_CALL EAX
ELSE
CALL EAX
ENDIF
POP EBP
POP EBX
POP EDI
POP ESI
RET
main ENDP
反汇编显示了推测指令是如何插入的
问题
在 2021 年,我是否可以安全地删除该 MASM 宏并依靠 CPU 微码更新等……来解决任何 Spectre 问题?对于 C 代码,看起来 M$ 和 Linux C 编译器已经解决了它:
- Microsoft在其 MSVC 编译器中添加了/Qspectre 。
- GCC 具有通过 -mfunction-return 等减轻 Spectre v2 的编译器选项,...
谢谢。