Re: [PATCH v3 04/10] x86/traps: Allow custom fixups in handle_bug()

Kees Cook
2025-02-19T17:55:14Z

On Wed, Feb 19, 2025 at 05:21:11PM +0100, Peter Zijlstra wrote:
> The normal fixup in handle_bug() is simply continuing at the next
> instruction. However upcomming patches make this the wrong thing, so
> allow handlers (specifically handle_cfi_failure()) to over-ride
> regs->ip.
>
> The callchain is such that the fixup needs to be done before it is
> determined if the exception is fatal, as such, revert any changes in
> that case.
>
> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
> ---
> arch/x86/kernel/traps.c | 12 +++++++++---
> 1 file changed, 9 insertions(+), 3 deletions(-)
>
> --- a/arch/x86/kernel/traps.c
> +++ b/arch/x86/kernel/traps.c
> @@ -287,11 +287,12 @@ static inline void handle_invalid_op(str
>
> static noinstr bool handle_bug(struct pt_regs *regs)
> {
> + unsigned long addr = regs->ip;
> bool handled = false;
> int ud_type, ud_len;
> s32 ud_imm;
>
> - ud_type = decode_bug(regs->ip, &ud_imm, &ud_len);
> + ud_type = decode_bug(addr, &ud_imm, &ud_len);
> if (ud_type == BUG_NONE)
> return handled;
>
> @@ -315,7 +316,8 @@ static noinstr bool handle_bug(struct pt
> switch (ud_type) {
> case BUG_EA:
> if (handle_cfi_failure(regs) == BUG_TRAP_TYPE_WARN) {
> - regs->ip += ud_len;
> + if (regs->ip == addr)
> + regs->ip += ud_len;
> handled = true;
> }
> break;
> @@ -323,7 +325,8 @@ static noinstr bool handle_bug(struct pt
> case BUG_UD2:
> if (report_bug(regs->ip, regs) == BUG_TRAP_TYPE_WARN ||
> handle_cfi_failure(regs) == BUG_TRAP_TYPE_WARN) {
> - regs->ip += ud_len;
> + if (regs->ip == addr)
> + regs->ip += ud_len;
> handled = true;
> }
> break;
> @@ -340,6 +343,9 @@ static noinstr bool handle_bug(struct pt
> break;
> }
>
> + if (!handled && regs->ip != addr)
> + regs->ip = addr;

Can you add a comment above this just to help with people scanning
through this code in the future, maybe:

/* Restore failure location if we're not continuing execution. */

> +
> if (regs->flags & X86_EFLAGS_IF)
> raw_local_irq_disable();
> instrumentation_end();

But yeah, seems fine:

Reviewed-by: Kees Cook <kees@kernel.org>

--
Kees Cook