From: George Guo <[email protected]>

Add architecture-specific -fPIC compiler flag for LoongArch64 to prevent
kernel panics when applying livepatches containing references to symbols
defined in the same compilation unit.

Root cause:
In the KLP workflow, when a function is livepatched, it's extracted
from the original object file and compiled into a separate kernel
module. When the patched function references symbols defined in the
same compilation unit (like 'uts_sem' in kernel/sys.c), these
references break if not compiled as position-independent code.

On LoongArch64, without -fPIC, references to same-compilation-unit symbols
use absolute addressing that assumes fixed memory locations. When the
function is relocated into the livepatch module, these absolute addresses
become invalid, causing kernel panics.

Example failure case:
- SYSCALL_DEFINE1(newuname) references the same-compilation-unit
  symbol 'uts_sem'
- When kpatch extracts this function into a module, the reference to
  'uts_sem' must be properly relocated
- Without -fPIC, the absolute address reference causes invalid memory
  access and kernel panic

Solution:
Force -fPIC compilation for all LoongArch64 KLP builds. This ensures
that references to same-compilation-unit symbols use position-independent
addressing, allowing proper relocation by the kernel module loader and
preventing kernel panics in livepatch scenarios.

Co-developed-by: Kexin Liu <[email protected]>
Signed-off-by: Kexin Liu <[email protected]>
Signed-off-by: George Guo <[email protected]>
---
 scripts/livepatch/klp-build | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/scripts/livepatch/klp-build b/scripts/livepatch/klp-build
index 529437d75346..83a43e0df3b9 100755
--- a/scripts/livepatch/klp-build
+++ b/scripts/livepatch/klp-build
@@ -543,8 +543,10 @@ fix_patches() {
 clean_kernel() {
        local cmd=()
        local ARCH_KBUILD_CFLAGS_KERNEL=""
+       local ARCH_KCFLAGS=""
 
        if [[ -v CONFIG_LOONGARCH && "$CONFIG_LOONGARCH" == "y" ]]; then
+               ARCH_KCFLAGS="-fPIC"
                if [[ -n "$CONFIG_CC_IS_CLANG" ]]; then
                        
ARCH_KBUILD_CFLAGS_KERNEL="-fno-direct-access-external-data"
                else
@@ -592,7 +594,7 @@ build_kernel() {
                cmd+=("-s")
        fi
        cmd+=("-j$JOBS")
-       cmd+=("KCFLAGS=-ffunction-sections -fdata-sections")
+       cmd+=("KCFLAGS=-ffunction-sections -fdata-sections $ARCH_KCFLAGS")
        cmd+=("KBUILD_CFLAGS_KERNEL=$ARCH_KBUILD_CFLAGS_KERNEL")
        cmd+=("vmlinux")
        cmd+=("modules")
-- 
2.25.1


Reply via email to