Skip to contentSkip to conversation

riscv: Implement _THIS_IP_ using inline asm

PATCH In review Marco Elver 3 participants 3 messages May 21 RISC-V

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 riscv: Implement _THIS_IP_ using inline asm

Both GCC [1] and Clang [2] consider the generic version of _THIS_IP_ to be broken:

        #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })

In particular, the address of a label is only expected to be used with a computed goto.

While the generic version more or less works today, it is known to be brittle and may break with current and future optimizations. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Fix it by overriding _THIS_IP_ in <asm/linkage.h> (which is included by <linux/instruction_pointer.h>) using an architecture-specific inline asm version. Additionally, avoiding taking the address of a label prevents compilers from emitting spurious indirect branch targets (e.g. ENDBR or BTI) under control-flow integrity schemes.

---
 arch/riscv/include/asm/linkage.h | 2 ++
 1 file changed, 2 insertions(+)
arch/riscv/include/asm/linkage.h +2 -0
index 9e88ba23cd2b..7e0210ef4eb4 100644
@@ -9,4 +9,6 @@
 #define __ALIGN		.balign 4
 #define __ALIGN_STR	".balign 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("auipc %0, 0" : "=r" (__ip)); __ip; })
+
 #endif /* _ASM_RISCV_LINKAGE_H */
Signature · 1 line
2.54.0.746.g67dd491aae-goog
maintainer
#2 lore raw
In reply to Marco Elver
Quoted 21 lines · Marco Elver

Both GCC [1] and Clang [2] consider the generic version of _THIS_IP_ to be broken:

        #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })

In particular, the address of a label is only expected to be used with a computed goto.

While the generic version more or less works today, it is known to be brittle and may break with current and future optimizations. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Fix it by overriding _THIS_IP_ in <asm/linkage.h> (which is included by <linux/instruction_pointer.h>) using an architecture-specific inline asm version. Additionally, avoiding taking the address of a label prevents compilers from emitting spurious indirect branch targets (e.g. ENDBR or BTI) under control-flow integrity schemes.

Quoted 3 lines

Thanks, queued for v7.2.

- Paul