[RFC PATCH 24/28] tools/objtool: Treat indirect ftrace calls as direct calls

Ard Biesheuvel
2024-09-25T15:02:52Z

From: Ard Biesheuvel <ardb@kernel.org>

In some cases, the compiler may rely on indirect calls using GOT slots
as memory operands to emit function calls. This leaves it up to the
linker to relax the call to a direct call if possible, i.e., if the
destination address is known at link time and in range, which may not be
the case when building shared libraries for user space.

On x86, this may happen when building in PIC mode with ftrace enabled,
and given that vmlinux is a fully linked binary, this relaxation is
always possible, and therefore mandatory per the x86_64 psABI.

This means that the indirect calls to __fentry__ that are observeable in
vmlinux.o will have been converted to direct calls in vmlinux, and can
be treated as such by objtool.

Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
---
tools/objtool/check.c | 32 ++++++++++++++++++--
1 file changed, 30 insertions(+), 2 deletions(-)

diff --git a/tools/objtool/check.c b/tools/objtool/check.c
index 04725bd83232..94a56099e22d 100644
--- a/tools/objtool/check.c
+++ b/tools/objtool/check.c
@@ -1696,11 +1696,39 @@ static int add_call_destinations(struct objtool_file *file)
struct reloc *reloc;

for_each_insn(file, insn) {
- if (insn->type != INSN_CALL)
+ if (insn->type != INSN_CALL &&
+ insn->type != INSN_CALL_DYNAMIC)
continue;

reloc = insn_reloc(file, insn);
- if (!reloc) {
+ if (insn->type == INSN_CALL_DYNAMIC) {
+ if (!reloc)
+ continue;
+
+ /*
+ * GCC 13 and older on x86 will always emit the call to
+ * __fentry__ using a relaxable GOT-based symbol
+ * reference when operating in PIC mode, i.e.,
+ *
+ * call *0x0(%rip)
+ * R_X86_64_GOTPCRELX __fentry__-0x4
+ *
+ * where it is left up to the linker to relax this into
+ *
+ * call __fentry__
+ * nop
+ *
+ * if __fentry__ turns out to be DSO local, which is
+ * always the case for vmlinux. Given that this
+ * relaxation is mandatory per the x86_64 psABI, these
+ * calls can simply be treated as direct calls.
+ */
+ if (arch_ftrace_match(reloc->sym->name)) {
+ insn->type = INSN_CALL;
+ add_call_dest(file, insn, reloc->sym, false);
+ }
+
+ } else if (!reloc) {
dest_off = arch_jump_destination(insn);
dest = find_call_destination(insn->sec, dest_off);

--
2.46.0.792.g87dc391469-goog