Skip to content

Commit b54b600

Browse files
Pu Lehuiborkmann
authored andcommitted
riscv, bpf: Emit fixed-length instructions for BPF_PSEUDO_FUNC
For BPF_PSEUDO_FUNC instruction, verifier will refill imm with correct addresses of bpf_calls and then run last pass of JIT. Since the emit_imm of RV64 is variable-length, which will emit appropriate length instructions accorroding to the imm, it may broke ctx->offset, and lead to unpredictable problem, such as inaccurate jump. So let's fix it with fixed-length instructions. Fixes: 69c087b ("bpf: Add bpf_for_each_map_elem() helper") Suggested-by: Björn Töpel <bjorn@rivosinc.com> Signed-off-by: Pu Lehui <pulehui@huawei.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Reviewed-by: Björn Töpel <bjorn@kernel.org> Acked-by: Björn Töpel <bjorn@kernel.org> Link: https://lore.kernel.org/bpf/20221206091410.1584784-1-pulehui@huaweicloud.com
1 parent 08388ef commit b54b600

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

arch/riscv/net/bpf_jit_comp64.c

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,25 @@ static bool in_auipc_jalr_range(s64 val)
136136
val < ((1L << 31) - (1L << 11));
137137
}
138138

139+
/* Emit fixed-length instructions for address */
140+
static int emit_addr(u8 rd, u64 addr, bool extra_pass, struct rv_jit_context *ctx)
141+
{
142+
u64 ip = (u64)(ctx->insns + ctx->ninsns);
143+
s64 off = addr - ip;
144+
s64 upper = (off + (1 << 11)) >> 12;
145+
s64 lower = off & 0xfff;
146+
147+
if (extra_pass && !in_auipc_jalr_range(off)) {
148+
pr_err("bpf-jit: target offset 0x%llx is out of range\n", off);
149+
return -ERANGE;
150+
}
151+
152+
emit(rv_auipc(rd, upper), ctx);
153+
emit(rv_addi(rd, rd, lower), ctx);
154+
return 0;
155+
}
156+
157+
/* Emit variable-length instructions for 32-bit and 64-bit imm */
139158
static void emit_imm(u8 rd, s64 val, struct rv_jit_context *ctx)
140159
{
141160
/* Note that the immediate from the add is sign-extended,
@@ -1050,7 +1069,15 @@ int bpf_jit_emit_insn(const struct bpf_insn *insn, struct rv_jit_context *ctx,
10501069
u64 imm64;
10511070

10521071
imm64 = (u64)insn1.imm << 32 | (u32)imm;
1053-
emit_imm(rd, imm64, ctx);
1072+
if (bpf_pseudo_func(insn)) {
1073+
/* fixed-length insns for extra jit pass */
1074+
ret = emit_addr(rd, imm64, extra_pass, ctx);
1075+
if (ret)
1076+
return ret;
1077+
} else {
1078+
emit_imm(rd, imm64, ctx);
1079+
}
1080+
10541081
return 1;
10551082
}
10561083

0 commit comments

Comments
 (0)