The cast of an arena pointer to its user address zero extended the low half, shifted it up, or'ed the user base in, rotated it back down and replaced the result with zero from a cleared r11 through a cmove for a NULL pointer: seven instructions with a dependency chain of six. Or the user base into r11 instead and pick it with a cmovne when the low half is not zero, five instructions with a chain of three. LLVM emits the cast for every arena pointer handed back to user space. Before, for r1 = addr_space_cast(r7, 1, 0) with a user base of 0x7f1200000000: 44 89 ef movl %r13d,%edi 48 c1 e7 20 shlq $0x20,%rdi 48 81 cf 12 7f 00 00 orq $0x7f12,%rdi 48 c1 c7 20 rolq $0x20,%rdi 4d 31 db xorq %r11,%r11 85 ff testl %edi,%edi 49 0f 44 fb cmoveq %r11,%rdi After: 44 89 ef movl %r13d,%edi 49 bb 00 00 00 00 12 7f 00 00 movabsq $0x7f1200000000,%r11 49 09 fb orq %rdi,%r11 85 ff testl %edi,%edi 49 0f 45 fb cmovneq %r11,%rdi Signed-off-by: Daniel Borkmann --- arch/x86/net/bpf_jit_comp.c | 33 ++++++++------------------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index c2fe72fa0bed..3975a94ac812 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -2544,35 +2544,18 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * case BPF_ALU64 | BPF_MOV | BPF_X: if (insn_is_cast_user(insn)) { - if (dst_reg != src_reg) - /* 32-bit mov */ - emit_mov_reg(&prog, false, dst_reg, src_reg); - /* shl dst_reg, 32 */ - maybe_emit_1mod(&prog, dst_reg, true); - EMIT3(0xC1, add_1reg(0xE0, dst_reg), 32); - - /* or dst_reg, user_vm_start */ - maybe_emit_1mod(&prog, dst_reg, true); - if (is_axreg(dst_reg)) - EMIT1_off32(0x0D, user_vm_start >> 32); - else - EMIT2_off32(0x81, add_1reg(0xC8, dst_reg), user_vm_start >> 32); - - /* rol dst_reg, 32 */ - maybe_emit_1mod(&prog, dst_reg, true); - EMIT3(0xC1, add_1reg(0xC0, dst_reg), 32); - - /* xor r11, r11 */ - EMIT3(0x4D, 0x31, 0xDB); - - /* test dst_reg32, dst_reg32; check if lower 32-bit are zero */ + /* mov dst_reg32, src_reg32 to zero extend the low half */ + emit_mov_reg(&prog, false, dst_reg, src_reg); + /* mov r11, the high half of user_vm_start; or r11, dst_reg */ + emit_mov_imm64(&prog, AUX_REG, user_vm_start >> 32, 0); + emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true); + /* test dst_reg32, dst_reg32; a NULL pointer stays NULL */ maybe_emit_mod(&prog, dst_reg, dst_reg, false); EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg)); - - /* cmove r11, dst_reg; if so, set dst_reg to zero */ + /* cmovne dst_reg, r11 */ /* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */ maybe_emit_mod(&prog, AUX_REG, dst_reg, true); - EMIT3(0x0F, 0x44, add_2reg(0xC0, AUX_REG, dst_reg)); + EMIT3(0x0F, 0x45, add_2reg(0xC0, AUX_REG, dst_reg)); break; } else if (insn_is_mov_percpu_addr(insn)) { /* mov , (if necessary) */ -- 2.43.0