arm64: Reorganize the unwinder and implement stack trace reliability checks
Subsystems (6)
A message that is not in the archive (sent off-list or not yet received): 95691cae4f4504f33d0fc9075541b1e7deefe96f
v13 cover arm64: Reorganize the unwinder and implement stack trace reliability checks
From: "Madhavan T. Venkataraman" <[email protected]>
I have rebased this patch series on top of Linus' tree as of Jan 15, 2022. The base commit is provided at the end of this email.
Remove NULL task check
======================
Currently, there is a check for a NULL task in unwind_frame(). It is not needed since all current consumers pass a non-NULL task.
Rename unwinder functions
=========================
Rename unwinder functions to unwind*() similar to other architectures for naming consistency.
start_backtrace() ==> unwind_init() unwind_frame() ==> unwind_next() walk_stackframe() ==> unwind()
Rename struct stackframe
========================
Rename "struct stackframe" to "struct unwind_state" for better naming and consistency.
Split unwind_init()
===================
Unwind initialization has 3 cases. Accordingly, define 3 separate init functions as follows:
- unwind_init_from_regs()
- unwind_init_from_current()
- unwind_init_from_task()
This makes it easier to understand and add specialized code to each case in the future.
Copy task argument
==================
Copy the task argument passed to arch_stack_walk() to unwind_state so that it can be passed to unwind functions via unwind_state rather than as a separate argument. The task is a fundamental part of the unwind state.
Use stack_trace_consume_fn
==========================
stack_trace_consume_fn is a typedef already defined. unwind() does not use this for its consume_entry() argument. Fix this. Also, rename the arguments to unwind() for better naming consistency.
Redefine the unwinder loop
==========================
Redefine the unwinder loop and make it simple and somewhat similar to other architectures. Define the following:
while (unwind_continue(&state, consume_entry, cookie)) unwind_next(&state);
unwind_continue()
This new function implements checks to determine whether the unwind should continue or terminate.
Reliability checks
==================
There are some kernel features and conditions that make a stack trace unreliable. Callers may require the unwinder to detect these cases. E.g., livepatch.
Introduce a new function called unwind_check_reliability() that will detect these cases and set a boolean "reliable" in the stackframe. Call unwind_check_reliability() for every frame.
Introduce the first reliability check in unwind_check_reliability() - If a return PC is not a valid kernel text address, consider the stack trace unreliable. It could be some generated code.
Other reliability checks will be added in the future.
Make unwind() return a boolean to indicate reliability of the stack trace.
SYM_CODE check
==============
This is the second reliability check implemented.
SYM_CODE functions do not follow normal calling conventions. They cannot be unwound reliably using the frame pointer. Collect the address ranges of these functions in a special section called "sym_code_functions".
In unwind_check_reliability(), check the return PC against these ranges. If a match is found, then mark the stack trace unreliable.
Last stack frame
================
If a SYM_CODE function occurs in the very last frame in the stack trace, then the stack trace is not considered unreliable. This is because there is no more unwinding to do. Examples:
- EL0 exception stack traces end in the top level EL0 exception handlers.
- All kernel thread stack traces end in ret_from_fork().
arch_stack_walk_reliable()
==========================
Introduce arch_stack_walk_reliable() for ARM64. This works like arch_stack_walk() except that it returns an error if the stack trace is found to be unreliable.
Until all of the reliability checks are in place in unwind_check_reliability(), arch_stack_walk_reliable() may not be used by livepatch. But it may be used by debug and test code.
HAVE_RELIABLE_STACKTRACE
========================
Select this config for arm64. However, make it conditional on STACK_VALIDATION. When objtool is enhanced to implement stack validation for arm64, STACK_VALIDATION will be defined.
---
Changelog:
v13:
From Mark Brown:
- Reviewed-by for the following:
[PATCH v12 03/10] arm64: Rename stackframe to unwind_state [PATCH v11 05/10] arm64: Copy unwind arguments to unwind_state [PATCH v11 07/10] arm64: Introduce stack trace reliability checks
in the unwinder
[PATCH v11 5/5] arm64: Create a list of SYM_CODE functions, check
return PC against list
From Mark Rutland:
- Reviewed-by for the following:
[PATCH v12 01/10] arm64: Remove NULL task check from unwind_frame() [PATCH v12 02/10] arm64: Rename unwinder functions [PATCH v12 03/10] arm64: Rename stackframe to unwind_state
- For each of the 3 cases of unwind initialization, have a separate init function. Call the common init from each of these init functions rather than call it separately.
- Only copy the task argument to arch_stack_walk() into unwind state. Pass the rest of the arguments as arguments to unwind functions.
v12:
From Mark Brown:
- Reviewed-by for the following:
[PATCH v11 1/5] arm64: Call stack_backtrace() only from within
walk_stackframe()
[PATCH v11 2/5] arm64: Rename unwinder functions [PATCH v11 3/5] arm64: Make the unwind loop in unwind() similar to
other architectures
[PATCH v11 5/5] arm64: Create a list of SYM_CODE functions, check
return PC against list
- Add an extra patch at the end to select HAVE_RELIABLE_STACKTRACE just as a place holder for the review. I have added it and made it conditional on STACK_VALIDATION which has not yet been implemented.
- Mark had a concern about the code for the check for the final frame being repeated in two places. I have now added a new field called "final_fp" in struct stackframe which I compute once in stacktrace initialization. I have added an explicit comment that the stacktrace must terminate at the final_fp.
- Place the implementation of arch_stack_walk_reliable() in a separate patch after all the reliability checks have been implemented.
From Mark Rutland:
- Place the removal of the NULL task check in unwind_frame() in a separate patch.
- Add a task field to struct stackframe so the task pointer can be passed around via the frame instead of as a separate argument. I have taken this a step further by copying all of the arguments to arch_stack_walk() into struct stackframe so that only that struct needs to be passed to unwind functions.
- Rename start_backtrace() to unwind_init() instead of unwind_start().
- Acked-by for the following:
[PATCH v11 2/5] arm64: Rename unwinder functions
- Rename "struct stackframe" to "struct unwind_state".
- Define separate inline functions for initializing the starting FP and PC from regs, or caller, or blocked task. Don't merge unwind_init() into unwind().
v11:
From Mark Rutland:
- Peter Zijlstra has submitted patches that make ARCH_STACKWALK independent of STACKTRACE. Mark Rutland extracted some of the patches from my v10 series and added his own patches and comments, rebased it on top of Peter's changes and submitted the series.
So, I have rebased the rest of the patches from v10 on top of Mark Rutland's changes.
- Split the renaming of the unwinder functions and annotating them with notrace and NOKPROBE_SYMBOL(). Also, there is currently no need to annotate unwind_start() as its caller is already annotated properly. So, I am removing the annotation patch from the series. This can be done separately later if deemed necessary. Similarly, I have removed the annotations from unwind_check_reliability() and unwind_continue().
From Nobuta Keiya:
- unwind_start() should check for final frame and not mark the final frame unreliable.
v9, v10:
- v9 had a threading problem. So, I resent it as v10.
From me:
- Removed the word "RFC" from the subject line as I believe this is mature enough to be a regular patch.
From Mark Brown, Mark Rutland:
- Split the patches into smaller, self-contained ones.
- Always enable STACKTRACE so that arch_stack_walk() is always defined.
From Mark Rutland:
- Update callchain_trace() take the return value of perf_callchain_store() into acount.
- Restore get_wchan() behavior to the original code.
- Simplify an if statement in dump_backtrace().
From Mark Brown:
- Do not abort the stack trace on the first unreliable frame.
v8:
- Synced to v5.14-rc5.
From Mark Rutland:
- Make the unwinder loop similar to other architectures.
- Keep details to within the unwinder functions and return a simple boolean to the caller.
- Convert some of the current code that contains unwinder logic to simply use arch_stack_walk(). I have converted all of them.
- Do not copy sym_code_functions[]. Just place it in rodata for now.
- Have the main loop check for termination conditions rather than having unwind_frame() check for them. In other words, let unwind_frame() assume that the fp is valid.
- Replace the big comment for SYM_CODE functions with a shorter comment.
/*
* As SYM_CODE functions don't follow the usual calling
* conventions, we assume by default that any SYM_CODE function
* cannot be unwound reliably.
*
* Note that this includes:
*
* - Exception handlers and entry assembly
* - Trampoline assembly (e.g., ftrace, kprobes)
* - Hypervisor-related assembly
* - Hibernation-related assembly
* - CPU start-stop, suspend-resume assembly
* - Kernel relocation assembly
*/
v7:
The Mailer screwed up the threading on this. So, I have resent this same series as version 8 with proper threading to avoid confusion.
v6:
From Mark Rutland:
- The per-frame reliability concept and flag are acceptable. But more work is needed to make the per-frame checks more accurate and more complete. E.g., some code reorg is being worked on that will help.
I have now removed the frame->reliable flag and deleted the whole concept of per-frame status. This is orthogonal to this patch series. Instead, I have improved the unwinder to return proper return codes so a caller can take appropriate action without needing per-frame status.
- Remove the mention of PLTs and update the comment.
I have replaced the comment above the call to __kernel_text_address() with the comment suggested by Mark Rutland.
Other comments:
- Other comments on the per-frame stuff are not relevant because that approach is not there anymore.
v5:
From Keiya Nobuta:
- The term blacklist(ed) is not to be used anymore. I have changed it to unreliable. So, the function unwinder_blacklisted() has been changed to unwinder_is_unreliable().
From Mark Brown:
- Add a comment for the "reliable" flag in struct stackframe. The reliability attribute is not complete until all the checks are in place. Added a comment above struct stackframe.
- Include some of the comments in the cover letter in the actual code so that we can compare it with the reliable stack trace requirements document for completeness. I have added a comment:
- above unwinder_is_unreliable() that lists the requirements that are addressed by the function.
- above the __kernel_text_address() call about all the cases the call covers.
v4:
From Mark Brown:
- I was checking the return PC with __kernel_text_address() before the Function Graph trace handling. Mark Brown felt that all the reliability checks should be performed on the original return PC once that is obtained. So, I have moved all the reliability checks to after the Function Graph Trace handling code in the unwinder. Basically, the unwinder should perform PC translations first (for rhe return trampoline for Function Graph Tracing, Kretprobes, etc). Then, the reliability checks should be applied to the resulting PC.
- Mark said to improve the naming of the new functions so they don't collide with existing ones. I have used a prefix "unwinder_" for all the new functions.
From Josh Poimboeuf:
- In the error scenarios in the unwinder, the reliable flag in the stack frame should be set. Implemented this.
- Some of the other comments are not relevant to the new code as I have taken a different approach in the new code. That is why I have not made those changes. E.g., Ard wanted me to add the "const" keyword to the global section array. That array does not exist in v4. Similarly, Mark Brown said to use ARRAY_SIZE() for the same array in a for loop.
Other changes:
- Add a new definition for SYM_CODE_END() that adds the address range of the function to a special section called "sym_code_functions".
- Include the new section under initdata in vmlinux.lds.S.
- Define an early_initcall() to copy the contents of the "sym_code_functions" section to an array by the same name.
- Define a function unwinder_blacklisted() that compares a return PC against sym_code_sections[]. If there is a match, mark the stack trace unreliable. Call this from unwind_frame().
v3:
- Implemented a sym_code_ranges[] array to contains sections bounds for text sections that contain SYM_CODE_*() functions. The unwinder checks each return PC against the sections. If it falls in any of the sections, the stack trace is marked unreliable.
- Moved SYM_CODE functions from .text and .init.text into a new text section called ".code.text". Added this section to vmlinux.lds.S and sym_code_ranges[].
- Fixed the logic in the unwinder that handles Function Graph Tracer return trampoline.
- Removed all the previous code that handles:
- ftrace entry code for traced function
- special_functions[] array that lists individual functions
- kretprobe_trampoline() special case
v2
- Removed the terminating entry { 0, 0 } in special_functions[] and replaced it with the idiom { /* sentinel */ }.
- Change the ftrace trampoline entry ftrace_graph_call in special_functions[] to ftrace_call + 4 and added explanatory comments.
- Unnested #ifdefs in special_functions[] for FTRACE.
v1
- Define a bool field in struct stackframe. This will indicate if a stack trace is reliable.
- Implement a special_functions[] array that will be populated with special functions in which the stack trace is considered unreliable.
- Using kallsyms_lookup(), get the address ranges for the special functions and record them.
- Implement an is_reliable_function(pc). This function will check if a given return PC falls in any of the special functions. If it does, the stack trace is unreliable.
- Implement check_reliability() function that will check if a stack frame is reliable. Call is_reliable_function() from check_reliability().
- Before a return PC is checked against special_funtions[], it must be validates as a proper kernel text address. Call __kernel_text_address() from check_reliability().
- Finally, call check_reliability() from unwind_frame() for each stack frame.
- Add EL1 exception handlers to special_functions[].
el1_sync();
el1_irq();
el1_error();
el1_sync_invalid();
el1_irq_invalid();
el1_fiq_invalid();
el1_error_invalid();
- The above functions are currently defined as LOCAL symbols. Make them global so that they can be referenced from the unwinder code.
- Add FTRACE trampolines to special_functions[]:
ftrace_graph_call()
ftrace_graph_caller()
return_to_handler()
- Add the kretprobe trampoline to special functions[]:
kretprobe_trampoline()
Previous versions and discussion
================================
v12: https://lore.kernel.org/linux-arm-kernel/[email protected]/T/#m21e86eecb9b8f0831196568f0bf62c3b56f65bf0
v11: https://lore.kernel.org/linux-arm-kernel/[email protected]/T/#t
v10: https://lore.kernel.org/linux-arm-kernel/[email protected]/T/#t
v9: Mailer screwed up the threading. Sent the same as v10 with proper threading.
v8: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v7: Mailer screwed up the threading. Sent the same as v8 with proper threading.
v6: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v5: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v4: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v3: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v2: https://lore.kernel.org/linux-arm-kernel/[email protected]/
v1: https://lore.kernel.org/linux-arm-kernel/[email protected]/
Madhavan T. Venkataraman (11):
arm64: Remove NULL task check from unwind_frame()
arm64: Rename unwinder functions
arm64: Rename stackframe to unwind_state
arm64: Split unwind_init()
arm64: Copy the task argument to unwind_state
arm64: Use stack_trace_consume_fn and rename args to unwind()
arm64: Make the unwind loop in unwind() similar to other architectures
arm64: Introduce stack trace reliability checks in the unwinder
arm64: Create a list of SYM_CODE functions, check return PC against
list
arm64: Introduce arch_stack_walk_reliable()
arm64: Select HAVE_RELIABLE_STACKTRACE
arch/arm64/Kconfig | 1 + arch/arm64/include/asm/linkage.h | 12 ++ arch/arm64/include/asm/sections.h | 1 + arch/arm64/include/asm/stacktrace.h | 14 +- arch/arm64/kernel/stacktrace.c | 287 +++++++++++++++++++++------- arch/arm64/kernel/vmlinux.lds.S | 10 + 6 files changed, 258 insertions(+), 67 deletions(-)
base-commit: a33f5c380c4bd3fa5278d690421b72052456d9fe
Signature · 1 line
2.25.1
PATCH v13 1/11 arm64: Remove NULL task check from unwind_frame()
From: "Madhavan T. Venkataraman" <[email protected]>
Currently, there is a check for a NULL task in unwind_frame(). It is not needed since all current consumers pass a non-NULL task.
--- arch/arm64/kernel/stacktrace.c | 3 --- 1 file changed, 3 deletions(-)
arch/arm64/kernel/stacktrace.c +0 -3
@@ -69,9 +69,6 @@ static int notrace unwind_frame(struct task_struct *tsk,unsigned long fp = frame->fp;struct stack_info info; -if (!tsk) - tsk = current; -/* Final frame; nothing to unwind */ if (fp == (unsigned long )task_pt_regs (tsk)->stackframe)return -ENOENT ;
Signature · 1 line
2.25.1
PATCH v13 2/11 arm64: Rename unwinder functions
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Rename unwinder functions for consistency and better naming.
- Rename start_backtrace() to unwind_init().
- Rename unwind_frame() to unwind_next().
- Rename walk_stackframe() to unwind().
--- arch/arm64/kernel/stacktrace.c | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-)
arch/arm64/kernel/stacktrace.c +16 -16
@@ -33,8 +33,8 @@*/ -static void start_backtrace (struct stackframe *frame,unsigned long fp, -unsigned long pc) +static void unwind_init (struct stackframe *frame,unsigned long fp, +unsigned long pc) { frame->fp = fp; frame->pc = pc;
@@ -45,7 +45,7 @@ static void start_backtrace(struct stackframe *frame, unsigned long fp,/* * Prime the first unwind. * -* In unwind_frame() we'll check that the FP points to a valid stack, +* In unwind_next() we'll check that the FP points to a valid stack, * which can't be STACK_TYPE_UNKNOWN, and the first unwind will be * treated as a transition to whichever stack that happens to be. The * prev_fp value won't be used, but we set it to 0 such that it is
@@ -63,8 +63,8 @@ static void start_backtrace(struct stackframe *frame, unsigned long fp,* records (e.g. a cycle), determined based on the location and fp value of A * and the location (but not the fp value) of B. */ -static int notrace unwind_frame(struct task_struct *tsk, -struct stackframe *frame) +static int notrace unwind_next(struct task_struct *tsk, +struct stackframe *frame) {unsigned long fp = frame->fp;struct stack_info info;
@@ -104,7 +104,7 @@ static int notrace unwind_frame(struct task_struct *tsk,/* * Record this frame record's values and location. The prev_fp and -* prev_type are only meaningful to the next unwind_frame() invocation. +* prev_type are only meaningful to the next unwind_next() invocation. */ frame->fp =READ_ONCE_NOCHECK (*(unsigned long *)(fp)); frame->pc =READ_ONCE_NOCHECK (*(unsigned long *)(fp +8 ));
@@ -137,23 +137,23 @@ static int notrace unwind_frame(struct task_struct *tsk,return 0 ; } -NOKPROBE_SYMBOL (unwind_frame); +NOKPROBE_SYMBOL (unwind_next); -static void notrace walk_stackframe(struct task_struct *tsk, -struct stackframe *frame, -bool (*fn)(void *,unsigned long ),void *data) +static void notrace unwind(struct task_struct *tsk, +struct stackframe *frame, +bool (*fn)(void *,unsigned long ),void *data) {while (1 ) {int ret;if (!fn (data, frame->pc))break ; - ret =unwind_frame (tsk, frame); + ret =unwind_next (tsk, frame);if (ret <0 )break ; } } -NOKPROBE_SYMBOL (walk_stackframe); +NOKPROBE_SYMBOL (unwind);static bool dump_backtrace_entry (void *arg,unsigned long where) {
@@ -195,14 +195,14 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct stackframe frame;if (regs) -start_backtrace (&frame, regs->regs[29 ], regs->pc); +unwind_init (&frame, regs->regs[29 ], regs->pc);else if (task == current) -start_backtrace (&frame, +unwind_init (&frame, (unsigned long )__builtin_frame_address (1 ), (unsigned long )__builtin_return_address (0 ));else -start_backtrace (&frame,thread_saved_fp (task), +unwind_init (&frame,thread_saved_fp (task),thread_saved_pc (task)); -walk_stackframe (task, &frame, consume_entry, cookie); +unwind (task, &frame, consume_entry, cookie); }
Signature · 1 line
2.25.1
PATCH v13 3/11 arm64: Rename stackframe to unwind_state
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Rename "struct stackframe" to "struct unwind_state" for consistency and better naming. Accordingly, rename variable/argument "frame" to "state".
--- arch/arm64/include/asm/stacktrace.h | 2 +- arch/arm64/kernel/stacktrace.c | 66 ++++++++++++++--------------- 2 files changed, 34 insertions(+), 34 deletions(-)
arch/arm64/include/asm/stacktrace.h +1 -1
@@ -52,7 +52,7 @@ struct stack_info {* associated with the most recently encountered replacement lr * value. */ -struct stackframe { +struct unwind_state {unsigned long fp;unsigned long pc; DECLARE_BITMAP(stacks_done, __NR_STACK_TYPES);
arch/arm64/kernel/stacktrace.c +33 -33
146 lines not on this page · raw message
Signature · 1 line
2.25.1
PATCH v13 4/11 arm64: Split unwind_init()
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
unwind_init() is currently a single function that initializes all of the unwind state. Split it into the following functions and call them appropriately:
- unwind_init_from_regs() - initialize from regs passed by caller.
- unwind_init_from_current() - initialize for the current task from the caller of arch_stack_walk().
- unwind_init_from_task() - initialize from the saved state of a task other than the current task. In this case, the other task must not be running.
This is done for two reasons:
- the different ways of initializing are clear
- specialized code can be added to each initializer in the future.
--- arch/arm64/kernel/stacktrace.c | 54 +++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 10 deletions(-)
arch/arm64/kernel/stacktrace.c +44 -10
@@ -33,11 +33,8 @@*/ -static void unwind_init (struct unwind_state *state,unsigned long fp, -unsigned long pc) +static void unwind_init_common (struct unwind_state *state) { - state->fp = fp; - state->pc = pc;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif
@@ -56,6 +53,46 @@ static void unwind_init(struct unwind_state *state, unsigned long fp, state->prev_type =STACK_TYPE_UNKNOWN ; } +/* +* TODO: document requirements here. +*/ +static inline void unwind_init_from_regs (struct unwind_state *state, +struct pt_regs *regs) +{ +unwind_init_common (state); + + state->fp = regs->regs[29 ]; + state->pc = regs->pc; +} + +/* +* TODO: document requirements here. +* +* Note: this is always inlined, and we expect our caller to be a noinline +* function, such that this starts from our caller's caller. +*/ +static __always_inline void unwind_init_from_current(struct unwind_state *state) +{ +unwind_init_common (state); + + state->fp = (unsigned long )__builtin_frame_address (1 ); + state->pc = (unsigned long )__builtin_return_address (0 ); +} + +/* +* TODO: document requirements here. +* +* The caller guarantees that the task is not running. +*/ +static inline void unwind_init_from_task (struct unwind_state *state, +struct task_struct *task) +{ +unwind_init_common (state); + + state->fp =thread_saved_fp (task); + state->pc =thread_saved_pc (task); +} +/* * Unwind from one frame record (A) to the next frame record (B). *
@@ -195,14 +232,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init (&state, regs->regs[29 ], regs->pc); +unwind_init_from_regs (&state, regs);else if (task == current) -unwind_init (&state, - (unsigned long )__builtin_frame_address (1 ), - (unsigned long )__builtin_return_address (0 )); +unwind_init_from_current (&state);else -unwind_init (&state,thread_saved_fp (task), -thread_saved_pc (task)); +unwind_init_from_task (&state, task);unwind (task, &state, consume_entry, cookie); }
Signature · 1 line
2.25.1
Re: [PATCH v13 04/11] arm64: Split unwind_init()
Quoted 11 lines · On Mon, Jan 17, 2022 at 08:56:01AM -0600, [email protected] wrote:
arch/arm64/kernel/stacktrace.c +10
-0+/* +* TODO: document requirements here. +*/ +static inline void unwind_init_from_regs (struct unwind_state *state, +struct pt_regs *regs) +/* +* TODO: document requirements here. +* +* Note: this is always inlined, and we expect our caller to be a noinline +* function, such that this starts from our caller's caller.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 88
Quoted 10 lines
arch/arm64/kernel/stacktrace.c +9
-0+*/ +static __always_inline void unwind_init_from_current(struct unwind_state *state) +/* + * TODO: document requirements here. + * + * The caller guarantees that the task is not running. + */ +static inline void unwind_init_from_task(struct unwind_state *state, + struct task_struct *task)
Other than the obvious gap this looks good to me. For _current() I don't think we've got any particular requirements other than what's documented. For the others I think the main thing is that trying to walk the stack of a task that is actively executing is going to be a bad idea so we should say that the task shouldn't be running, but in general given that one of the main use cases is printing diagnostics on error we shouldn't have too many *requirements* for calling these.
Re: [PATCH v13 04/11] arm64: Split unwind_init()
Quoted 16 lines · Mark Brown
Quoted 13 lines · On Mon, Jan 17, 2022 at 08:56:01AM -0600, [email protected] wrote:
arch/arm64/kernel/stacktrace.c +12
-0+/* +* TODO: document requirements here. +*/ +static inline void unwind_init_from_regs(struct unwind_state *state, + struct pt_regs *regs) +/* + * TODO: document requirements here. + * + * Note: this is always inlined, and we expect our caller to be a noinline + * function, such that this starts from our caller's caller. + */ +static __always_inline void unwind_init_from_current(struct unwind_state *state)
Quoted 15 lines
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 88
Quoted 7 lines
arch/arm64/kernel/stacktrace.c +7
-0+/* +* TODO: document requirements here. +* +* The caller guarantees that the task is not running. +*/ +static inline void unwind_init_from_task (struct unwind_state *state, +struct task_struct *task)Other than the obvious gap this looks good to me. For
_current()I don't think we've got any particular requirements other than what's documented. For the others I think the main thing is that trying to walk the stack of a task that is actively executing is going to be a bad idea so we should say that the task shouldn't be running, but in general given that one of the main use cases is printing diagnostics on error we shouldn't have too many *requirements* for calling these.
OK. For now, I will remove the TODO comment from individual functions. I will add only a common general comment above all 3 helpers that additional requirements may be documented as seen fit. And, I will add that the task must not be running in other-directed cases.
Madhavan
Re: [PATCH v13 04/11] arm64: Split unwind_init()
Quoted 35 lines · Madhavan T. Venkataraman
Quoted 16 lines · Mark Brown
Quoted 13 lines · On Mon, Jan 17, 2022 at 08:56:01AM -0600, [email protected] wrote:
arch/arm64/kernel/stacktrace.c +12
-0+/* +* TODO: document requirements here. +*/ +static inline void unwind_init_from_regs(struct unwind_state *state, + struct pt_regs *regs) +/* + * TODO: document requirements here. + * + * Note: this is always inlined, and we expect our caller to be a noinline + * function, such that this starts from our caller's caller. + */ +static __always_inline void unwind_init_from_current(struct unwind_state *state)Quoted 15 lines
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 88
Quoted 7 lines
arch/arm64/kernel/stacktrace.c +7
-0+/* +* TODO: document requirements here. +* +* The caller guarantees that the task is not running. +*/ +static inline void unwind_init_from_task (struct unwind_state *state, +struct task_struct *task)Other than the obvious gap this looks good to me. For
_current()I don't think we've got any particular requirements other than what's documented. For the others I think the main thing is that trying to walk the stack of a task that is actively executing is going to be a bad idea so we should say that the task shouldn't be running, but in general given that one of the main use cases is printing diagnostics on error we shouldn't have too many *requirements* for calling these.
Quoted 5 lines
OK. For now, I will remove the TODO comment from individual functions. I will add only a common general comment above all 3 helpers that additional requirements may be documented as seen fit. And, I will add that the task must not be running in other-directed cases.
If what I have suggested above for comments is good enough, can I get a Reviewed-by for this? I will fix the comments on the next send.
Quoted 1 line
Madhavan
Re: [PATCH v13 04/11] arm64: Split unwind_init()
Quoted 2 lines · Madhavan T. Venkataraman
If what I have suggested above for comments is good enough, can I get a Reviewed-by for this? I will fix the comments on the next send.
I would think so, I'll take a look at the new version.
Mark Rutland
reviewerRe: [PATCH v13 04/11] arm64: Split unwind_init()
In reply to [email protected]Hi Madhavan,
The diff itself largely looks good, but we need to actually write the comments. Can you pleaes pick up the wording I've written below for those?
That and renaming unwind_init_from_current to unwind_init_from_caller.
With those I think this is good, but I'd like to see the updated version before I provide Acked-by or Reviewed-by tags -- hopefully that's just a formality! :)
Quoted 44 lines · On Mon, Jan 17, 2022 at 08:56:01AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
unwind_init()is currently a single function that initializes all of the unwind state. Split it into the following functions and call them appropriately:-
unwind_init_from_regs()- initialize from regs passed by caller.-
unwind_init_from_current()- initialize for the current task from the caller ofarch_stack_walk().-
unwind_init_from_task()- initialize from the saved state of a task other than the current task. In this case, the other task must not be running.This is done for two reasons:
- the different ways of initializing are clear
- specialized code can be added to each initializer in the future.
Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/kernel/stacktrace.c | 54 +++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 10 deletions(-)arch/arm64/kernel/stacktrace.c +1
-4@@ -33,11 +33,8 @@*/ -static void unwind_init (struct unwind_state *state,unsigned long fp, -unsigned long pc) +static void unwind_init_common (struct unwind_state *state) { - state->fp = fp; - state->pc = pc;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 58
Quoted 6 lines
arch/arm64/kernel/stacktrace.c +3
-0@@ -56,6 +53,46 @@ static void unwind_init(struct unwind_state *state, unsigned long fp, state->prev_type =STACK_TYPE_UNKNOWN ; } +/* +* TODO: document requirements here. +*/
Please make this:
/*
* Start an unwind from a pt_regs.
*
* The unwind will begin at the PC within the regs.
*
* The regs must be on a stack currently owned by the calling task. */
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 61
Quoted 3 lines
arch/arm64/kernel/stacktrace.c +3
-0+static inline void unwind_init_from_regs (struct unwind_state *state, +struct pt_regs *regs) +{
In future we could add:
WARN_ON_ONCE(!on_accessible_stack(current, regs, sizeof(*regs), NULL));
... to validate the requirements, but I'm happy to lave that for a future patch so this patch can be a pure refactoring.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 73
Quoted 12 lines
arch/arm64/kernel/stacktrace.c +12
-0+unwind_init_common (state); + + state->fp = regs->regs[29 ]; + state->pc = regs->pc; +} + +/* +* TODO: document requirements here. +* +* Note: this is always inlined, and we expect our caller to be a noinline +* function, such that this starts from our caller's caller. +*/
Please make this:
/*
* Start an unwind from a caller.
*
* The unwind will begin at the caller of whichever function this is inlined
* into.
*
* The function which invokes this must be noinline.
*/
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 74
Quoted 1 line
arch/arm64/kernel/stacktrace.c +1
-0+static __always_inline void unwind_init_from_current(struct unwind_state *state)
Can we please rename s/current/caller/ here? That way it's clear *where* in current we're unwinding from, and the fact that it's current is implicit but obvious.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 75
Quoted 1 line
arch/arm64/kernel/stacktrace.c +1
-0+{
Similarly to unwind_init_from_regs(), in a future patch we could add:
WARN_ON_ONCE(task == current);
... but for now we can omit that so this patch can be a pure refactoring.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 86
Quoted 11 lines
arch/arm64/kernel/stacktrace.c +11
-0+unwind_init_common (state); + + state->fp = (unsigned long )__builtin_frame_address (1 ); + state->pc = (unsigned long )__builtin_return_address (0 ); +} + +/* +* TODO: document requirements here. +* +* The caller guarantees that the task is not running. +*/
Please make this:
/*
* Start an unwind from a blocked task.
*
* The unwind will begin at the blocked tasks saved PC (i.e. the caller of
* cpu_switch_to()).
*
* The caller should ensure the task is blocked in cpu_switch_to() for the
* duration of the unwind, or the unwind will be bogus. It is never valid to
* call this for the current task.
*/
Thanks,
Mark.
Quoted 33 lines
arch/arm64/kernel/stacktrace.c +12
-6+static inline void unwind_init_from_task (struct unwind_state *state, +struct task_struct *task) +{ +unwind_init_common (state); + + state->fp =thread_saved_fp (task); + state->pc =thread_saved_pc (task); +} +/* * Unwind from one frame record (A) to the next frame record (B). * @@ -195,14 +232,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init (&state, regs->regs[29 ], regs->pc); +unwind_init_from_regs (&state, regs);else if (task == current) -unwind_init (&state, - (unsigned long )__builtin_frame_address (1 ), - (unsigned long )__builtin_return_address (0 )); +unwind_init_from_current (&state);else -unwind_init (&state,thread_saved_fp (task), -thread_saved_pc (task)); +unwind_init_from_task (&state, task);unwind (task, &state, consume_entry, cookie); }Signature · 1 line
2.25.1
Re: [PATCH v13 04/11] arm64: Split unwind_init()
Quoted 10 lines · Mark Rutland
Hi Madhavan,
The diff itself largely looks good, but we need to actually write the comments. Can you pleaes pick up the wording I've written below for those?
That and renaming
unwind_init_from_currenttounwind_init_from_caller.With those I think this is good, but I'd like to see the updated version before I provide Acked-by or Reviewed-by tags -- hopefully that's just a formality! :)
Will do.
Madhavan
Quoted 172 lines · On Mon, Jan 17, 2022 at 08:56:01AM -0600, [email protected] wrote:
Quoted 44 lines
From: "Madhavan T. Venkataraman" <[email protected]>
unwind_init()is currently a single function that initializes all of the unwind state. Split it into the following functions and call them appropriately:-
unwind_init_from_regs()- initialize from regs passed by caller.-
unwind_init_from_current()- initialize for the current task from the caller ofarch_stack_walk().-
unwind_init_from_task()- initialize from the saved state of a task other than the current task. In this case, the other task must not be running.This is done for two reasons:
- the different ways of initializing are clear
- specialized code can be added to each initializer in the future.
Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/kernel/stacktrace.c | 54 +++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 10 deletions(-)arch/arm64/kernel/stacktrace.c +1
-4@@ -33,11 +33,8 @@*/ -static void unwind_init (struct unwind_state *state,unsigned long fp, -unsigned long pc) +static void unwind_init_common (struct unwind_state *state) { - state->fp = fp; - state->pc = pc;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 58
Quoted 6 lines
arch/arm64/kernel/stacktrace.c +3
-0@@ -56,6 +53,46 @@ static void unwind_init(struct unwind_state *state, unsigned long fp, state->prev_type =STACK_TYPE_UNKNOWN ; } +/* +* TODO: document requirements here. +*/ Please make this:
/*
* Start an unwind from apt_regs.
*
* The unwind will begin at the PC within the regs.
*
* The regs must be on a stack currently owned by the calling task. */arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 61
Quoted 3 lines
arch/arm64/kernel/stacktrace.c +3
-0+static inline void unwind_init_from_regs (struct unwind_state *state, +struct pt_regs *regs) +{In future we could add:
WARN_ON_ONCE(!on_accessible_stack(current, regs, sizeof(*regs), NULL));... to validate the requirements, but I'm happy to lave that for a future patch so this patch can be a pure refactoring.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 73
Quoted 12 lines
arch/arm64/kernel/stacktrace.c +12
-0+unwind_init_common (state); + + state->fp = regs->regs[29 ]; + state->pc = regs->pc; +} + +/* +* TODO: document requirements here. +* +* Note: this is always inlined, and we expect our caller to be a noinline +* function, such that this starts from our caller's caller. +*/ Please make this:
/*
* Start an unwind from a caller.
*
* The unwind will begin at the caller of whichever function this is inlined
* into.
*
* The function which invokes this must be noinline.
*/arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 74
Quoted 1 line
arch/arm64/kernel/stacktrace.c +1
-0+static __always_inline void unwind_init_from_current(struct unwind_state *state)Can we please rename s/current/caller/ here? That way it's clear *where* in current we're unwinding from, and the fact that it's current is implicit but obvious.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 75
Quoted 1 line
arch/arm64/kernel/stacktrace.c +1
-0+{Similarly to
unwind_init_from_regs(), in a future patch we could add:WARN_ON_ONCE(task == current);... but for now we can omit that so this patch can be a pure refactoring.
arch/arm64/kernel/stacktrace.c static void unwind_init(struct unwind_state *state, unsigned long fp, · line 86
Quoted 11 lines
arch/arm64/kernel/stacktrace.c +11
-0+unwind_init_common (state); + + state->fp = (unsigned long )__builtin_frame_address (1 ); + state->pc = (unsigned long )__builtin_return_address (0 ); +} + +/* +* TODO: document requirements here. +* +* The caller guarantees that the task is not running. +*/ Please make this:
/*
* Start an unwind from a blocked task.
*
* The unwind will begin at the blocked tasks saved PC (i.e. the caller of
*cpu_switch_to()).
*
* The caller should ensure the task is blocked incpu_switch_to()for the
* duration of the unwind, or the unwind will be bogus. It is never valid to
* call this for the current task.
*/Thanks,
Mark.Quoted 33 lines
arch/arm64/kernel/stacktrace.c +12
-6+static inline void unwind_init_from_task (struct unwind_state *state, +struct task_struct *task) +{ +unwind_init_common (state); + + state->fp =thread_saved_fp (task); + state->pc =thread_saved_pc (task); +} +/* * Unwind from one frame record (A) to the next frame record (B). * @@ -195,14 +232,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init (&state, regs->regs[29 ], regs->pc); +unwind_init_from_regs (&state, regs);else if (task == current) -unwind_init (&state, - (unsigned long )__builtin_frame_address (1 ), - (unsigned long )__builtin_return_address (0 )); +unwind_init_from_current (&state);else -unwind_init (&state,thread_saved_fp (task), -thread_saved_pc (task)); +unwind_init_from_task (&state, task);unwind (task, &state, consume_entry, cookie); }Signature · 1 line
2.25.1
PATCH v13 5/11 arm64: Copy the task argument to unwind_state
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Copy the task argument passed to arch_stack_walk() to unwind_state so that it can be passed to unwind functions via unwind_state rather than as a separate argument. The task is a fundamental part of the unwind state.
--- arch/arm64/include/asm/stacktrace.h | 3 +++ arch/arm64/kernel/stacktrace.c | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-)
arch/arm64/include/asm/stacktrace.h +3 -0
@@ -51,6 +51,8 @@ struct stack_info {* @kr_cur: When KRETPROBES is selected, holds the kretprobe instance * associated with the most recently encountered replacement lr * value. +* +* @task: Pointer to the task structure. */ struct unwind_state {unsigned long fp;
@@ -61,6 +63,7 @@ struct unwind_state {#ifdef CONFIG_KRETPROBES struct llist_node *kr_cur;#endif +struct task_struct *task; }; extern void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,
arch/arm64/kernel/stacktrace.c +16 -13
@@ -33,8 +33,10 @@*/ -static void unwind_init_common (struct unwind_state *state) +static void unwind_init_common (struct unwind_state *state, +struct task_struct *task) { + state->task = task;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif
@@ -57,9 +59,10 @@ static void unwind_init_common(struct unwind_state *state)* TODO: document requirements here. */ static inline void unwind_init_from_regs (struct unwind_state *state, +struct task_struct *task,struct pt_regs *regs) { -unwind_init_common (state); +unwind_init_common (state, task); state->fp = regs->regs[29 ]; state->pc = regs->pc;
@@ -71,9 +74,10 @@ static inline void unwind_init_from_regs(struct unwind_state *state,* Note: this is always inlined, and we expect our caller to be a noinline * function, such that this starts from our caller's caller. */ -static __always_inline void unwind_init_from_current(struct unwind_state *state) +static __always_inline void unwind_init_from_current(struct unwind_state *state, +struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task); state->fp = (unsigned long )__builtin_frame_address (1 ); state->pc = (unsigned long )__builtin_return_address (0 );
@@ -87,7 +91,7 @@ static __always_inline void unwind_init_from_current(struct unwind_state *state)static inline void unwind_init_from_task (struct unwind_state *state,struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task); state->fp =thread_saved_fp (task); state->pc =thread_saved_pc (task);
@@ -100,11 +104,11 @@ static inline void unwind_init_from_task(struct unwind_state *state,* records (e.g. a cycle), determined based on the location and fp value of A * and the location (but not the fp value) of B. */ -static int notrace unwind_next(struct task_struct *tsk, -struct unwind_state *state) +static int notrace unwind_next(struct unwind_state *state) {unsigned long fp = state->fp;struct stack_info info; +struct task_struct *tsk = state->task;/* Final frame; nothing to unwind */ if (fp == (unsigned long )task_pt_regs (tsk)->stackframe)
@@ -176,8 +180,7 @@ static int notrace unwind_next(struct task_struct *tsk, }NOKPROBE_SYMBOL (unwind_next); -static void notrace unwind(struct task_struct *tsk, -struct unwind_state *state, +static void notrace unwind(struct unwind_state *state,bool (*fn)(void *,unsigned long ),void *data) {while (1 ) {
@@ -185,7 +188,7 @@ static void notrace unwind(struct task_struct *tsk,if (!fn (data, state->pc))break ; - ret =unwind_next (tsk, state); + ret =unwind_next (state);if (ret <0 )break ; }
@@ -232,11 +235,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init_from_regs (&state, regs); +unwind_init_from_regs (&state, task, regs);else if (task == current) -unwind_init_from_current (&state); +unwind_init_from_current (&state, task);else unwind_init_from_task (&state, task); -unwind (task, &state, consume_entry, cookie); +unwind (&state, consume_entry, cookie); }
Signature · 1 line
2.25.1
Re: [PATCH v13 05/11] arm64: Copy the task argument to unwind_state
Quoted 5 lines · On Mon, Jan 17, 2022 at 08:56:02AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Copy the task argument passed to
arch_stack_walk()tounwind_stateso that it can be passed to unwind functions viaunwind_staterather than as a separate argument. The task is a fundamental part of the unwind state.
Mark Rutland
reviewerRe: [PATCH v13 05/11] arm64: Copy the task argument to unwind_state
In reply to [email protected]Quoted 17 lines · On Mon, Jan 17, 2022 at 08:56:02AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Copy the task argument passed to
arch_stack_walk()tounwind_stateso that it can be passed to unwind functions viaunwind_staterather than as a separate argument. The task is a fundamental part of the unwind state.Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/include/asm/stacktrace.h | 3 +++ arch/arm64/kernel/stacktrace.c | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-)arch/arm64/include/asm/stacktrace.h +0
-0
arch/arm64/include/asm/stacktrace.h struct stack_info { · line 55
Quoted 5 lines
arch/arm64/include/asm/stacktrace.h +2
-0@@ -51,6 +51,8 @@ struct stack_info {* @kr_cur: When KRETPROBES is selected, holds the kretprobe instance * associated with the most recently encountered replacement lr * value. +* +* @task: Pointer to the task structure.
Can we please say:
@task: The task being unwound.
Quoted 28 lines
arch/arm64/include/asm/stacktrace.h +1
-0*/ struct unwind_state {unsigned long fp;@@ -61,6 +63,7 @@ struct unwind_state {#ifdef CONFIG_KRETPROBES struct llist_node *kr_cur;#endif +struct task_struct *task; }; extern void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,arch/arm64/kernel/stacktrace.c +3
-1@@ -33,8 +33,10 @@*/ -static void unwind_init_common (struct unwind_state *state) +static void unwind_init_common (struct unwind_state *state, +struct task_struct *task) { + state->task = task;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif
arch/arm64/kernel/stacktrace.c static void unwind_init_common(struct unwind_state *state) · line 62
Quoted 4 lines
arch/arm64/kernel/stacktrace.c +1
-0@@ -57,9 +59,10 @@ static void unwind_init_common(struct unwind_state *state)* TODO: document requirements here. */ static inline void unwind_init_from_regs(struct unwind_state *state, + struct task_struct *task,
Please drop the task parameter here ...
arch/arm64/kernel/stacktrace.c static void unwind_init_common(struct unwind_state *state) · line 65
Quoted 4 lines
arch/arm64/kernel/stacktrace.c +1
-1struct pt_regs *regs) { -unwind_init_common (state); +unwind_init_common (state, task);
... and make this:
unwind_init_common(state, current);
... since that way it's *impossible* to have ismatched parameters, which is one of the reasons for having separate functions in the first place.
arch/arm64/kernel/stacktrace.c static inline void unwind_init_from_regs(struct unwind_state *state, · line 80
Quoted 12 lines
arch/arm64/kernel/stacktrace.c +3
-2state->fp = regs->regs[29 ]; state->pc = regs->pc;@@ -71,9 +74,10 @@ static inline void unwind_init_from_regs(struct unwind_state *state,* Note: this is always inlined, and we expect our caller to be a noinline * function, such that this starts from our caller's caller. */ -static __always_inline void unwind_init_from_current(struct unwind_state *state) +static __always_inline void unwind_init_from_current(struct unwind_state *state, +struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task);
Same comments as for unwind_init_from_regs(): please drop the task parameter and hard-code current in the call to unwind_init_common().
Quoted 45 lines
arch/arm64/kernel/stacktrace.c +5
-6state->fp = (unsigned long )__builtin_frame_address (1 ); state->pc = (unsigned long )__builtin_return_address (0 );@@ -87,7 +91,7 @@ static __always_inline void unwind_init_from_current(struct unwind_state *state)static inline void unwind_init_from_task (struct unwind_state *state,struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task); state->fp =thread_saved_fp (task); state->pc =thread_saved_pc (task);@@ -100,11 +104,11 @@ static inline void unwind_init_from_task(struct unwind_state *state,* records (e.g. a cycle), determined based on the location and fp value of A * and the location (but not the fp value) of B. */ -static int notrace unwind_next(struct task_struct *tsk, -struct unwind_state *state) +static int notrace unwind_next(struct unwind_state *state) {unsigned long fp = state->fp;struct stack_info info; +struct task_struct *tsk = state->task;/* Final frame; nothing to unwind */ if (fp == (unsigned long )task_pt_regs (tsk)->stackframe)@@ -176,8 +180,7 @@ static int notrace unwind_next(struct task_struct *tsk, }NOKPROBE_SYMBOL (unwind_next); -static void notrace unwind(struct task_struct *tsk, -struct unwind_state *state, +static void notrace unwind(struct unwind_state *state,bool (*fn)(void *,unsigned long ),void *data) {while (1 ) {@@ -185,7 +188,7 @@ static void notrace unwind(struct task_struct *tsk,if (!fn (data, state->pc))break ; - ret =unwind_next (tsk, state); + ret =unwind_next (state);if (ret <0 )break ; }
arch/arm64/kernel/stacktrace.c noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry, · line 242
Quoted 10 lines
arch/arm64/kernel/stacktrace.c +2
-2@@ -232,11 +235,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init_from_regs (&state, regs); +unwind_init_from_regs (&state, task, regs);else if (task == current) -unwind_init_from_current (&state); +unwind_init_from_current (&state, task);else unwind_init_from_task (&state, task);
As above we shouldn't need these two changes.
For the regs case we might want to sanity-check that task == current.
arch/arm64/kernel/stacktrace.c noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry, · line 244
Quoted 2 lines
arch/arm64/kernel/stacktrace.c +1
-1-unwind (task, &state, consume_entry, cookie); +unwind (&state, consume_entry, cookie);
Otherwise, this looks good to me.
Thanks,
Mark.
Re: [PATCH v13 05/11] arm64: Copy the task argument to unwind_state
It looks like I forgot to reply to this. Sorry about that.
Quoted 26 lines · Mark Rutland
Quoted 17 lines · On Mon, Jan 17, 2022 at 08:56:02AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Copy the task argument passed to
arch_stack_walk()tounwind_stateso that it can be passed to unwind functions viaunwind_staterather than as a separate argument. The task is a fundamental part of the unwind state.Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/include/asm/stacktrace.h | 3 +++ arch/arm64/kernel/stacktrace.c | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-)arch/arm64/include/asm/stacktrace.h +0
-0arch/arm64/include/asm/stacktrace.h struct stack_info { · line 55
Quoted 5 lines
arch/arm64/include/asm/stacktrace.h +2
-0@@ -51,6 +51,8 @@ struct stack_info {* @kr_cur: When KRETPROBES is selected, holds the kretprobe instance * associated with the most recently encountered replacement lr * value. +* +* @task: Pointer to the task structure. Can we please say:
Quoted 2 lines
@task: The task being unwound.
Will do.
Quoted 19 lines
Quoted 19 lines
arch/arm64/include/asm/stacktrace.h +1
-0*/ struct unwind_state {unsigned long fp;@@ -61,6 +63,7 @@ struct unwind_state {#ifdef CONFIG_KRETPROBES struct llist_node *kr_cur;#endif +struct task_struct *task; }; extern void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,arch/arm64/kernel/stacktrace.c +0
-0@@ -33,8 +33,10 @@*/
Quoted 15 lines
arch/arm64/kernel/stacktrace.c static void unwind_init_common(struct unwind_state *state) · line 62
Quoted 13 lines
arch/arm64/kernel/stacktrace.c +4
-1-static void unwind_init_common (struct unwind_state *state) +static void unwind_init_common (struct unwind_state *state, +struct task_struct *task) { + state->task = task;#ifdef CONFIG_KRETPROBES state->kr_cur =NULL ;#endif @@ -57,9 +59,10 @@ static void unwind_init_common(struct unwind_state *state)* TODO: document requirements here. */ static inline void unwind_init_from_regs(struct unwind_state *state, + struct task_struct *task,Please drop the
taskparameter here ...
OK.
Quoted 9 lines
arch/arm64/kernel/stacktrace.c static void unwind_init_common(struct unwind_state *state) · line 65
Quoted 5 lines
arch/arm64/kernel/stacktrace.c +1
-1struct pt_regs *regs) { -unwind_init_common (state); +unwind_init_common (state, task);... and make this:
unwind_init_common(state, current);
OK.
Quoted 4 lines
... since that way it's *impossible* to have ismatched parameters, which is one of the reasons for having separate functions in the first place.
Quoted 16 lines
arch/arm64/kernel/stacktrace.c static inline void unwind_init_from_regs(struct unwind_state *state, · line 80
Quoted 12 lines
arch/arm64/kernel/stacktrace.c +3
-2state->fp = regs->regs[29 ]; state->pc = regs->pc;@@ -71,9 +74,10 @@ static inline void unwind_init_from_regs(struct unwind_state *state,* Note: this is always inlined, and we expect our caller to be a noinline * function, such that this starts from our caller's caller. */ -static __always_inline void unwind_init_from_current(struct unwind_state *state) +static __always_inline void unwind_init_from_current(struct unwind_state *state, +struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task);Same comments as for
unwind_init_from_regs(): please drop thetaskparameter and hard-codecurrentin the call tounwind_init_common().
OK.
Quoted 58 lines
Quoted 45 lines
arch/arm64/kernel/stacktrace.c +5
-6state->fp = (unsigned long )__builtin_frame_address (1 ); state->pc = (unsigned long )__builtin_return_address (0 );@@ -87,7 +91,7 @@ static __always_inline void unwind_init_from_current(struct unwind_state *state)static inline void unwind_init_from_task (struct unwind_state *state,struct task_struct *task) { -unwind_init_common (state); +unwind_init_common (state, task); state->fp =thread_saved_fp (task); state->pc =thread_saved_pc (task);@@ -100,11 +104,11 @@ static inline void unwind_init_from_task(struct unwind_state *state,* records (e.g. a cycle), determined based on the location and fp value of A * and the location (but not the fp value) of B. */ -static int notrace unwind_next(struct task_struct *tsk, -struct unwind_state *state) +static int notrace unwind_next(struct unwind_state *state) {unsigned long fp = state->fp;struct stack_info info; +struct task_struct *tsk = state->task;/* Final frame; nothing to unwind */ if (fp == (unsigned long )task_pt_regs (tsk)->stackframe)@@ -176,8 +180,7 @@ static int notrace unwind_next(struct task_struct *tsk, }NOKPROBE_SYMBOL (unwind_next); -static void notrace unwind(struct task_struct *tsk, -struct unwind_state *state, +static void notrace unwind(struct unwind_state *state,bool (*fn)(void *,unsigned long ),void *data) {while (1 ) {@@ -185,7 +188,7 @@ static void notrace unwind(struct task_struct *tsk,if (!fn (data, state->pc))break ; - ret =unwind_next (tsk, state); + ret =unwind_next (state);if (ret <0 )break ; }arch/arm64/kernel/stacktrace.c noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry, · line 242
Quoted 10 lines
arch/arm64/kernel/stacktrace.c +2
-2@@ -232,11 +235,11 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,struct unwind_state state;if (regs) -unwind_init_from_regs (&state, regs); +unwind_init_from_regs (&state, task, regs);else if (task == current) -unwind_init_from_current (&state); +unwind_init_from_current (&state, task);else unwind_init_from_task (&state, task);As above we shouldn't need these two changes.
Quoted 2 lines
For the regs case we might want to sanity-check that task == current.
Will do.
Quoted 4 lines
arch/arm64/kernel/stacktrace.c noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry, · line 244
Quoted 2 lines
arch/arm64/kernel/stacktrace.c +1
-1-unwind (task, &state, consume_entry, cookie); +unwind (&state, consume_entry, cookie);Otherwise, this looks good to me.
Thanks.
Madhavan
PATCH v13 6/11 arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to unwind() for better consistency. Also, use the typedef stack_trace_consume_fn for the consume_entry function as it is already defined in linux/stacktrace.h.
--- arch/arm64/kernel/stacktrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/arm64/kernel/stacktrace.c +2 -2
@@ -181,12 +181,12 @@ static int notrace unwind_next(struct unwind_state *state)NOKPROBE_SYMBOL (unwind_next); static void notrace unwind(struct unwind_state *state, -bool (*fn)(void *,unsigned long ),void *data) +stack_trace_consume_fn consume_entry,void *cookie) {while (1 ) {int ret; -if (!fn (data, state->pc)) +if (!consume_entry (cookie, state->pc))break ; ret =unwind_next (state);if (ret <0 )
Signature · 1 line
2.25.1
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 5 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.
Consistency with...? But otherwise:
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 8 lines · Mark Brown
Quoted 5 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Consistency with...? But otherwise:
Naming consistency. E.g., the name consume_entry is used in a lot of places. This code used to use fn() instead of consume_entry(). arch_stack_walk() names the argument to consume_entry as cookie. This code calls it data instead of cookie. That is all. It is minor in nature. But I thought I might as well make it conform while I am at it.
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 7 lines · Madhavan T. Venkataraman
Quoted 5 lines · Mark Brown
Quoted 3 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.
Quoted 7 lines
Quoted 1 line
Consistency with...? But otherwise:
Naming consistency. E.g., the name
consume_entryis used in a lot of places. This code used to usefn()instead ofconsume_entry().arch_stack_walk()names the argument toconsume_entryas cookie. This code calls it data instead of cookie. That is all. It is minor in nature. But I thought I might as well make it conform while I am at it.
The commit message should probably say some of that then.
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 10 lines · Mark Brown
Quoted 8 lines · Madhavan T. Venkataraman
Quoted 7 lines · Mark Brown
Quoted 3 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Consistency with...? But otherwise:
Quoted 7 lines
Quoted 5 lines
Naming consistency. E.g., the name
consume_entryis used in a lot of places. This code used to usefn()instead ofconsume_entry().arch_stack_walk()names the argument toconsume_entryas cookie. This code calls it data instead of cookie. That is all. It is minor in nature. But I thought I might as well make it conform while I am at it.The commit message should probably say some of that then.
OK. Will add that to the commit message in the next version.
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to [email protected]Quoted 7 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Signed-off-by Madhavan T. Venkataraman <[email protected]>
How about:
| arm64: align with common stracktrace naming | | For historical reasons, the naming of parameters and their types in the arm64 | stacktrace code differs from that used in generic code and other | architectures, even though the types are equivalent. | | For consistency and clarity, use the generic names.
Either way:
Mark.
Quoted 26 lines
--- arch/arm64/kernel/stacktrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)arch/arm64/kernel/stacktrace.c +2
-2@@ -181,12 +181,12 @@ static int notrace unwind_next(struct unwind_state *state)NOKPROBE_SYMBOL (unwind_next); static void notrace unwind(struct unwind_state *state, -bool (*fn)(void *,unsigned long ),void *data) +stack_trace_consume_fn consume_entry,void *cookie) {while (1 ) {int ret; -if (!fn (data, state->pc)) +if (!consume_entry (cookie, state->pc))break ; ret =unwind_next (state);if (ret <0 )Signature · 1 line
2.25.1
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 11 lines · Mark Rutland
Quoted 7 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Signed-off-by Madhavan T. Venkataraman <[email protected]>How about:
Quoted 8 lines
| arm64: align with common stracktrace naming | | For historical reasons, the naming of parameters and their types in the arm64 | stacktrace code differs from that used in generic code and other | architectures, even though the types are equivalent. | | For consistency and clarity, use the generic names.
Will add this.
Madhavan
Quoted 32 lines
Either way:
Reviewed-by Mark Rutland <[email protected]>Mark.
Quoted 26 lines
--- arch/arm64/kernel/stacktrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)arch/arm64/kernel/stacktrace.c +2
-2@@ -181,12 +181,12 @@ static int notrace unwind_next(struct unwind_state *state)NOKPROBE_SYMBOL (unwind_next); static void notrace unwind(struct unwind_state *state, -bool (*fn)(void *,unsigned long ),void *data) +stack_trace_consume_fn consume_entry,void *cookie) {while (1 ) {int ret; -if (!fn (data, state->pc)) +if (!consume_entry (cookie, state->pc))break ; ret =unwind_next (state);if (ret <0 )Signature · 1 line
2.25.1
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Mark RutlandHey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
Thanks.
Madhavan
Quoted 51 lines · Mark Rutland
Quoted 7 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Signed-off-by Madhavan T. Venkataraman <[email protected]>How about:
| arm64: align with common stracktrace naming | | For historical reasons, the naming of parameters and their types in the arm64 | stacktrace code differs from that used in generic code and other | architectures, even though the types are equivalent. | | For consistency and clarity, use the generic names.Either way:
Reviewed-by Mark Rutland <[email protected]>Mark.
Quoted 26 lines
--- arch/arm64/kernel/stacktrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)arch/arm64/kernel/stacktrace.c +2
-2@@ -181,12 +181,12 @@ static int notrace unwind_next(struct unwind_state *state)NOKPROBE_SYMBOL (unwind_next); static void notrace unwind(struct unwind_state *state, -bool (*fn)(void *,unsigned long ),void *data) +stack_trace_consume_fn consume_entry,void *cookie) {while (1 ) {int ret; -if (!fn (data, state->pc)) +if (!consume_entry (cookie, state->pc))break ; ret =unwind_next (state);if (ret <0 )Signature · 1 line
2.25.1
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 4 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Please don't send content free pings. As far as I remember I'd reviewed or was expecting changes based on review or dependent patches for everything that you'd sent.
Quoted 1 line
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
That's more a question for Catalin and Will. If myself and Mark have reviewed patches then we're saying we think those patches are good to go.
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 10 lines · Mark Brown
Quoted 4 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Please don't send content free pings. As far as I remember I'd reviewed or was expecting changes based on review or dependent patches for everything that you'd sent.
Indeed you did! Many thanks!
It is just that patch 11 that defines "select HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.
Quoted 5 lines
Quoted 1 line
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
That's more a question for Catalin and Will. If myself and Mark have reviewed patches then we're saying we think those patches are good to go.
Got it!
Thanks!
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 5 lines · Madhavan T. Venkataraman
It is just that patch 11 that defines "select
HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.
I think that's more a question for the livepatch people to be honest - it's not entirely a technical one, there's a bunch of confidence level stuff going on. For example there was some suggestion that people might insist on having objtool support, though there's also substantial pushback on making objtool a requirement for anything from other quarters. I was hoping that posting that patch would provoke some discussion about what exactly is needed but that's not happened thus far.
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 8 lines · Mark Brown
Quoted 5 lines · Madhavan T. Venkataraman
It is just that patch 11 that defines "select
HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.
Quoted 8 lines
I think that's more a question for the livepatch people to be honest - it's not entirely a technical one, there's a bunch of confidence level stuff going on. For example there was some suggestion that people might insist on having objtool support, though there's also substantial pushback on making objtool a requirement for anything from other quarters. I was hoping that posting that patch would provoke some discussion about what exactly is needed but that's not happened thus far.
Understood. In that case, I will remove that patch because it is not really required for my current work on the unwinder. I will bring this up later in a different patch series where it will trigger a discussion.
Thanks.
Madhavan
Miroslav Benes
maintainerRe: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Mark BrownQuoted 8 lines · Mark Brown
Quoted 5 lines · Madhavan T. Venkataraman
It is just that patch 11 that defines "select
HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.
Quoted 8 lines
I think that's more a question for the livepatch people to be honest - it's not entirely a technical one, there's a bunch of confidence level stuff going on. For example there was some suggestion that people might insist on having objtool support, though there's also substantial pushback on making objtool a requirement for anything from other quarters. I was hoping that posting that patch would provoke some discussion about what exactly is needed but that's not happened thus far.
I think everyone will be happy with HAVE_RELIABLE_STACKTRACE on arm64 as long as there is a guarantee that stack traces are really reliable. My understanding is that there is still some work to be done on arm64 arch side (but I may have misunderstood what Mark R. said elsewhere). And yes, then there is a question of objtool. It is one option but not the only one. There have been proposals of implementing guarantees on a compiler side and leaving objtool for x86_64 only (albeit objtool may bring more features to the table... ORC, arch features checking).
Madhavan also mentioned that he enhanced objtool and he planned to submit it eventually
(https://lore.kernel.org/all/[email protected]/T/#u),
so maybe arm64 maintainers could decide on a future direction based on that?
Regards
Miroslav
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 28 lines · Miroslav Benes
Quoted 8 lines · Mark Brown
Quoted 5 lines · Madhavan T. Venkataraman
It is just that patch 11 that defines "select
HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.Quoted 8 lines
I think that's more a question for the livepatch people to be honest - it's not entirely a technical one, there's a bunch of confidence level stuff going on. For example there was some suggestion that people might insist on having objtool support, though there's also substantial pushback on making objtool a requirement for anything from other quarters. I was hoping that posting that patch would provoke some discussion about what exactly is needed but that's not happened thus far.
I think everyone will be happy with
HAVE_RELIABLE_STACKTRACEon arm64 as long as there is a guarantee that stack traces are really reliable. My understanding is that there is still some work to be done on arm64 arch side (but I may have misunderstood what Mark R. said elsewhere). And yes, then there is a question of objtool. It is one option but not the only one. There have been proposals of implementing guarantees on a compiler side and leaving objtool forx86_64only (albeit objtool may bring more features to the table... ORC, arch features checking).
Quoted 6 lines
Madhavan also mentioned that he enhanced objtool and he planned to submit it eventually
(https://lore.kernel.org/all/[email protected]/T/#u),
so maybe arm64 maintainers could decide on a future direction based on that?
Yes. I am working on that right now. Hope to send it out soon.
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Mark BrownQuoted 8 lines · Mark Brown
Quoted 5 lines · Madhavan T. Venkataraman
It is just that patch 11 that defines "select
HAVE_RELIABLE_STACKTRACE" did not receive any comments from you (unless I missed a comment that came from you. That is entirely possible. If I missed it, my bad). Since you suggested that change, I just wanted to make sure that that patch looks OK to you.
Quoted 8 lines
I think that's more a question for the livepatch people to be honest - it's not entirely a technical one, there's a bunch of confidence level stuff going on. For example there was some suggestion that people might insist on having objtool support, though there's also substantial pushback on making objtool a requirement for anything from other quarters. I was hoping that posting that patch would provoke some discussion about what exactly is needed but that's not happened thus far.
That patch has HAVE_RELIABLE_STACKTRACE depending on STACK_VALIDATION, which doesn't exist on arm64.
So it didn't seem controversial enough to warrant discussion ;-)
Signature · 1 line
Josh
Mark Rutland
reviewerRe: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Madhavan T. VenkataramanQuoted 3 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Sorry, I was expecting a new version with some of my comments addressed, in case that had effects on subsequent patches.
Quoted 2 lines
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
I would very much like to upstream the ones I have given a Reviewed-by.
Given those were conditional on some adjustments (e.g. actually filling out comments), do you mind if I pick those into a series now?
Then, once that's picked, you can rebase the rest atop, and we can review that.
Thanks,
Mark.
Quoted 52 lines · Mark Rutland
Quoted 51 lines · On Mon, Jan 17, 2022 at 08:56:03AM -0600, [email protected] wrote:
Quoted 7 lines
From: "Madhavan T. Venkataraman" <[email protected]>
Rename the arguments to
unwind()for better consistency. Also, use the typedefstack_trace_consume_fnfor theconsume_entryfunction as it is already defined inlinux/stacktrace.h.Signed-off-by Madhavan T. Venkataraman <[email protected]>How about:
| arm64: align with common stracktrace naming | | For historical reasons, the naming of parameters and their types in the arm64 | stacktrace code differs from that used in generic code and other | architectures, even though the types are equivalent. | | For consistency and clarity, use the generic names.Either way:
Reviewed-by Mark Rutland <[email protected]>Mark.
Quoted 26 lines
--- arch/arm64/kernel/stacktrace.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)arch/arm64/kernel/stacktrace.c +2
-2@@ -181,12 +181,12 @@ static int notrace unwind_next(struct unwind_state *state)NOKPROBE_SYMBOL (unwind_next); static void notrace unwind(struct unwind_state *state, -bool (*fn)(void *,unsigned long ),void *data) +stack_trace_consume_fn consume_entry,void *cookie) {while (1 ) {int ret; -if (!fn (data, state->pc)) +if (!consume_entry (cookie, state->pc))break ; ret =unwind_next (state);if (ret <0 )Signature · 1 line
2.25.1
Mark Rutland
reviewerRe: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 8 lines · Mark Rutland
Quoted 3 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Sorry, I was expecting a new version with some of my comments addressed, in case that had effects on subsequent patches.
Quoted 7 lines
Quoted 2 lines
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
I would very much like to upstream the ones I have given a Reviewed-by.
Given those were conditional on some adjustments (e.g. actually filling out comments), do you mind if I pick those into a series now?
FWIW, I've picked up the set I'm trivially happy with, rebased that on v5.18-rc1, and put that on a branch with a couple of other cleanups:
https://git.kernel.org/pub/scm/linux/kernel/git/mark/linux.git/log/?h=arm64/stacktrace/cleanups
I'll send that out on Monday if there are no objections.
Thanks,
Mark.
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
Quoted 20 lines · Mark Rutland
Quoted 8 lines · Mark Rutland
Quoted 3 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Sorry, I was expecting a new version with some of my comments addressed, in case that had effects on subsequent patches.
Quoted 7 lines
Quoted 2 lines
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
I would very much like to upstream the ones I have given a Reviewed-by.
Given those were conditional on some adjustments (e.g. actually filling out comments), do you mind if I pick those into a series now?
FWIW, I've picked up the set I'm trivially happy with, rebased that on v5.18-rc1, and put that on a branch with a couple of other cleanups:
Quoted 6 lines
https://git.kernel.org/pub/scm/linux/kernel/git/mark/linux.git/log/?h=arm64/stacktrace/cleanups
I'll send that out on Monday if there are no objections.
Thanks,
Mark.
LGTM.
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Mark RutlandQuoted 8 lines · Mark Rutland
Quoted 3 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Sorry, I was expecting a new version with some of my comments addressed, in case that had effects on subsequent patches.
Yes. I realized that. I am actually working on the next version addressing the comments I have received.
Quoted 11 lines
Quoted 2 lines
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
I would very much like to upstream the ones I have given a Reviewed-by.
Given those were conditional on some adjustments (e.g. actually filling out comments), do you mind if I pick those into a series now?
Then, once that's picked, you can rebase the rest atop, and we can review that.
That would be great! Thanks!
Madhavan
Re: [PATCH v13 06/11] arm64: Use stack_trace_consume_fn and rename args to unwind()
In reply to Mark RutlandQuoted 11 lines · Mark Rutland
Quoted 3 lines · Madhavan T. Venkataraman
Hey Mark Rutland, Mark Brown,
Could you please review the rest of the patches in the series when you can?
Sorry, I was expecting a new version with some of my comments addressed, in case that had effects on subsequent patches.
Quoted 2 lines
Also, many of the patches have received a Reviewed-By from you both. So, after I send the next version out, can we upstream those ones?
Quoted 8 lines
I would very much like to upstream the ones I have given a Reviewed-by.
Given those were conditional on some adjustments (e.g. actually filling out comments), do you mind if I pick those into a series now?
Then, once that's picked, you can rebase the rest atop, and we can review that.
So, do you want me to address the comments so far and send the next version? I can do it ASAP.
Madhavan
PATCH v13 7/11 arm64: Make the unwind loop in unwind() similar to other architectures
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Change the loop in unwind()
===========================
Change the unwind loop in unwind() to:
while (unwind_continue(state, consume_entry, cookie)) unwind_next(state);
This is easy to understand and maintain.
New function unwind_continue()
==============================
Define a new function unwind_continue() that is used in the unwind loop to check for conditions that terminate a stack trace.
The conditions checked are:
- If the bottom of the stack (final frame) has been reached, terminate.
- If the consume_entry() function returns false, the caller of unwind has asked to terminate the stack trace. So, terminate.
- If unwind_next() failed for some reason (like stack corruption), terminate.
Do not return an error value from unwind_next()
===============================================
We want to check for terminating conditions only in unwind_continue() from the unwinder loop. So, do not return an error value from unwind_next(). Simply set a flag in unwind_state and check the flag in unwind_continue().
Final FP
========
Introduce a new field "final_fp" in "struct unwind_state". Initialize this to the final frame of the stack trace:
task_pt_regs(task)->stackframe
This is where the stacktrace must terminate if it is successful. Add an explicit comment to that effect.
--- arch/arm64/include/asm/stacktrace.h | 6 +++ arch/arm64/kernel/stacktrace.c | 72 ++++++++++++++++++----------- 2 files changed, 52 insertions(+), 26 deletions(-)
arch/arm64/include/asm/stacktrace.h +6 -0
@@ -53,6 +53,10 @@ struct stack_info {* value. * * @task: Pointer to the task structure. +* +* @final_fp Pointer to the final frame. +* +* @failed: Unwind failed. */ struct unwind_state {unsigned long fp;
@@ -64,6 +68,8 @@ struct unwind_state {struct llist_node *kr_cur;#endif struct task_struct *task; +unsigned long final_fp; +bool failed; }; extern void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,
arch/arm64/kernel/stacktrace.c +46 -26
121 lines not on this page · raw message
Signature · 1 line
2.25.1
PATCH v13 8/11 arm64: Introduce stack trace reliability checks in the unwinder
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
There are some kernel features and conditions that make a stack trace unreliable. Callers may require the unwinder to detect these cases. E.g., livepatch.
Introduce a new function called unwind_check_reliability() that will detect these cases and set a flag in the stack frame. Call unwind_check_reliability() for every frame in unwind().
Introduce the first reliability check in unwind_check_reliability() - If a return PC is not a valid kernel text address, consider the stack trace unreliable. It could be some generated code. Other reliability checks will be added in the future.
Let unwind() return a boolean to indicate if the stack trace is reliable.
--- arch/arm64/include/asm/stacktrace.h | 3 +++ arch/arm64/kernel/stacktrace.c | 28 ++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-)
arch/arm64/include/asm/stacktrace.h +3 -0
@@ -57,6 +57,8 @@ struct stack_info {* @final_fp Pointer to the final frame. * * @failed: Unwind failed. +* +* @reliable: Stack trace is reliable. */ struct unwind_state {unsigned long fp;
@@ -70,6 +72,7 @@ struct unwind_state {struct task_struct *task;unsigned long final_fp;bool failed; +bool reliable; }; extern void dump_backtrace(struct pt_regs *regs, struct task_struct *tsk,
arch/arm64/kernel/stacktrace.c +26 -2
@@ -18,6 +18,25 @@#include <asm/stack_pointer.h> #include <asm/stacktrace.h> +/* +* Check the stack frame for conditions that make further unwinding unreliable. +*/ +static void unwind_check_reliability (struct unwind_state *state) +{ +if (state->fp == state->final_fp) { +/* Final frame; no more unwind, no need to check reliability */ +return ; + } + +/* +* If the PC is not a known kernel text address, then we cannot +* be sure that a subsequent unwind will be reliable, as we +* don't know that the code follows our unwind requirements. +*/ +if (!__kernel_text_address (state->pc)) + state->reliable = false; +} +/* * AArch64 PCS assigns the frame pointer to x29. *
@@ -54,6 +73,7 @@ static void unwind_init_common(struct unwind_state *state, state->prev_fp =0 ; state->prev_type =STACK_TYPE_UNKNOWN ; state->failed = false; + state->reliable = true;/* Stack trace terminates here. */ state->final_fp = (unsigned long )task_pt_regs (task)->stackframe;
@@ -207,11 +227,15 @@ static void notrace unwind_next(struct unwind_state *state) }NOKPROBE_SYMBOL (unwind_next); -static void notrace unwind(struct unwind_state *state, +static bool notrace unwind(struct unwind_state *state,stack_trace_consume_fn consume_entry,void *cookie) { -while (unwind_continue (state, consume_entry, cookie)) +unwind_check_reliability (state); +while (unwind_continue (state, consume_entry, cookie)) {unwind_next (state); +unwind_check_reliability (state); + } +return !state->failed && state->reliable; }NOKPROBE_SYMBOL (unwind);
Signature · 1 line
2.25.1
PATCH v13 9/11 arm64: Create a list of SYM_CODE functions, check return PC against list
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
SYM_CODE functions don't follow the usual calling conventions. Check if the return PC in a stack frame falls in any of these. If it does, consider the stack trace unreliable.
Define a special section for unreliable functions
=================================================
Define a SYM_CODE_END() macro for arm64 that adds the function address range to a new section called "sym_code_functions".
Linker file
===========
Include the "sym_code_functions" section under read-only data in vmlinux.lds.S.
Initialization
==============
Define an early_initcall() to create a sym_code_functions[] array from the linker data.
Unwinder check
==============
Add a reliability check in unwind_check_reliability() that compares a return PC with sym_code_functions[]. If there is a match, then return failure.
--- arch/arm64/include/asm/linkage.h | 12 +++++++ arch/arm64/include/asm/sections.h | 1 + arch/arm64/kernel/stacktrace.c | 55 +++++++++++++++++++++++++++++++ arch/arm64/kernel/vmlinux.lds.S | 10 ++++++ 4 files changed, 78 insertions(+)
arch/arm64/include/asm/linkage.h +12 -0
@@ -63,4 +63,16 @@SYM_FUNC_END_ALIAS (x); \ SYM_FUNC_END_ALIAS(__pi_##x) +/* +* Record the address range of each SYM_CODE function in a struct code_range +* in a special section. +*/ +#define SYM_CODE_END (name) \ + SYM_END(name, SYM_T_NONE) ;\ + 99: ;\ + .pushsection "sym_code_functions", "aw" ;\ + .quad name ;\ + .quad 99b ;\ + .popsection +#endif
arch/arm64/include/asm/sections.h +1 -0
@@ -22,5 +22,6 @@ extern char __irqentry_text_start[], __irqentry_text_end[];extern char __mmuoff_data_start[], __mmuoff_data_end[];extern char __entry_tramp_text_start[], __entry_tramp_text_end[];extern char __relocate_new_kernel_start[], __relocate_new_kernel_end[]; +extern char __sym_code_functions_start[], __sym_code_functions_end[];#endif /* __ASM_SECTIONS_H */
arch/arm64/kernel/stacktrace.c +55 -0
72 lines not on this page · raw message
arch/arm64/kernel/vmlinux.lds.S +10 -0
@@ -122,6 +122,14 @@ jiffies = jiffies_64; #define TRAMP_TEXT #endif +#define SYM_CODE_FUNCTIONS \ + . = ALIGN(16); \ + .symcode : AT(ADDR(.symcode) - LOAD_OFFSET) { \ + __sym_code_functions_start = .; \ + KEEP(*(sym_code_functions)) \ + __sym_code_functions_end = .; \ + } + /* * The size of the PE/COFF section that covers the kernel image, which * runs from _stext to _edata, must be a round multiple of the PE/COFF
@@ -209,6 +217,8 @@ SECTIONS swapper_pg_dir = .; . += PAGE_SIZE; + SYM_CODE_FUNCTIONS + . = ALIGN(SEGMENT_ALIGN); __init_begin = .; __inittext_begin = .;
Signature · 1 line
2.25.1
PATCH v13 10/11 arm64: Introduce arch_stack_walk_reliable()
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Introduce arch_stack_walk_reliable() for ARM64. This works like arch_stack_walk() except that it returns -EINVAL if the stack trace is not reliable.
Until all the reliability checks are in place, arch_stack_walk_reliable() may not be used by livepatch. But it may be used by debug and test code.
--- arch/arm64/kernel/stacktrace.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)
arch/arm64/kernel/stacktrace.c +22 -0
@@ -342,3 +342,25 @@ noinline notrace void arch_stack_walk(stack_trace_consume_fn consume_entry,unwind (&state, consume_entry, cookie); } + +/* +* arch_stack_walk_reliable() may not be used for livepatch until all of +* the reliability checks are in place in unwind_consume(). However, +* debug and test code can choose to use it even if all the checks are not +* in place. +*/ +noinline int notrace arch_stack_walk_reliable(stack_trace_consume_fn consume_fn, +void *cookie, +struct task_struct *task) +{ +struct unwind_state state; +bool reliable; + +if (task == current) +unwind_init_from_current (&state, task); +else +unwind_init_from_task (&state, task); + + reliable =unwind (&state, consume_fn, cookie); +return reliable ?0 : -EINVAL ; +}
Signature · 1 line
2.25.1
PATCH v13 11/11 arm64: Select HAVE_RELIABLE_STACKTRACE
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Select HAVE_RELIABLE_STACKTRACE in arm64/Kconfig to allow arch_stack_walk_reliable() to be used.
Note that this is conditional upon STACK_VALIDATION which will be added when frame pointer validation is implemented (say via objtool).
--- arch/arm64/Kconfig | 1 + 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +1 -0
@@ -223,6 +223,7 @@ config ARM64 select THREAD_INFO_IN_TASK select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT + select HAVE_RELIABLE_STACKTRACE if FRAME_POINTER && STACK_VALIDATION help ARM 64-bit (AArch64) Linux support.
Signature · 1 line
2.25.1
RE: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
Hi Madhavan,
Quoted 5 lines
Select
HAVE_RELIABLE_STACKTRACEin arm64/Kconfig to allowarch_stack_walk_reliable()to be used.Note that this is conditional upon
STACK_VALIDATIONwhich will be added when frame pointer validation is implemented (say via objtool).
I know that Julien Thierry published objtool support for arm64 [1], but I'm not sure if it has been updated. Could you tell me other threads if you know?
[1] https://lore.kernel.org/linux-arm-kernel/[email protected]/
Thanks,
Keiya
Quoted 18 lines
Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/Kconfig | 1 + 1 file changed, 1 insertion(+)arch/arm64/Kconfig +1
-1@@ -223,6 +223,7 @@ config ARM64 select THREAD_INFO_IN_TASK select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT + select HAVE_RELIABLE_STACKTRACE if FRAME_POINTER && STACK_VALIDATION help ARM 64-bit (AArch64) Linux support. --
Quoted 1 line
2.25.1
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
I have not seen any activity on that in a long time. IIRC, Julien quit RedHat. I don't know if anyone else has taken over this work in RedHat.
Sorry, I don't have any more information.
Madhavan
Quoted 34 lines · On 1/24/22 23:21, [email protected] wrote:
Hi Madhavan,
Quoted 5 lines
Select
HAVE_RELIABLE_STACKTRACEin arm64/Kconfig to allowarch_stack_walk_reliable()to be used.Note that this is conditional upon
STACK_VALIDATIONwhich will be added when frame pointer validation is implemented (say via objtool).I know that Julien Thierry published objtool support for arm64 [1], but I'm not sure if it has been updated. Could you tell me other threads if you know?
[1] https://lore.kernel.org/linux-arm-kernel/[email protected]/
Thanks,
KeiyaQuoted 17 lines
Signed-off-by Madhavan T. Venkataraman <[email protected]>--- arch/arm64/Kconfig | 1 + 1 file changed, 1 insertion(+)arch/arm64/Kconfig +1
-0@@ -223,6 +223,7 @@ config ARM64 select THREAD_INFO_IN_TASK select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT + select HAVE_RELIABLE_STACKTRACE if FRAME_POINTER && STACK_VALIDATION help ARM 64-bit (AArch64) Linux support.
Quoted 8 lines
Quoted 2 lines
--
2.25.1_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RE: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
Quoted 6 lines
I have not seen any activity on that in a long time. IIRC, Julien quit RedHat. I don't know if anyone else has taken over this work in RedHat.
Sorry, I don't have any more information.
Madhavan
Thanks for your information.
By the way, I'm considering test code for arch_stack_walk_reliable(). Specifically, I apply Suraj's patch to enable livepatch, and added a function that sleeps between SYM_CODE_START and SYM_CODE_END, then livepatch checks if the task has an unreliable stack.
For now my internal test code working correctly, but my Kconfig excludes STACK_VALIDATION dependency.
It seems that objtool will not be enabled yet, so I would like to test it easier. If you are already testing with this patch, could you tell me how to do it?
Thanks,
Keiya
Quoted 49 lines · On 1/24/22 23:21, [email protected] wrote:
Quoted 47 lines
Hi Madhavan,
Quoted 5 lines
Select
HAVE_RELIABLE_STACKTRACEin arm64/Kconfig to allowarch_stack_walk_reliable()to be used.Note that this is conditional upon
STACK_VALIDATIONwhich will be added when frame pointer validation is implemented (say via objtool).I know that Julien Thierry published objtool support for arm64 [1],
but I'm not sure if it has been updated. Could you tell me other threads if you know?[1]
https://lore.kernel.org/linux-arm-kernel/20210303170932.1838634-1-jthi
[email protected]/Thanks,
KeiyaQuoted 21 lines
Signed-off-by: Madhavan T. Venkataraman
<[email protected]>--- arch/arm64/Kconfig | 1 + 1 file changed, 1 insertion(+)arch/arm64/Kconfig index renamed from arch/arm64/Kconfig +0
-0
f6e333b59314..bc7b3514b563100644arch/arm64/Kconfig +2
-1@@ -223,6 +223,7 @@ config ARM64 select THREAD_INFO_IN_TASK select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT + select HAVE_RELIABLE_STACKTRACE if FRAME_POINTER && +STACK_VALIDATION help ARM 64-bit (AArch64) Linux support. --Quoted 1 line
2.25.1
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
Quoted 16 lines · On 1/26/22 04:20, [email protected] wrote:
Quoted 6 lines
I have not seen any activity on that in a long time. IIRC, Julien quit RedHat. I don't know if anyone else has taken over this work in RedHat.
Sorry, I don't have any more information.
Madhavan
Thanks for your information.
By the way, I'm considering test code for
arch_stack_walk_reliable(). Specifically, I apply Suraj's patch to enable livepatch, and added a function that sleeps betweenSYM_CODE_STARTandSYM_CODE_END, then livepatch checks if the task has an unreliable stack.
For now my internal test code working correctly, but myKconfigexcludesSTACK_VALIDATIONdependency.
Quoted 4 lines
It seems that objtool will not be enabled yet, so I would like to test it easier. If you are already testing with this patch, could you tell me how to do it?
For now, I have an instrumented kernel that directly invokes arch_stack_walk_reliable() from various places in the kernel (interrupt handlers, exception handlers, ftrace entry, kprobe handler, etc). I also have a test driver to induce conditions like null pointer dereference. I use this to test different cases where arch_stack_walk_reliable() should return an error.
As for livepatch testing, I have enhanced objtool and the kernel so the frame pointer can be validated dynamically rather than statically. I have tested various different livepatch selftests successfully. I have also written my own livepatch tests to add to the selftests. I am currently working on preparing an RFC patch series for review. Basically, this series implements STACK_VALIDATION in a different way.
I plan to publish my work soon (hopefully Feb 2022). I was going to do in December. However, my workload in Microsoft did not permit me to do that. I am also planning to set up a github repo so people can try out my changes, if they are interested.
So, stay tuned.
Madhavan
RE: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
Quoted 21 lines
Quoted 16 lines
Quoted 6 lines
I have not seen any activity on that in a long time. IIRC, Julien quit RedHat. I don't know if anyone else has taken over this work in RedHat.
Sorry, I don't have any more information.
Madhavan
Thanks for your information.
By the way, I'm considering test code for
arch_stack_walk_reliable(). Specifically, I apply Suraj's patch to enable livepatch, and added a function that sleeps betweenSYM_CODE_STARTandSYM_CODE_END, then livepatch checks if the task has an unreliable stack.
For now my internal test code working correctly, but myKconfigexcludesSTACK_VALIDATIONdependency.Quoted 4 lines
It seems that objtool will not be enabled yet, so I would like to test it easier. If you are already testing with this patch, could you tell me how to do it?
Quoted 5 lines
For now, I have an instrumented kernel that directly invokes
arch_stack_walk_reliable()from various places in the kernel (interrupt handlers, exception handlers, ftrace entry, kprobe handler, etc). I also have a test driver to induce conditions like null pointer dereference. I use this to test different cases wherearch_stack_walk_reliable()should return an error.
That's good to know, thanks.
Quoted 7 lines
As for livepatch testing, I have enhanced objtool and the kernel so the frame pointer can be validated dynamically rather than statically. I have tested various different livepatch selftests successfully. I have also written my own livepatch tests to add to the selftests. I am currently working on preparing an RFC patch series for review. Basically, this series implements
STACK_VALIDATIONin a different way.
Quoted 7 lines
I plan to publish my work soon (hopefully Feb 2022). I was going to do in December. However, my workload in Microsoft did not permit me to do that. I am also planning to set up a github repo so people can try out my changes, if they are interested.
So, stay tuned.
Madhavan
I'm very interested, so I would to be happy if you could tell me when the github repo is set up.
Thanks again,
Keiya
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [PATCH v13 11/11] arm64: Select HAVE_RELIABLE_STACKTRACE
In reply to [email protected]Quoted 2 lines · On Tue, Jan 25, 2022 at 05:21:27AM +0000, [email protected] wrote:
I know that Julien Thierry published objtool support for arm64 [1], but I'm not sure if it has been updated. Could you tell me other threads if you know?
I've not heard of anyone else picking that up.
cover arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to a message not in the archiveFrom: "Madhavan T. Venkataraman" <[email protected]>
Introduction
============
The livepatch feature requires an unwinder that can provide a reliable stack trace. General requirements for a reliable unwinder are described in this document from Mark Rutland:
Documentation/livepatch/reliable-stacktrace.rst
The requirements have two parts:
1. The unwinder must be enhanced with certain features. E.g.,
- Identifying successful termination of stack trace
- Identifying unwindable and non-unwindable code
- Identifying interrupts and exceptions occurring in the frame pointer prolog and epilog
- Identifying features such as kretprobe and ftrace graph tracing that can modify the return address stored on the stack
- Identifying corrupted/unreliable stack contents
- Architecture-specific items that can render a stack trace unreliable at certain points in code
Some of these features are already in the arm64 unwinder. I am pursuing the rest in another patch series. This is work in progress. The latest submission as of this writing is here:
https://lore.kernel.org/linux-arm-kernel/[email protected]/T/#t
2. Validation of the frame pointer
This assumes that the unwinder is based on the frame pointer (FP). The actual frame pointer that the unwinder uses cannot just be assumed to be correct. It needs to be validated somehow.
This patch series is to address this requirement.
Validation of the FP (aka STACK_VALIDATION)
====================
The current approach in Linux is to use objtool, a build time tool, for this purpose. When configured, objtool is invoked on every relocatable object file during kernel build. It performs static analysis of the code in each file. It walks the instructions in every function and notes the changes to the stack pointer (SP) and the frame pointer (FP). It makes sure that the changes are in accordance with the ABI rules. Once objtool completes successfully, the kernel can then be used for livepatch purposes.
Objtool can have uses other than just FP validation. For instance, it can check control flow integrity during its analysis.
Problem
=======
Objtool is complex and highly architecture-dependent. It presents a great challenge to support livepatch on an architecture. We need an alternative solution for livepatch, preferably one that is largely architecture independent.
A different approach
====================
I would like to propose a different approach for FP validation - one that is simpler as well as architecture-independent for the most part. This initial work is for arm64. But it can easily be extended to other architectures.
In this approach, objtool is used to generate data for the unwinder. The unwinder uses the data during a stack trace to validate the FP in each frame. In other words, the FP is validated dynamically and not statically at build time.
Background for the solution
===========================
DWARF is a debugging file format used by many compilers and debuggers to support source level debugging. One of the components of DWARF is the DWARF Call Frame Information (CFI). A special section called .debug_frame is generated by the compiler to contain CFI. CFI supplies all the rules required to compute the contents of every register at every instruction address. A complete unwinder can be built from CFI.
However, DWARF is complex and building a complete unwinder from DWARF CFI is a ship that has already sailed. That is not the purpose of this patch series.
The solution
============
The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Objtool can be invoked as follows:
objtool dwarf generate <object-file>
The version of the DWARF standard supported in this work is version 4. The official documentation for this version is here:
https://dwarfstd.org/doc/DWARF4.pdf
Section 6.4 contains the description of the CFI.
Register rules in CFI
=====================
CFI defines the Canonical Frame Address (CFA) as the value of the stack pointer (SP) when a call instruction is executed. For the called function, register values are expressed relative to the CFA.
DWARF CFI defines the following rules to obtain the value of a register in the previous frame, given a current frame:
1. Same_Value:
The current and previous values of the register are the same.
2. Val_Offset(N):
The previous value is (CFA + N) where N is a signed offset.
3. Offset(N):
The previous value is saved at (CFA + N).
4. register(R):
The previous value is saved in register R.
5. Val_Expression(E):
The previous value is the value produced by evaluating a given DWARF expression. DWARF expressions are evaluated on a stack. That is, operands are pushed and popped on a stack, DWARF operators are applied on them and the result is obtained.
6. Expression(E):
The previous value is stored at the address computed from a DWARF expression.
7. Architectural:
The previous value is obtained in an architecture-specific way via an architecture-specific "augmentor". Augmentors are vendor specific and are not part of the DWARF standard.
The minimum CFI needed for this work
====================================
Fortunately, gcc and clang only generate rules (1), (2) and (3) for the SP, FP and return address (RA). So, this implementation only supports these 3 rules. These are very simple rules. At the time of this writing, these rules are found to be sufficient for ARM, ARM64 and RISCV.
As an exercise, I also ran my CFI parser on X64. For a very small percentage of the functions, DWARF expressions are indeed used. Of course, X64 already has a complete objtool-based static stack validation scheme. So, X64 does not need this.
I have not checked other architectures so far.
Compact encoding of CFI
=======================
The CFI is defined in a very generic format to allow all of the above rules to be defined. Since this work uses only a minimal subset of the rules, the supported CFI rules can be encoded in a more compact format. Also, this subset of the rules can be statically evaluated at build time by objtool. The kernel does not have to do any CFI parsing.
Unsupported rules
=================
There are three main reasons why I chose not to support rules (4) thru (7).
- the compiler does not generate these for the SP, FP and RA for arm64. So, arm64 does not need them.
- They have complexity.
- Objtool may not be able to do all the work for rules (4) thru (7). The kernel may be required to evaluate expressions that involve dereferencing an address, getting the value stored in a register, etc.
That does not mean that they cannot be supported. But supporting them would increase the complexity. I strongly suggest that this work be used only for architectures where all of the parsing and record generation can be done in objtool at build time. The kernel part of the implementation should be kept simple.
How to deal with unsupported rules, if they are present?
========================================================
objtool does not generate any rule data for the code locations at which unsupported rules exist. When the unwinder tries to find a rule for any of these locations, it will not find any. Then, it will simply consider the code locations unreliable from an unwind perspective. The requirement for the unwinder is really that it must be able to identify reliable and unreliable code. It can still do this.
So, livepatch can be supported even on architectures where unsupported rules are generated by the compiler. It only means that the code ranges that contain those rules will be considered unreliable by the unwinder. If they occur in frequently used functions, then it is definitely a problem. If not, they may result in some retries during the livepatch process. But livepatch can still be done.
FP prolog, epilog and leaf functions
====================================
DWARF CFI rules allow objtool to recognize these cases. Objtool does not generate any rule data for a function unless the frame is completely setup. If an interrupt or an exception happens in code where the frame is not set up or not set up completely, the unwinder will not find the rules for such code. Automatically, the stack trace is considered unreliable as it should be.
Assembly functions
==================
DWARF CFI is generated by the compiler only for C functions. This means that the unwinder will not find any rules for assembly code. So, assembly functions are automatically considered unreliable from an unwind perspective.
For assembly functions, DWARF annotations are defined that can be placed in assembly code. In that case, DWARF CFI can be generated for assembly functions as well. However, DWARF annotations are a PITA to maintain. So, this is not a good path to go down.
Now, there are certain points in assembly code that we would like to unwind through reliably. Like interrupt and exception handlers. This is mainly for getting reliable stack traces in these cases and reducing the number of retries during the livepatch process. For these, unwind hints can be placed at strategic points in assembly code. Only a small number of these hints should be needed.
In this work, I have defined the following unwind hints so stack traces that contain these can be done reliably:
- Exception handlers
- Interrupt handlers
- FTrace tracer functions
- FTrace graph return prepare code
- FTrace callsites
- Kretprobe Trampoline
Unwind hints are collected in a special section. Objtool converts unwind hints to rule data just like the CFI based ones. The kernel does not need special code to process unwind hints.
Generated code
==============
Generated code will not have any DWARF rules. Such code will be considered unreliable by the kernel.
Size of the memory consumed within the kernel for this feature
==============================================================
This depends on the amount of code in the kernel which, in turn, depends on the number of configs turned on. E.g., on the kernel on my arm64 system, the .debug_frame section generated by the compiler in vmlinux is about 3.42 MB. But the rule data generated by objtool for vmlinux is only about 1.06 MB.
Architecture-dependent part
===========================
The following architecture-dependent items must be supplied to support an architecture:
- Mapping from DWARF register numbers to actual registers. This is required only for the SP and FP (and RA, if the architecture defines an RA register).
- Relocation information for the special section created by objtool. Relocation types are processor-specific.
- Architecture-specific rule checking. For instance, the return address and the frame pointer are saved on adjacent locations on the stack for arm64. This is checked by an arm64-specific rule checker during CFI parsing.
The architecture dependent portion is very small.
Items like endianness and address size are already handled in generic code.
GitHub repository
=================
I have created a github repo to share my work. For each version I will create a branch. For version 1, it is here:
https://github.com/madvenka786/linux/tree/dwarftool_v1
Please feel free to clone and check it out. And, please let me know if you find any issues.
Testing
=======
I have run all of the livepatch selftests successfully. I have written a couple of extra selftests myself which I will be posting separately.
There is an open source utility called dwarfdump. It parses the CFI and produces ASCII output of the same. I have written a tool to extract that information and compare it with what my parser generates. The comparison is successful. So, the parser has been well tested.
I have extracted the same instruction addresses from vmlinux and fed them to the lookup function in the kernel that the unwinder uses. I have verified that the correct CFI rules are looked up for every single input address. So, the lookup function has been well tested.
TBD
===
- Objtool generates a table of instruction addresses or PCs for the kernel. These need to be sorted for doing an efficient binary search. Currently, the sorting is done in the kernel during boot. I will add support to the sorttable script so that the sorting can be done at build time.
- I need to perform more rigorous testing with different scenarios. This is work in progress. Any ideas or suggestions are welcome.
Madhavan T. Venkataraman (9):
objtool: Parse DWARF Call Frame Information in object files
objtool: Generate DWARF rules and place them in a special section
dwarf: Build the kernel with DWARF information
dwarf: Implement DWARF rule processing in the kernel
dwarf: Implement DWARF support for modules
arm64: unwinder: Add a reliability check in the unwinder based on
DWARF CFI
arm64: dwarf: Implement unwind hints
dwarf: Enable livepatch for ARM64
Suraj Jitindar Singh (1):
dwarf: Miscellaneous changes required for enabling livepatch
arch/Kconfig | 4 +- arch/arm64/Kconfig | 7 + arch/arm64/Kconfig.debug | 5 + arch/arm64/configs/defconfig | 1 + arch/arm64/include/asm/livepatch.h | 42 ++ arch/arm64/include/asm/sections.h | 4 + arch/arm64/include/asm/stacktrace.h | 9 + arch/arm64/include/asm/thread_info.h | 4 +- arch/arm64/include/asm/unwind_hints.h | 28 + arch/arm64/kernel/entry-ftrace.S | 23 + arch/arm64/kernel/entry.S | 3 + arch/arm64/kernel/ftrace.c | 16 + arch/arm64/kernel/probes/kprobes_trampoline.S | 2 + arch/arm64/kernel/signal.c | 4 + arch/arm64/kernel/stacktrace.c | 131 ++++ arch/arm64/kernel/vmlinux.lds.S | 22 + include/linux/dwarf.h | 90 +++ include/linux/ftrace.h | 4 + include/linux/module.h | 3 + kernel/Makefile | 1 + kernel/dwarf_fp.c | 305 ++++++++++ kernel/module.c | 31 + scripts/Makefile.build | 4 + scripts/link-vmlinux.sh | 6 + tools/include/linux/dwarf.h | 90 +++ tools/objtool/Build | 5 + tools/objtool/Makefile | 10 +- tools/objtool/arch/arm64/Build | 2 + tools/objtool/arch/arm64/dwarf_arch.c | 114 ++++ tools/objtool/arch/arm64/dwarf_clang.c | 53 ++ .../arch/arm64/include/arch/dwarf_reg.h | 17 + tools/objtool/builtin-dwarf.c | 75 +++ tools/objtool/dwarf_op.c | 560 ++++++++++++++++++ tools/objtool/dwarf_parse.c | 351 +++++++++++ tools/objtool/dwarf_rules.c | 265 +++++++++ tools/objtool/dwarf_util.c | 280 +++++++++ tools/objtool/elf.c | 2 +- tools/objtool/include/objtool/builtin.h | 1 + tools/objtool/include/objtool/dwarf_def.h | 460 ++++++++++++++ tools/objtool/include/objtool/elf.h | 1 + tools/objtool/include/objtool/objtool.h | 3 + tools/objtool/objtool.c | 1 + tools/objtool/sync-check.sh | 6 + tools/objtool/weak.c | 38 ++ 44 files changed, 3079 insertions(+), 4 deletions(-) create mode 100644 arch/arm64/include/asm/livepatch.h create mode 100644 arch/arm64/include/asm/unwind_hints.h create mode 100644 include/linux/dwarf.h create mode 100644 kernel/dwarf_fp.c create mode 100644 tools/include/linux/dwarf.h create mode 100644 tools/objtool/arch/arm64/Build create mode 100644 tools/objtool/arch/arm64/dwarf_arch.c create mode 100644 tools/objtool/arch/arm64/dwarf_clang.c create mode 100644 tools/objtool/arch/arm64/include/arch/dwarf_reg.h create mode 100644 tools/objtool/builtin-dwarf.c create mode 100644 tools/objtool/dwarf_op.c create mode 100644 tools/objtool/dwarf_parse.c create mode 100644 tools/objtool/dwarf_rules.c create mode 100644 tools/objtool/dwarf_util.c create mode 100644 tools/objtool/include/objtool/dwarf_def.h
base-commit: fc74e0a40e4f9fd0468e34045b0c45bba11dcbb2
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 1/9 objtool: Parse DWARF Call Frame Information in object files
From: "Madhavan T. Venkataraman" <[email protected]>
If CONFIG_DEBUG_INFO_DWARF* is enabled, the compiler generates DWARF Call Frame Information (CFI) for every object file and places it in a special section named ".debug_frame". The CFI information can be used for frame pointer validation.
Implement a CFI parser in objtool. This can be invoked as follows:
objtool dwarf generate <object-file>
The version of the DWARF standard supported in this work is version 4. The official documentation for this version is here:
https://dwarfstd.org/doc/DWARF4.pdf
Section 6.4 contains the description of the CFI.
Initial implementation
======================
This initial work is for supporting frame pointer validation for ARM64. That said, it is generic enough to support other architectures in the future.
CFI defines 7 different register rules to compute register values at every instruction address. These are described below. Of these, only the first 3 rules are generated by gcc and clang for the stack pointer (SP), the frame pointer (FP) and the return address (RA) for ARM64. As of this writing, the same is true for RISCV as well.
So, in objtool, provide support for the first three rules and mark the rest as unsupported.
Register rules
==============
CFI defines the Canonical Frame Address (CFA) as the value of the SP when a call instruction is executed. For the called function, other register values are expressed relative to the CFA.
CFI defines the following rules to obtain the value of a register in the previous frame, given a current frame:
1. Same_Value:
The current and previous values of the register are the same.
2. Val_Offset(N):
The previous value is (CFA + N) where N is a signed offset.
3. Offset(N):
The previous value is saved at (CFA + N).
4. register(R):
The previous value is saved in register R.
5. Val_Expression(E):
The previous value is the value produced by evaluating a given DWARF expression. DWARF expressions are evaluated on a stack. That is, operands are pushed and popped on a stack, DWARF operators are applied on them and the result is obtained.
6. Expression(E):
The previous value is stored at the address computed from a DWARF expression.
7. Architectural:
The previous value is obtained in an architecture-specific way via an architecture-specific "augmentor". Augmentors are vendor specific and are not part of the DWARF standard.
DWARF rule encoding
===================
The CFI is defined in a very generic format to allow all of the above rules to be defined for different architectures. Since this work uses only a minimal subset of the rules, the supported CFI rules can be encoded in a more compact format for the kernel.
Provide stubs for generating compact rule data from the CFI rules. In a future patch, the stubs will be filled with actual code and the rules will be written to a special section in the object file. And, in a future patch, the kernel will use the rule data.
Unsupported rules
=================
For arm64, this is not an issue. If the compiler generates unsupported rules for the SP, FP and RA for some other architecture, objtool will not generate any rule data for those code locations. These will be treated as unreliable PCs from an unwinder perspective.
FP prolog, epilog and leaf functions
====================================
This implementation recognizes these cases in the DWARF CFI. It does not generate any rule data unless the frame is completely setup. So, if an interrupt or an exception were to happen in the prolog, epilog or a function where the frame has not been set up for whatever reason, the kernel will recognize that and consider the code unreliable from an unwinder perspective.
Assembly functions
==================
DWARF CFI is generated by the compiler only for C functions. So, objtool will not generate any rule data for assembly functions. By default, the kernel will consider all assembly functions as unreliable from an unwinder perspective.
DWARF annotations for assembly code can be used so CFI can be generated for assembly functions as well. However, DWARF annotations are a pain to maintain. So, we should never go down that path.
Now, there are certain points in assembly code that we would like to unwind through reliably. Like interrupt and exception handlers. For these, unwind hints can be defined and placed at strategic points in assembly code. This will be done in a futurep patch. Unwind hints are a lot simpler and a lot easier to maintain than DWARF annotations.
Generated code
==============
Generated code will not have any DWARF rules. The kernel will consider such code unreliable from an unwinder perspective.
Architecture-specific part
===========================
The following pieces in this implementation are architecture-specific. Code must be provided for each architecture spearately.
- DWARF register number to architecture register mapping
- Relocation handling for rule data (relocation types are processor-specific)
- ABI-specific checking of rules parsed by objtool.
Only a small amount of architecture-specific code is required. Other aspects such as endianness and address size are handled in the generic code.
--- tools/objtool/Build | 5 + tools/objtool/Makefile | 10 +- tools/objtool/arch/arm64/Build | 2 + tools/objtool/arch/arm64/dwarf_arch.c | 114 ++++ tools/objtool/arch/arm64/dwarf_clang.c | 53 ++ .../arch/arm64/include/arch/dwarf_reg.h | 17 + tools/objtool/builtin-dwarf.c | 57 ++ tools/objtool/dwarf_op.c | 560 ++++++++++++++++++ tools/objtool/dwarf_parse.c | 294 +++++++++ tools/objtool/dwarf_rules.c | 37 ++ tools/objtool/dwarf_util.c | 280 +++++++++ tools/objtool/elf.c | 2 +- tools/objtool/include/objtool/builtin.h | 1 + tools/objtool/include/objtool/dwarf_def.h | 438 ++++++++++++++ tools/objtool/include/objtool/elf.h | 1 + tools/objtool/include/objtool/objtool.h | 1 + tools/objtool/objtool.c | 1 + tools/objtool/weak.c | 27 + 18 files changed, 1898 insertions(+), 2 deletions(-) create mode 100644 tools/objtool/arch/arm64/Build create mode 100644 tools/objtool/arch/arm64/dwarf_arch.c create mode 100644 tools/objtool/arch/arm64/dwarf_clang.c create mode 100644 tools/objtool/arch/arm64/include/arch/dwarf_reg.h create mode 100644 tools/objtool/builtin-dwarf.c create mode 100644 tools/objtool/dwarf_op.c create mode 100644 tools/objtool/dwarf_parse.c create mode 100644 tools/objtool/dwarf_rules.c create mode 100644 tools/objtool/dwarf_util.c create mode 100644 tools/objtool/include/objtool/dwarf_def.h
tools/objtool/Build +5 -0
@@ -7,9 +7,14 @@ objtool-$(SUBCMD_CHECK) += special.o objtool-$(SUBCMD_ORC) += check.o objtool-$(SUBCMD_ORC) += orc_gen.o objtool-$(SUBCMD_ORC) += orc_dump.o +objtool-$(SUBCMD_DWARF) += dwarf_parse.o +objtool-$(SUBCMD_DWARF) += dwarf_op.o +objtool-$(SUBCMD_DWARF) += dwarf_rules.o +objtool-$(SUBCMD_DWARF) += dwarf_util.o objtool-y += builtin-check.o objtool-y += builtin-orc.o +objtool-y += builtin-dwarf.o objtool-y += elf.o objtool-y += objtool.o
tools/objtool/Makefile +9 -1
@@ -41,13 +41,21 @@ AWK = awk SUBCMD_CHECK := n SUBCMD_ORC := n +SUBCMD_DWARF := n ifeq ($(SRCARCH),x86) SUBCMD_CHECK := y SUBCMD_ORC := y endif -export SUBCMD_CHECK SUBCMD_ORC +ifeq ($(SRCARCH),arm64) + SUBCMD_DWARF := y +ifneq ($(LLVM),) + SUBCMD_DWARF_CLANG := y +endif +endif + +export SUBCMD_CHECK SUBCMD_ORC SUBCMD_DWARF SUBCMD_DWARF_CLANG export srctree OUTPUT CFLAGS SRCARCH AWK include $(srctree)/tools/build/Makefile.include
tools/objtool/arch/arm64/Build new file +2 -0
@@ -0,0 +1,2 @@ +objtool-$(SUBCMD_DWARF) += dwarf_arch.o +objtool-$(SUBCMD_DWARF_CLANG) += dwarf_clang.o
tools/objtool/arch/arm64/dwarf_arch.c new file +114 -0
114 lines not on this page · raw message
tools/objtool/arch/arm64/dwarf_clang.c new file +53 -0
53 lines not on this page · raw message
tools/objtool/arch/arm64/include/arch/dwarf_reg.h new file +17 -0
@@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* dwarf_reg.h - DWARF register numbers for the stack pointer, frame pointer +* and return address. +* +* Author: Madhavan T. Venkataraman ([email protected]) +* +* Copyright (c) 2022 Microsoft Corporation +*/ +#ifndef _ARM64_ARCH_DWARF_REG_H +#define _ARM64_ARCH_DWARF_REG_H + +#define FP_REG 29 +#define RA_REG 30 +#define SP_REG 31 + +#endif /* _ARM64_ARCH_DWARF_REG_H */
tools/objtool/builtin-dwarf.c new file +57 -0
57 lines not on this page · raw message
tools/objtool/dwarf_op.c new file +560 -0
560 lines not on this page · raw message
tools/objtool/dwarf_parse.c new file +294 -0
294 lines not on this page · raw message
tools/objtool/dwarf_rules.c new file +37 -0
@@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* dwarf_rules.c - Allocation and management of DWARF rules. +* +* Author: Madhavan T. Venkataraman ([email protected]) +* +* Copyright (C) 2022 Microsoft Corporation +*/ +#include <stdio.h> + +#include <objtool/objtool.h> +#include <objtool/warn.h> +#include <objtool/dwarf_def.h> +#include <linux/compiler.h> + +/* +* The following are stubs for now. Later, they will be filled to create +* DWARF rules that the kernel can use to compute the frame pointer at +* a given instruction address. +*/ +void dwarf_rule_start (struct fde *fde) +{ +} + +int dwarf_rule_add (struct fde *fde,unsigned long addr, +struct rule *sp_rule,struct rule *fp_rule) +{ +return 0 ; +} + +void dwarf_rule_next (struct fde *fde,unsigned long addr) +{ +} + +void dwarf_rule_reset (struct fde *fde) +{ +}
tools/objtool/dwarf_util.c new file +280 -0
280 lines not on this page · raw message
tools/objtool/elf.c +1 -1
@@ -108,7 +108,7 @@ static struct section *find_section_by_index(struct elf *elf,return NULL ; } -static struct symbol *find_symbol_by_index (struct elf *elf,unsigned int idx) +struct symbol *find_symbol_by_index (struct elf *elf,unsigned int idx) {struct symbol *sym;
tools/objtool/include/objtool/builtin.h +1 -0
@@ -15,5 +15,6 @@ extern int cmd_parse_options(int argc, const char **argv, const char * const usaextern int cmd_check (int argc,const char **argv);extern int cmd_orc (int argc,const char **argv); +extern int cmd_dwarf (int argc,const char **argv);#endif /* _BUILTIN_H */
tools/objtool/include/objtool/dwarf_def.h new file +438 -0
438 lines not on this page · raw message
tools/objtool/include/objtool/elf.h +1 -0
@@ -151,6 +151,7 @@ struct section *find_section_by_name(const struct elf *elf, const char *name);struct symbol *find_func_by_offset (struct section *sec,unsigned long offset);struct symbol *find_symbol_by_offset (struct section *sec,unsigned long offset);struct symbol *find_symbol_by_name (const struct elf *elf,const char *name); +struct symbol *find_symbol_by_index (struct elf *elf,unsigned int idx);struct symbol *find_symbol_containing (const struct section *sec,unsigned long offset);struct reloc *find_reloc_by_dest (const struct elf *elf,struct section *sec,unsigned long offset); struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
tools/objtool/include/objtool/objtool.h +1 -0
@@ -41,5 +41,6 @@ void objtool_pv_add(struct objtool_file *file, int idx, struct symbol *func);int check (struct objtool_file *file);int orc_dump (const char *objname);int orc_create (struct objtool_file *file); +int dwarf_parse (struct objtool_file *file);#endif /* _OBJTOOL_H */
tools/objtool/objtool.c +1 -0
@@ -38,6 +38,7 @@ static const char objtool_usage_string[] =static struct cmd_struct objtool_cmds[] = { {"check" , cmd_check,"Perform stack metadata validation on an object file" }, {"orc" , cmd_orc,"Generate in-place ORC unwind tables for an object file" }, + {"dwarf" , cmd_dwarf,"Generate DWARF rules for object file" }, };bool help;
tools/objtool/weak.c +27 -0
@@ -8,6 +8,7 @@#include <stdbool.h> #include <errno.h> #include <objtool/objtool.h> +#include <objtool/dwarf_def.h> #define UNSUPPORTED (name) \ ({ \
@@ -29,3 +30,29 @@ int __weak orc_create(struct objtool_file *file) {UNSUPPORTED ("orc" ); } + +int __weak dwarf_parse (struct objtool_file *file) + +{ +fprintf (stderr,"error: objtool: %s not implemented\n" , __func__); +return -EOPNOTSUPP ; +} + +int __weak arch_dwarf_fde_reloc (struct fde *fde) +{ +fprintf (stderr,"error: objtool: %s not implemented\n" , __func__); +return -EOPNOTSUPP ; +} + +void __weak arch_dwarf_clang_hack (struct fde *fde,unsigned long pc, +struct rule *sp_rule,struct rule *fp_rule) +{ +} + +int __weak arch_dwarf_check_rules (struct fde *fde,unsigned long pc, +struct rule *sp_rule,struct rule *fp_rule, +struct rule *ra_rule) +{ +fprintf (stderr,"error: objtool: %s not implemented\n" , __func__); +return -EOPNOTSUPP ; +}
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 2/9 objtool: Generate DWARF rules and place them in a special section
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Convert the DWARF Call Frame Information parsed by dwarf_parse() into compact DWARF rules that are usable by the kernel. Place the rules in a special section called .dwarf_rules. Also, place the PCs for the rules in a special section called .dwarf_pcs. In addition, define relocation entries for the PCs as they will change during linking.
An entry in .dwarf_rules and its corresponding entry in .dwarf_pcs together describe a code range and DWARF rules for the code range. In the future, the kernel will use the rules to compute the frame pointer at a given instruction address. The unwinder can use the computed frame pointer to validate the actual frame pointer for a reliable stack trace.
During rule generation, eliminate null offset rules and merge adjacent rules that are identical to minimize the number of rules.
Also add an objtool option to dump the DWARF rules for debugging purposes. It is invoked as follows:
objtool dwarf dump <object-file>
--- include/linux/dwarf.h | 43 +++++ tools/include/linux/dwarf.h | 43 +++++ tools/objtool/builtin-dwarf.c | 22 ++- tools/objtool/dwarf_rules.c | 181 +++++++++++++++++++++- tools/objtool/include/objtool/dwarf_def.h | 12 ++ tools/objtool/include/objtool/objtool.h | 2 + tools/objtool/sync-check.sh | 6 + tools/objtool/weak.c | 11 ++ 8 files changed, 311 insertions(+), 9 deletions(-) create mode 100644 include/linux/dwarf.h create mode 100644 tools/include/linux/dwarf.h
include/linux/dwarf.h new file +43 -0
@@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* dwarf.h - DWARF data structures used by the unwinder. +* +* Author: Madhavan T. Venkataraman ([email protected]) +* +* Copyright (c) 2022 Microsoft Corporation +*/ + +#ifndef _LINUX_DWARF_H +#define _LINUX_DWARF_H + +#include <linux/types.h> + +/* +* objtool generates two special sections that contain DWARF information that +* will be used by the reliable unwinder to validate the frame pointer in every +* frame: +* +* .dwarf_rules: +* This contains an array of struct dwarf_rule. Each rule contains the +* size of a code range. In addition, a rule contains the offsets that +* must be used to compute the frame pointer at any of the instructions +* within the code range. The computation is: +* +* CFA = %sp + sp_offset +* FP = CFA + fp_offset +* +* where %sp is the stack pointer at the instruction address and FP is +* the frame pointer. +* +* .dwarf_pcs: +* This contains an array of starting PCs, one for each rule. +*/ +struct dwarf_rule { +unsigned int size:30 ; +unsigned int sp_saved:1 ; +unsigned int fp_saved:1 ; +short sp_offset; +short fp_offset; +}; + +#endif /* _LINUX_DWARF_H */
tools/include/linux/dwarf.h new file +43 -0
43 lines not on this page · raw message
tools/objtool/builtin-dwarf.c +20 -2
@@ -25,6 +25,10 @@ static const char * const dwarf_usage[] = {* information. */ "objtool dwarf generate file" , +/* +* Dump DWARF rules for debugging purposes. +*/ +"objtool dwarf dump file" , NULL, };
@@ -37,6 +41,7 @@ int cmd_dwarf(int argc, const char **argv) {const char *object;struct objtool_file *file; +int ret; argc--; argv++;if (argc !=2 )
@@ -48,8 +53,21 @@ int cmd_dwarf(int argc, const char **argv)if (!file)return 1 ; -if (!strncmp (argv[0 ],"gen" ,3 )) -return dwarf_parse (file); +if (!strncmp (argv[0 ],"gen" ,3 )) { + ret =dwarf_parse (file); +if (!ret) + ret =dwarf_write (file); +if (!ret && file->elf->changed) + ret =elf_write (file->elf); +return ret; + } + +if (!strcmp (argv[0 ],"dump" )) { + ret =dwarf_parse (file); +if (!ret) +dwarf_dump (); +return ret; + }usage_with_options (dwarf_usage, dwarf_options);
tools/objtool/dwarf_rules.c +174 -7
199 lines not on this page · raw message
tools/objtool/include/objtool/dwarf_def.h +12 -0
@@ -10,6 +10,8 @@#ifndef _OBJTOOL_DWARF_DEF_H#define _OBJTOOL_DWARF_DEF_H +#include <linux/dwarf.h> +/* * The DWARF Call Frame Information (CFI) is encoded in a self-contained * section called .debug_frame.
@@ -228,6 +230,14 @@ struct cie {bool unusable; }; +struct fde_entry { +struct fde_entry *next; +unsigned long addr; +size_t size; +struct rule sp_rule; +struct rule fp_rule; +}; +/* * Frame Description Entry (FDE): *
@@ -290,6 +300,8 @@ struct fde {struct section *section;unsigned long offset;unsigned long sp_offset; +struct fde_entry *head; +struct fde_entry *tail; };/*
tools/objtool/include/objtool/objtool.h +2 -0
@@ -42,5 +42,7 @@ int check(struct objtool_file *file);int orc_dump (const char *objname);int orc_create (struct objtool_file *file);int dwarf_parse (struct objtool_file *file); +void dwarf_dump (void ); +int dwarf_write (struct objtool_file *file);#endif /* _OBJTOOL_H */
tools/objtool/sync-check.sh +6 -0
@@ -27,6 +27,12 @@ arch/x86/lib/insn.c ' fi +if [ "$SRCARCH" = "arm64" ]; then +FILES="$FILES +include/linux/dwarf.h +" +fi + check_2 () { file1=$1 file2=$2
tools/objtool/weak.c +11 -0
@@ -38,6 +38,17 @@ int __weak dwarf_parse(struct objtool_file *file)return -EOPNOTSUPP ; } +int __weak dwarf_write (struct objtool_file *file) +{ +fprintf (stderr,"error: objtool: %s not implemented\n" , __func__); +return -1 ; +} + +void __weak dwarf_dump (void ) +{ +fprintf (stderr,"error: objtool: %s not implemented\n" , __func__); +} +int __weak arch_dwarf_fde_reloc (struct fde *fde) {fprintf (stderr,"error: objtool: %s not implemented\n" , __func__);
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 3/9 dwarf: Build the kernel with DWARF information
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Define CONFIG_DWARF_FP - to include DWARF based FP validation code. Define CONFIG_STACK_VALIDATION - to enable DWARF based FP validation.
When these configs are enabled, invoke objtool on relocatable files during the kernel build with the following command:
objtool dwarf generate <object-file>
Objtool creates the following sections in each object file:
.dwarf_rules Array of DWARF rules
.dwarf_pcs Array of PCs, one-to-one with rules
In the future, the kernel can use these sections to find the rules for a given instruction address. The unwinder can then compute the FP at an instruction address and validate the actual FP with that.
NOTE: CONFIG_STACK_VALIDATION needs to be turned on here. Otherwise, objtool will not be invoked during the kernel build process. The actual stack validation code will be added separately. This is harmless.
--- arch/Kconfig | 4 +++- arch/arm64/Kconfig | 2 ++ arch/arm64/Kconfig.debug | 5 +++++ arch/arm64/configs/defconfig | 1 + arch/arm64/kernel/vmlinux.lds.S | 22 ++++++++++++++++++++++ scripts/Makefile.build | 4 ++++ scripts/link-vmlinux.sh | 6 ++++++ 7 files changed, 43 insertions(+), 1 deletion(-)
arch/Kconfig +3 -1
@@ -1016,7 +1016,9 @@ config HAVE_STACK_VALIDATION bool help Architecture supports the 'objtool check' host tool command, which - performs compile-time stack metadata validation. + performs compile-time stack metadata validation. Or, on architectures + that use DWARF validated frame pointers, it supports the + 'objtool dwarf generate' host tool command. config HAVE_RELIABLE_STACKTRACE bool
arch/arm64/Kconfig +2 -0
@@ -220,6 +220,8 @@ config ARM64 select SWIOTLB select SYSCTL_EXCEPTION_TRACE select THREAD_INFO_IN_TASK + select HAVE_STACK_VALIDATION if DWARF_FP + select STACK_VALIDATION if HAVE_STACK_VALIDATION select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT help
arch/arm64/Kconfig.debug +5 -0
@@ -20,4 +20,9 @@ config ARM64_RELOC_TEST depends on m tristate "Relocation testing module" +config DWARF_FP + def_bool y + depends on FRAME_POINTER + depends on DEBUG_INFO_DWARF4 + source "drivers/hwtracing/coresight/Kconfig"
arch/arm64/configs/defconfig +1 -0
@@ -1233,3 +1233,4 @@ CONFIG_DEBUG_KERNEL=y # CONFIG_DEBUG_PREEMPT is not set # CONFIG_FTRACE is not set CONFIG_MEMTEST=y +CONFIG_DEBUG_INFO_DWARF4=y
arch/arm64/kernel/vmlinux.lds.S +22 -0
@@ -122,6 +122,25 @@ jiffies = jiffies_64; #define TRAMP_TEXT #endif +#ifdef CONFIG_DWARF_FP +#define DWARF_RULES \ + . = ALIGN(8); \ + .dwarf_rules : { \ + __dwarf_rules_start = .; \ + KEEP(*(.dwarf_rules)) \ + __dwarf_rules_end = .; \ + } + +#define DWARF_PCS \ + . = ALIGN(8); \ + __dwarf_pcs_start = .; \ + KEEP(*(.dwarf_pcs)) \ + __dwarf_pcs_end = .; +#else +#define DWARF_RULES +#define DWARF_PCS +#endif + /* * The size of the PE/COFF section that covers the kernel image, which * runs from _stext to _edata, must be a round multiple of the PE/COFF
@@ -239,6 +258,7 @@ SECTIONS CON_INITCALL INIT_RAM_FS *(.init.altinstructions .init.bss) /* from the EFI stub */ + DWARF_PCS } .exit.data : { EXIT_DATA
@@ -291,6 +311,8 @@ SECTIONS __mmuoff_data_end = .; } + DWARF_RULES + PECOFF_EDATA_PADDING __pecoff_data_rawsize = ABSOLUTE(. - __initdata_begin); _edata = .;
scripts/Makefile.build +4 -0
@@ -227,6 +227,9 @@ ifdef CONFIG_STACK_VALIDATION objtool := $(objtree)/tools/objtool/objtool +ifdef CONFIG_DWARF_FP +objtool_args = dwarf generate +else objtool_args = \ $(if $(CONFIG_UNWINDER_ORC),orc generate,check) \ $(if $(part-of-module), --module) \
@@ -235,6 +238,7 @@ objtool_args = \ $(if $(CONFIG_RETPOLINE), --retpoline) \ $(if $(CONFIG_X86_SMAP), --uaccess) \ $(if $(CONFIG_FTRACE_MCOUNT_USE_OBJTOOL), --mcount) +endif cmd_objtool = $(if $(objtool-enabled), ; $(objtool) $(objtool_args) $@) cmd_gen_objtooldep = $(if $(objtool-enabled), { echo ; echo '$@: $$(wildcard $(objtool))' ; } >> $(dot-target).cmd)
scripts/link-vmlinux.sh +6 -0
@@ -104,6 +104,12 @@ objtool_link() local objtoolcmd; local objtoolopt; + if [ "${CONFIG_LTO_CLANG} ${CONFIG_DWARF_FP}" = "y y" ] + then + tools/objtool/objtool dwarf generate ${1} + return + fi + if [ "${CONFIG_LTO_CLANG} ${CONFIG_STACK_VALIDATION}" = "y y" ]; then # Don't perform vmlinux validation unless explicitly requested, # but run objtool on vmlinux.o now that we have an object file.
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 4/9 dwarf: Implement DWARF rule processing in the kernel
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Define a struct dwarf_info to store all of the DWARF information needed to lookup the DWARF rules for an instruction address. There is one dwarf_info for vmlinux and one for every module.
Implement a lookup function dwarf_lookup(). Given an instruction address, the function looks up the corresponding DWARF rules. The unwinder will use the lookup function in the future.
Sort the rules based on instruction address. This allows a binary search.
Divide the text range into fixed sized blocks and map the rules to their respective blocks. Given an instruction address, first locate the block for the address. Then, perform a binary search within the rules in the block. This minimizes the number of rules to consider in the binary search.
dwarf_info contains an array of PCs to search. In order to save space, store the PCs array as an array of offsets from the base PC of the text range. This way, we only need 32 bits to store the PC.
--- arch/arm64/include/asm/sections.h | 4 + include/linux/dwarf.h | 21 +++ kernel/Makefile | 1 + kernel/dwarf_fp.c | 244 ++++++++++++++++++++++++++++++ tools/include/linux/dwarf.h | 21 +++ 5 files changed, 291 insertions(+) create mode 100644 kernel/dwarf_fp.c
arch/arm64/include/asm/sections.h +4 -0
@@ -22,5 +22,9 @@ extern char __irqentry_text_start[], __irqentry_text_end[];extern char __mmuoff_data_start[], __mmuoff_data_end[];extern char __entry_tramp_text_start[], __entry_tramp_text_end[];extern char __relocate_new_kernel_start[], __relocate_new_kernel_end[]; +#ifdef CONFIG_DWARF_FP +extern char __dwarf_rules_start[], __dwarf_rules_end[]; +extern char __dwarf_pcs_start[], __dwarf_pcs_end[]; +#endif #endif /* __ASM_SECTIONS_H */
include/linux/dwarf.h +21 -0
@@ -40,4 +40,25 @@ struct dwarf_rule { short fp_offset; }; +/* +* The whole text area is divided into fixed sized blocks. Rules are mapped +* to their respective blocks. To find a block for an instruction address, +* the block of the address is located. Then, a binary search is performed +* on just the rules in the block. This minimizes the number of rules to +* be considered for the search. +*/ +struct dwarf_block { +int first_rule; +int last_rule; +}; + +#ifdef CONFIG_DWARF_FP +extern struct dwarf_rule *dwarf_lookup (unsigned long pc); +#else +static inline struct dwarf_rule *dwarf_lookup (unsigned long pc) +{ +return NULL ; +} +#endif +#endif /* _LINUX_DWARF_H */
kernel/Makefile +1 -0
@@ -130,6 +130,7 @@ obj-$(CONFIG_WATCH_QUEUE) += watch_queue.o obj-$(CONFIG_RESOURCE_KUNIT_TEST) += resource_kunit.o obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o +obj-$(CONFIG_DWARF_FP) += dwarf_fp.o CFLAGS_stackleak.o += $(DISABLE_STACKLEAK_PLUGIN) obj-$(CONFIG_GCC_PLUGIN_STACKLEAK) += stackleak.o
kernel/dwarf_fp.c new file +244 -0
244 lines not on this page · raw message
tools/include/linux/dwarf.h +21 -0
@@ -40,4 +40,25 @@ struct dwarf_rule { short fp_offset; }; +/* +* The whole text area is divided into fixed sized blocks. Rules are mapped +* to their respective blocks. To find a block for an instruction address, +* the block of the address is located. Then, a binary search is performed +* on just the rules in the block. This minimizes the number of rules to +* be considered for the search. +*/ +struct dwarf_block { +int first_rule; +int last_rule; +}; + +#ifdef CONFIG_DWARF_FP +extern struct dwarf_rule *dwarf_lookup (unsigned long pc); +#else +static inline struct dwarf_rule *dwarf_lookup (unsigned long pc) +{ +return NULL ; +} +#endif +#endif /* _LINUX_DWARF_H */
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 5/9 dwarf: Implement DWARF support for modules
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
When a module is loaded, allocate and initialize its struct dwarf_info. When a module is unloaded, free the same.
Add code in dwarf_lookup() to look up a given address in modules, if vmlinux does not contain the address.
--- include/linux/dwarf.h | 18 ++++++++++ include/linux/module.h | 3 ++ kernel/dwarf_fp.c | 71 ++++++++++++++++++++++++++++++++++--- kernel/module.c | 31 ++++++++++++++++ tools/include/linux/dwarf.h | 18 ++++++++++ 5 files changed, 136 insertions(+), 5 deletions(-)
include/linux/dwarf.h +18 -0
@@ -11,6 +11,7 @@#define _LINUX_DWARF_H#include <linux/types.h> +#include <linux/module.h> /* * objtool generates two special sections that contain DWARF information that
@@ -54,11 +55,28 @@ struct dwarf_block {#ifdef CONFIG_DWARF_FP extern struct dwarf_rule *dwarf_lookup (unsigned long pc); +#ifdef CONFIG_MODULES +extern void dwarf_module_alloc (struct module *mod, +struct dwarf_rule *rules,size_t rules_size, +unsigned long *pcs,size_t pcs_size); +extern void dwarf_module_free (struct module *mod); +#endif #else static inline struct dwarf_rule *dwarf_lookup (unsigned long pc) {return NULL ; } +#ifdef CONFIG_MODULES +static inline void dwarf_module_alloc (struct module *mod, +struct dwarf_rule *rules, +size_t rules_size, +unsigned long *pcs,size_t pcs_size) +{ +} +static inline void dwarf_module_free (struct module *mod) +{ +} +#endif #endif #endif /* _LINUX_DWARF_H */
include/linux/module.h +3 -0
@@ -538,6 +538,9 @@ struct module {struct error_injection_entry *ei_funcs;unsigned int num_ei_funcs;#endif +#ifdef CONFIG_DWARF_FP +void *dwarf_info; +#endif }____cacheline_aligned __randomize_layout;#ifndef MODULE_ARCH_INIT #define MODULE_ARCH_INIT {}
kernel/dwarf_fp.c +66 -5
85 lines not on this page · raw message
kernel/module.c +31 -0
@@ -59,6 +59,7 @@#include <linux/audit.h> #include <uapi/linux/module.h> #include "module-internal.h" +#include <linux/dwarf.h> #define CREATE_TRACE_POINTS #include <trace/events/module.h>
@@ -2153,6 +2154,7 @@ void __weak module_arch_freeing_init(struct module *mod) }static void cfi_cleanup (struct module *mod); +static void module_dwarf_free (struct module *mod);/* Free a module, remove from lists, etc. */ static void free_module (struct module *mod)
@@ -2175,6 +2177,9 @@ static void free_module(struct module *mod)/* Arch-specific cleanup. */ module_arch_cleanup (mod); +/* Dwarf cleanup. */ +module_dwarf_free (mod); +/* Module unload stuff */ module_unload_free (mod);
@@ -3946,6 +3951,7 @@ static int unknown_module_param_cb(char *param, char *val, const char *modname, }static void cfi_init (struct module *mod); +static void module_dwarf_init (struct module *mod,struct load_info *info);/* * Allocate and load the module: note that size of section 0 is always
@@ -4074,6 +4080,8 @@ static int load_module(struct load_info *info, const char __user *uargs,if (err <0 ) goto free_modinfo; +module_dwarf_init (mod, info); +flush_module_icache (mod);/* Setup CFI for the module. */
@@ -4154,6 +4162,7 @@ static int load_module(struct load_info *info, const char __user *uargs,kfree (mod->args); free_arch_cleanup:cfi_cleanup (mod); +module_dwarf_free (mod);module_arch_cleanup (mod); free_modinfo:free_modinfo (mod);
@@ -4542,6 +4551,28 @@ static void cfi_cleanup(struct module *mod)#endif } +static void module_dwarf_init (struct module *mod,struct load_info *info) +{ +Elf_Shdr *dwarf_rules, *dwarf_pcs; + + dwarf_rules = &info->sechdrs[find_sec (info,".dwarf_rules" )]; + dwarf_pcs = &info->sechdrs[find_sec (info,".dwarf_pcs" )]; + +if (!dwarf_rules || !dwarf_pcs) +return ; + +dwarf_module_alloc (mod, + (void *) dwarf_rules->sh_addr, + dwarf_rules->sh_size, + (void *) dwarf_pcs->sh_addr, + dwarf_pcs->sh_size); +} + +static void module_dwarf_free (struct module *mod) +{ +dwarf_module_free (mod); +} +/* Maximum number of characters written by module_flags() */ #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
tools/include/linux/dwarf.h +18 -0
@@ -11,6 +11,7 @@#define _LINUX_DWARF_H#include <linux/types.h> +#include <linux/module.h> /* * objtool generates two special sections that contain DWARF information that
@@ -54,11 +55,28 @@ struct dwarf_block {#ifdef CONFIG_DWARF_FP extern struct dwarf_rule *dwarf_lookup (unsigned long pc); +#ifdef CONFIG_MODULES +extern void dwarf_module_alloc (struct module *mod, +struct dwarf_rule *rules,size_t rules_size, +unsigned long *pcs,size_t pcs_size); +extern void dwarf_module_free (struct module *mod); +#endif #else static inline struct dwarf_rule *dwarf_lookup (unsigned long pc) {return NULL ; } +#ifdef CONFIG_MODULES +static inline void dwarf_module_alloc (struct module *mod, +struct dwarf_rule *rules, +size_t rules_size, +unsigned long *pcs,size_t pcs_size) +{ +} +static inline void dwarf_module_free (struct module *mod) +{ +} +#endif #endif #endif /* _LINUX_DWARF_H */
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 6/9 arm64: unwinder: Add a reliability check in the unwinder based on DWARF CFI
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Introduce a reliability flag in struct stackframe. This will be set to false if the PC does not have valid DWARF rules or if the frame pointer computed from the DWARF rules does not match the actual frame pointer.
Now that the unwinder can validate the frame pointer, introduce arch_stack_walk_reliable().
--- arch/arm64/include/asm/stacktrace.h | 6 +++ arch/arm64/kernel/stacktrace.c | 69 +++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+)
arch/arm64/include/asm/stacktrace.h +6 -0
@@ -5,6 +5,7 @@#ifndef __ASM_STACKTRACE_H#define __ASM_STACKTRACE_H +#include <linux/dwarf.h> #include <linux/percpu.h> #include <linux/sched.h> #include <linux/sched/task_stack.h>
@@ -35,6 +36,7 @@ struct stack_info {* A snapshot of a frame record or fp/lr register values, along with some * accounting information necessary for robust unwinding. * +* @sp: The sp value (CFA) at the call site of the current function. * @fp: The fp value in the frame record (or the real fp) * @pc: The lr value in the frame record (or the real lr) *
@@ -47,8 +49,11 @@ struct stack_info {* @prev_type: The type of stack this frame record was on, or a synthetic * value of STACK_TYPE_UNKNOWN. This is used to detect a * transition from one stack to another. +* +* @reliable Stack trace is reliable. */ struct stackframe { +unsigned long sp;unsigned long fp;unsigned long pc; DECLARE_BITMAP(stacks_done, __NR_STACK_TYPES);
@@ -57,6 +62,7 @@ struct stackframe {#ifdef CONFIG_KRETPROBES struct llist_node *kr_cur;#endif +bool reliable; };extern int unwind_frame (struct task_struct *tsk,struct stackframe *frame);
arch/arm64/kernel/stacktrace.c +69 -0
99 lines not on this page · raw message
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 7/9 arm64: dwarf: Implement unwind hints
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
DWARF information is not generated for assembly functions. However, we would like to unwind through some of these functions as they may occur frequently in a stacktrace. Implement unwind hints for this purpose.
An unwind hint placed after a desired call instruction creates a DWARF rule for that instruction address in a special section called ".discard.unwind_hints". objtool merges these DWARF rules along with the ones generated by the compiler for C functions.
Add unwind hints for the following cases:
Exception handlers
==================
When an exception is taken in the kernel, an exception frame gets pushed on the stack. To be able to unwind through the special frame, place an unwind hint in the exception handler macro.
Interrupt handlers
==================
When an interrupt happens, the exception handler switches to an IRQ stack and calls the interrupt handler. Place an unwind hint after the call to the interrupt handler so the unwinder can unwind through the switched stacks.
FTrace stub
===========
ftrace_common() calls ftrace_stub(). The stub is patched with tracer functions when tracing is enabled. Place an unwind hint right after the call to the stub function so that stack traces taken from within a tracer function can correctly unwind to the caller.
FTrace Graph Caller
===================
ftrace_graph_caller() calls a function, prepare_ftrace_return(), to prepare for graph tracing. Place an unwind hint after the call so a stack trace taken from within the prepare function can correctly unwind to the caller.
FTrace callsite
===============
ftrace_regs_entry() sets up two stackframes - one for the callsite and one for the ftrace entry code. Unwind hints have been placed for the ftrace entry code above. We need an unwind hint for the callsite. Callsites are numerous. But the unwind hint required for all the callsites is the same. Define a dummy function with the callsite unwind hint like this:
SYM_CODE_START(ftrace_callsite)
unwind_hint 4, 16, -16 // for the callsite
retSYM_CODE_END(ftrace_callsite)
When the unwinder comes across an ftrace entry, it will change the PC that it needs to lookup to ftrace_callsite() to obtain the unwind hint for the callsite like this:
#ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS if (is_ftrace_entry(frame->prev_pc)) lookup_pc = (unsigned long)&ftrace_callsite;
#endif
This way, the unwinder can unwind through an ftrace callsite.
Kretprobe Trampoline
====================
This trampoline sets up pt_regs on the stack and sets up a synthetic frame in the pt_regs. Place an unwind hint where trampoline_probe_handler() returns to __kretprobe_trampoline to unwind through the synthetic frame.
is_ftrace_entry()
=================
The code for this function has been borrowed from Suraj Jitindar Singh.
--- arch/arm64/include/asm/stacktrace.h | 3 + arch/arm64/include/asm/unwind_hints.h | 28 ++++++++ arch/arm64/kernel/entry-ftrace.S | 23 ++++++ arch/arm64/kernel/entry.S | 3 + arch/arm64/kernel/ftrace.c | 16 +++++ arch/arm64/kernel/probes/kprobes_trampoline.S | 2 + arch/arm64/kernel/stacktrace.c | 70 +++++++++++++++++-- include/linux/dwarf.h | 10 ++- include/linux/ftrace.h | 4 ++ tools/include/linux/dwarf.h | 10 ++- tools/objtool/dwarf_parse.c | 59 +++++++++++++++- tools/objtool/dwarf_rules.c | 65 ++++++++++++++++- tools/objtool/include/objtool/dwarf_def.h | 10 +++ 13 files changed, 294 insertions(+), 9 deletions(-) create mode 100644 arch/arm64/include/asm/unwind_hints.h
arch/arm64/include/asm/stacktrace.h +3 -0
@@ -46,6 +46,7 @@ struct stack_info {* @prev_fp: The fp that pointed to this frame record, or a synthetic value * of 0. This is used to ensure that within a stack, each * subsequent frame record is at an increasing address. +* @prev_pc: The pc in the previous frame. * @prev_type: The type of stack this frame record was on, or a synthetic * value of STACK_TYPE_UNKNOWN. This is used to detect a * transition from one stack to another.
@@ -58,11 +59,13 @@ struct stackframe {unsigned long pc;DECLARE_BITMAP (stacks_done, __NR_STACK_TYPES);unsigned long prev_fp; +unsigned long prev_pc;enum stack_type prev_type;#ifdef CONFIG_KRETPROBES struct llist_node *kr_cur;#endif bool reliable; +bool synthetic_frame; };extern int unwind_frame (struct task_struct *tsk,struct stackframe *frame);
arch/arm64/include/asm/unwind_hints.h new file +28 -0
@@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_ARM64_DWARF_UNWIND_HINTS_H +#define _ASM_ARM64_DWARF_UNWIND_HINTS_H + +#ifdef __ASSEMBLY__ + +#ifdef CONFIG_DWARF_FP + +.macro dwarf_unwind_hint, size, sp_offset, fp_offset +.Ldwarf_hint_pc_\@ : .pushsection .discard.unwind_hints + /* struct dwarf_unwind_hint */ + .long 0, (.Ldwarf_hint_pc_\@ - .) + .int \size + .short \sp_offset + .short \fp_offset + .popsection +.endm + +#else + +.macro dwarf_unwind_hint, size, sp_offset, fp_offset +.endm + +#endif + +#endif /* __ASSEMBLY__ */ + +#endif /* _ASM_ARM64_DWARF_UNWIND_HINTS_H */
arch/arm64/kernel/entry-ftrace.S +23 -0
@@ -11,6 +11,7 @@ #include <asm/assembler.h> #include <asm/ftrace.h> #include <asm/insn.h> +#include <asm/unwind_hints.h> #ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS /*
@@ -99,7 +100,14 @@ SYM_CODE_START(ftrace_common) mov x3, sp // regs SYM_INNER_LABEL(ftrace_call, SYM_L_GLOBAL) + /* + * Tracer functions are patched at ftrace_stub. Stack traces + * taken from tracer functions will end up here. Place an + * unwind hint based on the stackframe setup in ftrace_regs_entry. + */ bl ftrace_stub +SYM_INNER_LABEL(ftrace_call_entry, SYM_L_GLOBAL) + dwarf_unwind_hint 4, PT_REGS_SIZE, (S_STACKFRAME - PT_REGS_SIZE) #ifdef CONFIG_FUNCTION_GRAPH_TRACER SYM_INNER_LABEL(ftrace_graph_call, SYM_L_GLOBAL) // ftrace_graph_caller();
@@ -138,10 +146,25 @@ SYM_CODE_START(ftrace_graph_caller) add x1, sp, #S_LR // parent_ip (callsite's LR) ldr x2, [sp, #PT_REGS_SIZE] // parent fp (callsite's FP) bl prepare_ftrace_return +SYM_INNER_LABEL(ftrace_graph_caller_entry, SYM_L_GLOBAL) + dwarf_unwind_hint 4, PT_REGS_SIZE, (S_STACKFRAME - PT_REGS_SIZE) b ftrace_common_return SYM_CODE_END(ftrace_graph_caller) #endif +/* + * ftrace_regs_entry() sets up two stackframes - one for the callsite and + * one for the ftrace entry code. Unwind hints have been placed for the + * ftrace entry code above. We need an unwind hint for the callsite. Callsites + * are numerous. But the unwind hint required for all the callsites is the + * same. Define a dummy function here with the callsite unwind hint for the + * benefit of the unwinder. + */ +SYM_CODE_START(ftrace_callsite) + dwarf_unwind_hint 4, 16, -16 // for the callsite + ret +SYM_CODE_END(ftrace_callsite) + #else /* CONFIG_DYNAMIC_FTRACE_WITH_REGS */ /*
arch/arm64/kernel/entry.S +3 -0
@@ -28,6 +28,7 @@ #include <asm/thread_info.h> #include <asm/asm-uaccess.h> #include <asm/unistd.h> +#include <asm/unwind_hints.h> .macro clear_gp_regs .irp n,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29
@@ -551,6 +552,7 @@ SYM_CODE_START_LOCAL(el\el\ht\()_\regsize\()_\label) .if \el == 0 b ret_to_user .else + dwarf_unwind_hint 4, PT_REGS_SIZE, (S_STACKFRAME - PT_REGS_SIZE) b ret_to_kernel .endif SYM_CODE_END(el\el\ht\()_\regsize\()_\label)
@@ -783,6 +785,7 @@ SYM_FUNC_START(call_on_irq_stack) /* Move to the new stack and call the function there */ mov sp, x16 blr x1 + dwarf_unwind_hint 4, 0, -16 /* * Restore the SP from the FP, and restore the FP and LR from the frame
arch/arm64/kernel/ftrace.c +16 -0
@@ -299,3 +299,19 @@ int ftrace_disable_ftrace_graph_caller(void) }#endif /* CONFIG_DYNAMIC_FTRACE */ #endif /* CONFIG_FUNCTION_GRAPH_TRACER */ + +#ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS + +bool is_ftrace_entry (unsigned long pc) +{ +if (pc == (unsigned long )&ftrace_call_entry) +return true; + +#ifdef CONFIG_FUNCTION_GRAPH_TRACER +if (pc == (unsigned long )&ftrace_graph_caller_entry) +return true; +#endif +return false; +} + +#endif
arch/arm64/kernel/probes/kprobes_trampoline.S +2 -0
@@ -6,6 +6,7 @@ #include <linux/linkage.h> #include <asm/asm-offsets.h> #include <asm/assembler.h> +#include <asm/unwind_hints.h> .text
@@ -71,6 +72,7 @@ SYM_CODE_START(__kretprobe_trampoline) mov x0, sp bl trampoline_probe_handler + dwarf_unwind_hint 4, PT_REGS_SIZE, (S_FP - PT_REGS_SIZE) /* * Replace trampoline address in lr with actual orig_ret_addr return * address.
arch/arm64/kernel/stacktrace.c +66 -4
105 lines not on this page · raw message
include/linux/dwarf.h +9 -1
@@ -34,9 +34,17 @@* This contains an array of starting PCs, one for each rule. */ struct dwarf_rule { -unsigned int size:30 ; +unsigned int size:29 ;unsigned int sp_saved:1 ;unsigned int fp_saved:1 ; +unsigned int hint:1 ; +short sp_offset; +short fp_offset; +}; + +struct dwarf_unwind_hint { +unsigned long pc; +unsigned int size;short sp_offset;short fp_offset; };
include/linux/ftrace.h +4 -0
@@ -604,6 +604,10 @@ extern int ftrace_update_ftrace_func(ftrace_func_t func);extern void ftrace_caller (void );extern void ftrace_regs_caller (void );extern void ftrace_call (void ); +extern void ftrace_call_entry (void ); +extern void ftrace_graph_caller_entry (void ); +extern void ftrace_callsite (void ); +extern bool is_ftrace_entry (unsigned long pc);extern void ftrace_regs_call (void );extern void mcount_call (void );
tools/include/linux/dwarf.h +9 -1
@@ -34,9 +34,17 @@* This contains an array of starting PCs, one for each rule. */ struct dwarf_rule { -unsigned int size:30 ; +unsigned int size:29 ;unsigned int sp_saved:1 ;unsigned int fp_saved:1 ; +unsigned int hint:1 ; +short sp_offset; +short fp_offset; +}; + +struct dwarf_unwind_hint { +unsigned long pc; +unsigned int size;short sp_offset;short fp_offset; };
tools/objtool/dwarf_parse.c +58 -1
82 lines not on this page · raw message
tools/objtool/dwarf_rules.c +63 -2
112 lines not on this page · raw message
tools/objtool/include/objtool/dwarf_def.h +10 -0
@@ -304,6 +304,15 @@ struct fde {struct fde_entry *tail; }; +/* +* Entry for an unwind hint. +*/ +struct hint_entry { +struct hint_entry *next; +struct section *section; +struct dwarf_unwind_hint *hint; +}; +/* * These are identifiers for 32-bit and 64-bit CIE entries respectively. * These identifiers distinguish a CIE from an FDE in .debug_frame.
@@ -429,6 +438,7 @@ extern u64 (*get_value)(unsigned char *field, unsigned int size);void dwarf_rule_start (struct fde *fde);int dwarf_rule_add (struct fde *fde,unsigned long addr,struct rule *sp_rule,struct rule *fp_rule); +int dwarf_hint_add (struct section *section,struct dwarf_unwind_hint *hint);void dwarf_rule_next (struct fde *fde,unsigned long addr);void dwarf_rule_reset (struct fde *fde);int arch_dwarf_fde_reloc (struct fde *fde);
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 8/9 dwarf: Miscellaneous changes required for enabling livepatch
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
- Create arch/arm64/include/asm/livepatch.h and define klp_arch_set_pc() and klp_get_ftrace_location() which are required for livepatch.
- Define TIF_PATCH_PENDING in arch/arm64/include/asm/thread_info.h for livepatch.
- Check TIF_PATCH_PENDING in do_notify_resume() to patch the current task for livepatch.
--- arch/arm64/include/asm/livepatch.h | 42 ++++++++++++++++++++++++++++ arch/arm64/include/asm/thread_info.h | 4 ++- arch/arm64/kernel/signal.c | 4 +++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 arch/arm64/include/asm/livepatch.h
arch/arm64/include/asm/livepatch.h new file +42 -0
@@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 +* +* livepatch.h - arm64-specific Kernel Live Patching Core +*/ +#ifndef _ASM_ARM64_LIVEPATCH_H +#define _ASM_ARM64_LIVEPATCH_H + +#include <linux/ftrace.h> + +static inline void klp_arch_set_pc (struct ftrace_regs *fregs,unsigned long ip) +{ +struct pt_regs *regs =ftrace_get_regs (fregs); + + regs->pc = ip; +} + +/* +* klp_get_ftrace_location is expected to return the address of the BL to the +* relevant ftrace handler in the callsite. The location of this can vary based +* on several compilation options. +* CONFIG_DYNAMIC_FTRACE_WITH_REGS +* - Inserts 2 nops on function entry the second of which is the BL +* referenced above. (See ftrace_init_nop() for the callsite sequence) +* (this is required by livepatch and must be selected) +* CONFIG_ARM64_BTI_KERNEL: +* - Inserts a hint #0x22 on function entry if the function is called +* indirectly (to satisfy BTI requirements), which is inserted before +* the two nops from above. +*/ +#define klp_get_ftrace_location klp_get_ftrace_location +static inline unsigned long klp_get_ftrace_location (unsigned long faddr) +{ +unsigned long addr = faddr +AARCH64_INSN_SIZE ; + +#if IS_ENABLED (CONFIG_ARM64_BTI_KERNEL ) + addr =ftrace_location_range (addr, addr +AARCH64_INSN_SIZE ); +#endif + +return addr; +} + +#endif /* _ASM_ARM64_LIVEPATCH_H */
arch/arm64/include/asm/thread_info.h +3 -1
@@ -68,6 +68,7 @@ int arch_dup_task_struct(struct task_struct *dst,#define TIF_UPROBE 4/* uprobe breakpoint or singlestep */ #define TIF_MTE_ASYNC_FAULT 5/* MTE Asynchronous Tag Check Fault */ #define TIF_NOTIFY_SIGNAL 6/* signal notifications exist */ +#define TIF_PATCH_PENDING 7/* pending live patching update */ #define TIF_SYSCALL_TRACE 8/* syscall trace active */ #define TIF_SYSCALL_AUDIT 9/* syscall auditing */ #define TIF_SYSCALL_TRACEPOINT 10/* syscall tracepoint for ftrace */
@@ -98,11 +99,12 @@ int arch_dup_task_struct(struct task_struct *dst,#define _TIF_SVE (1 << TIF_SVE)#define _TIF_MTE_ASYNC_FAULT (1 << TIF_MTE_ASYNC_FAULT)#define _TIF_NOTIFY_SIGNAL (1 << TIF_NOTIFY_SIGNAL) +#define _TIF_PATCH_PENDING (1 << TIF_PATCH_PENDING)#define _TIF_WORK_MASK (_TIF_NEED_RESCHED | _TIF_SIGPENDING | \ _TIF_NOTIFY_RESUME | _TIF_FOREIGN_FPSTATE | \ _TIF_UPROBE | _TIF_MTE_ASYNC_FAULT | \ - _TIF_NOTIFY_SIGNAL) + _TIF_NOTIFY_SIGNAL | _TIF_PATCH_PENDING)#define _TIF_SYSCALL_WORK (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_AUDIT | \ _TIF_SYSCALL_TRACEPOINT | _TIF_SECCOMP | \
arch/arm64/kernel/signal.c +4 -0
@@ -18,6 +18,7 @@#include <linux/sizes.h> #include <linux/string.h> #include <linux/tracehook.h> +#include <linux/livepatch.h> #include <linux/ratelimit.h> #include <linux/syscalls.h>
@@ -937,6 +938,9 @@ void do_notify_resume(struct pt_regs *regs, unsigned long thread_flags) (void __user *)NULL, current); } +if (thread_flags & _TIF_PATCH_PENDING) +klp_update_patch_state (current); +if (thread_flags & (_TIF_SIGPENDING | _TIF_NOTIFY_SIGNAL))do_signal (regs);
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
RFC PATCH 9/9 dwarf: Enable livepatch for ARM64
In reply to [email protected]From: "Madhavan T. Venkataraman" <[email protected]>
Enable livepatch in arch/arm64/Kconfig.
--- arch/arm64/Kconfig | 5 +++++ 1 file changed, 5 insertions(+)
arch/arm64/Kconfig +5 -0
@@ -222,6 +222,9 @@ config ARM64 select THREAD_INFO_IN_TASK select HAVE_STACK_VALIDATION if DWARF_FP select STACK_VALIDATION if HAVE_STACK_VALIDATION + select HAVE_RELIABLE_STACKTRACE if STACK_VALIDATION + select HAVE_LIVEPATCH if HAVE_DYNAMIC_FTRACE_WITH_REGS && HAVE_RELIABLE_STACKTRACE + select HAVE_ARCH_USERFAULTFD_MINOR if USERFAULTFD select TRACE_IRQFLAGS_SUPPORT help
@@ -2066,3 +2069,5 @@ source "arch/arm64/kvm/Kconfig" if CRYPTO source "arch/arm64/crypto/Kconfig" endif + +source "kernel/livepatch/Kconfig"
Signature · 7 lines
2.25.1 _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to [email protected]Quoted 7 lines · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
The solution
============The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Quoted 8 lines
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Objtool can be invoked as follows:
objtool dwarf generate <object-file>
Hi Madhaven,
This is quite interesting. And it's exactly the kind of crazy idea I can appreciate ;-)
Some initial thoughts:
1)
I have some concerns about DWARF's reliability, especially considering
a) inline asm, b) regular asm, and c) the kernel's tendency to push compilers to their limits.
BUT, supplementing the frame pointer unwinding with DWARF, rather than just relying on DWARF alone, does help a LOT.
I guess the hope is that cross-checking two "mostly reliable" things against each other (frame pointers and DWARF) will give a reliable result ;-)
In a general sense, I've never looked at DWARF's reliability, even for just normal C code. It would be good to have some way of knowing that DWARF looks mostly sane for both GCC and Clang. For example, maybe somehow cross-checking it with objtool's knowledge. And then of course we'd have to hope that it stays bug-free in future compilers.
I'd also be somewhat concerned about assembly. Since there's nothing ensuring the unwind hints are valid, and will stay valid over time, I wonder how likely it would be for that to break, and what the implications would be. Most likely I guess it would break silently, but then get caught by the frame pointer cross-checking. So a broken hint might not get noticed for a long time, but at least it (hopefully) wouldn't break reliable unwinding.
Also, inline asm can sometimes do stack hacks like "push;do_something;pop" which isn't visible to the toolchain. But again, hopefully the frame pointer checking would fail and mark it unreliable.
So I do have some worries about DWARF, but the fact that it's getting "fact checked" by frame pointers might be sufficient.
2)
If I understand correctly, objtool is converting parts of DWARF to a new format which can then be read by the kernel. In that case, please don't call it DWARF as that will cause a lot of confusion.
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
3)
Objtool has become an integral part of x86-64, due to security and performance features and toolchain workarounds.
Not *all* of its features require the full "branch validation" which follows all code paths -- and was the hardest part to get right -- but several features *do* need that: stack validation, ORC, uaccess validation, noinstr validation.
Objtool has been picking up a lot of steam (and features) lately, with more features currently in active development. And lately there have been renewed patches for porting it to powerpc and arm64 (and rumors of s390).
If arm64 ever wants one of those features -- particularly a "branch validation" based feature -- I think it would make more sense to just do the stack validation in objtool, rather than the DWARF supplementation approach.
Just to give an idea of what objtool already supports and how useful it has become for x86, here's an excerpt from some documentation I've been working on, since I'm in the middle of rewriting the interface to make it more modular. This is a list of all its current features:
Features
--------
Objtool has the following features:
- Stack unwinding metadata validation -- useful for helping to ensure stack traces are reliable for live patching
- ORC unwinder metadata generation -- a faster and more precise alternative to frame pointer based unwinding
- Retpoline validation -- ensures that all indirect calls go through retpoline thunks, for Spectre v2 mitigations
- Retpoline call site annotation -- annotates all retpoline thunk call sites, enabling the kernel to patch them inline, to prevent "thunk funneling" for both security and performance reasons
- Non-instrumentation validation -- validates non-instrumentable ("noinstr") code rules, preventing unexpected instrumentation in low-level C entry code
- Static call annotation -- annotates static call sites, enabling the kernel to implement inline static calls, a faster alternative to some indirect branches
- Uaccess validation -- validates uaccess rules for a proper safe implementation of Supervisor Mode Access Protection (SMAP)
- Straight Line Speculation validation -- validates certain SLS mitigations
- Indirect Branch Tracking validation -- validates Intel CET IBT rules to ensure that all functions referenced by function pointers have corresponding ENDBR instructions
- Indirect Branch Tracking annotation -- annotates unused ENDBR instruction sites, enabling the kernel to "seal" them (replace them with NOPs) to further harden IBT
- Function entry annotation -- annotates function entries, enabling kernel function tracing
- Other toolchain hacks which will go unmentioned at this time...
Signature · 1 line
Josh
Peter Zijlstra
maintainerRe: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Right; so not having seen the patches due to Madhaven's email being broken, I can perhaps less appreciated the crazy involved.
Quoted 9 lines · Josh Poimboeuf
2)
If I understand correctly, objtool is converting parts of DWARF to a new format which can then be read by the kernel. In that case, please don't call it DWARF as that will cause a lot of confusion.
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
What Josh said; please use/extend ORC.
I really don't understand where all this crazy is coming from; why does objtool need to do something radically weird for ARM64?
There are existing ARM64 patches for objtool; in fact they have recently been re-posted:
https://lkml.kernel.org/r/[email protected]
The only tricky bit seems to be the whole jump-table issue. Using DWARF as input to deal with jump-tables should be possible -- exceedingly overkill, but possible I suppose. Mandating DWARF sucks though, compile times are so much worse with DWARVES on :/
Once objtool can properly follow/validate ARM64 code, it should be fairly straight forward to have it generate ORC data just like it does on x86_64.
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 4 lines · Peter Zijlstra
Right; so not having seen the patches due to Madhaven's email being broken, I can perhaps less appreciated the crazy involved.
Crazy like a fox.
Quoted 7 lines · Josh Poimboeuf
Quoted 6 lines
2)
If I understand correctly, objtool is converting parts of DWARF to a new format which can then be read by the kernel. In that case, please don't call it DWARF as that will cause a lot of confusion.
Quoted 6 lines
Quoted 3 lines
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
What Josh said; please use/extend ORC.
Yes. I am looking into it.
Quoted 8 lines
I really don't understand where all this crazy is coming from; why does objtool need to do something radically weird for ARM64?
There are existing ARM64 patches for objtool; in fact they have recently been re-posted:
Quoted 9 lines
The only tricky bit seems to be the whole jump-table issue. Using DWARF as input to deal with jump-tables should be possible -- exceedingly overkill, but possible I suppose. Mandating DWARF sucks though, compile times are so much worse with DWARVES on :/
Once objtool can properly follow/validate ARM64 code, it should be fairly straight forward to have it generate ORC data just like it does on
x86_64.
My reasons for attempting the DWARF based implementation:
- My implementation is largely architecture independent. There are a couple of minor pieces that are architecture-specific, but they are minor in nature. So, if an architecture wanted to support the livepatch feature but did not want to do a heavy weight objtool implementation, then it has an option. There has been some debate about whether static analysis should be mandated for livepatch. My patch series is an attempt to provide an option.
- To get an objtool static analysis implementation working for an architecture as reliably as X64 and getting it reviewed and upstreamed can take years. It took years for X64, am I right? I mean, it has been quite a while since the original patch series for arm64 was posted. There have been only one or two minor comments so far. I am sure arm64 linux users would very much want to have livepatch available ASAP to be able to install security fixes without downtime. This is an immediate need.
- No software is bug free. So, even if static analysis is implemented for an architecture, it would be good to have another method of verifying the unwind rules generated from the static analysis. DWARF can provide that additional verification.
Madhavan
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to Josh PoimboeufHi Josh,
Quoted 13 lines · Josh Poimboeuf
Quoted 12 lines · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
The solution
============The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Quoted 9 lines
Quoted 3 lines
Objtool can be invoked as follows:
objtool dwarf generate <object-file>
Hi Madhaven,
This is quite interesting. And it's exactly the kind of crazy idea I can appreciate ;-)
A little crazy is a good thing sometimes.
Quoted 9 lines
Some initial thoughts:
1)
I have some concerns about DWARF's reliability, especially considering
a) inline asm, b) regular asm, and c) the kernel's tendency to push compilers to their limits.
I am thinking of implementing a DWARF verifier to make sure that the DWARF information in .debug_frame is correct. I am still in the process of designing this. I will keep you posted on that. This should address (a) and (c).
As for (b), the compiler does not generate any DWARF rules for ASM code. DWARF annotations are a PITA to maintain. So, in my current design regular ASM functions are considered unreliable from an unwind perspective except the places that have unwind hints. Unwind hints are only needed for places that tend to occur frequently in stack traces. So, it would be just a handful of unwind hints which can be maintained.
As you know, ASM functions come in two flavors - SYM_CODE() functions and SYM_FUNC() functions. SYM_CODE functions are, by definition, unreliable from an unwind perspective because they don't follow ABI rules and they don't set up any frame pointer. In my reliable stack trace patch series, I have a patch based on the opinion of the reviewers to mark these functions so the unwinder can recognize them and declare the stack trace unreliable. So, the only ASM functions that matter in (b) are the SYM_FUNC functions. For now, I have considered them to be unreliable. But I will analyze those functions to see if any of them can occur frequently in stack traces. If some of these functions can occur frequently in stack traces, I need to address them. I will see if unwind hints are a good fit. I will get back to you on this.
Quoted 3 lines
BUT, supplementing the frame pointer unwinding with DWARF, rather than just relying on DWARF alone, does help a LOT.
Yes.
Quoted 4 lines
I guess the hope is that cross-checking two "mostly reliable" things against each other (frame pointers and DWARF) will give a reliable result ;-)
Yes!
Quoted 6 lines
In a general sense, I've never looked at DWARF's reliability, even for just normal C code. It would be good to have some way of knowing that DWARF looks mostly sane for both GCC and Clang. For example, maybe somehow cross-checking it with objtool's knowledge. And then of course we'd have to hope that it stays bug-free in future compilers.
This is a valid point. So far, I find that gcc generates reliable DWARF information. But there are two bugs in what Clang generates. I have added workarounds in my parser to compensate.
So, I think a DWARF verifier is an option that architectures can use. At this point, I don't want to mandate a verifier on every architecture. But that is a discussion that we can have once I have a verifier ready.
Quoted 8 lines
I'd also be somewhat concerned about assembly. Since there's nothing ensuring the unwind hints are valid, and will stay valid over time, I wonder how likely it would be for that to break, and what the implications would be. Most likely I guess it would break silently, but then get caught by the frame pointer cross-checking. So a broken hint might not get noticed for a long time, but at least it (hopefully) wouldn't break reliable unwinding.
Yes. That is my thinking as well. When the unwinder checks the actual FP with the computed FP, any mismatch will be treated as unreliable code for unwind. So, apart from some retries during the livepatch process, this is most probably not a problem.
Now, I set a flag for an unwind hint so that the unwinder knows that it is processing an unwind hint. I could generate a warning if an unwind hint does not result in a reliable unwind of the frame. This would bring the broken hint to people's attention.
Quoted 8 lines
Also, inline asm can sometimes do stack hacks like "push;do_something;pop" which isn't visible to the toolchain. But again, hopefully the frame pointer checking would fail and mark it unreliable.
So I do have some worries about DWARF, but the fact that it's getting "fact checked" by frame pointers might be sufficient.
Exactly.
Quoted 7 lines
2)
If I understand correctly, objtool is converting parts of DWARF to a new format which can then be read by the kernel. In that case, please don't call it DWARF as that will cause a lot of confusion.
OK. I will rename it.
Quoted 4 lines
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
I will certainly look into it. So, if I decide to merge the two, I might want to make a minor change to the ORC structure. Would that be OK with you?
Quoted 16 lines
3)
Objtool has become an integral part of x86-64, due to security and performance features and toolchain workarounds.
Not *all* of its features require the full "branch validation" which follows all code paths -- and was the hardest part to get right -- but several features *do* need that: stack validation, ORC, uaccess validation, noinstr validation.
Objtool has been picking up a lot of steam (and features) lately, with more features currently in active development. And lately there have been renewed patches for porting it to powerpc and arm64 (and rumors of s390).
Quoted 5 lines
If arm64 ever wants one of those features -- particularly a "branch validation" based feature -- I think it would make more sense to just do the stack validation in objtool, rather than the DWARF supplementation approach.
First off, I think that objtool does a great job for X64. I only want to implement frame pointer validation in a different way. All the other features of objtool (listed below) are great. I have admired the amount of work you guys have put into the X64 part.
These are the reasons why I tried the DWARF based method:
- My implementation is largely architecture independent. There are a couple of minor pieces that are architecture-specific, but they are minor in nature. So, if an architecture wanted to support the livepatch feature but did not want to do a heavy weight objtool implementation, then it has an option. There has been some debate about whether static analysis should be mandated for livepatch. My patch series is an attempt to provide an option.
- To get an objtool static analysis implementation working for an architecture as reliably as X64 and getting it reviewed and upstreamed can take years. It took years for X64, am I right? I mean, it has been quite a while since the original patch series for arm64 was posted. There have been only one or two minor comments so far. I am sure arm64 linux users would very much want to have livepatch available ASAP to be able to install security fixes without downtime. This is an immediate need.
- No software is bug free. So, even if static analysis is implemented for an architecture, it would be good to have another method of verifying the unwind rules generated from the static analysis. DWARF can provide that additional verification.
Quoted 43 lines
Just to give an idea of what objtool already supports and how useful it has become for x86, here's an excerpt from some documentation I've been working on, since I'm in the middle of rewriting the interface to make it more modular. This is a list of all its current features:
Features
--------Objtool has the following features:
- Stack unwinding metadata validation -- useful for helping to ensure stack traces are reliable for live patching
- ORC unwinder metadata generation -- a faster and more precise alternative to frame pointer based unwinding
- Retpoline validation -- ensures that all indirect calls go through retpoline thunks, for Spectre v2 mitigations
- Retpoline call site annotation -- annotates all retpoline thunk call sites, enabling the kernel to patch them inline, to prevent "thunk funneling" for both security and performance reasons
- Non-instrumentation validation -- validates non-instrumentable ("noinstr") code rules, preventing unexpected instrumentation in low-level C entry code
- Static call annotation -- annotates static call sites, enabling the kernel to implement inline static calls, a faster alternative to some indirect branches
- Uaccess validation -- validates uaccess rules for a proper safe implementation of Supervisor Mode Access Protection (SMAP)
- Straight Line Speculation validation -- validates certain SLS mitigations
- Indirect Branch Tracking validation -- validates Intel CET IBT rules to ensure that all functions referenced by function pointers have corresponding ENDBR instructions
Quoted 9 lines
- Indirect Branch Tracking annotation -- annotates unused ENDBR instruction sites, enabling the kernel to "seal" them (replace them with NOPs) to further harden IBT
- Function entry annotation -- annotates function entries, enabling kernel function tracing
- Other toolchain hacks which will go unmentioned at this time...
I completely agree.
So, it is just frame pointer validation for livepatch I am trying to look at.
Thanks!
Madhavan
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Hi Madhaven,
Sorry I sent the last email as HTML. This is a plain text resend.
Quoted 7 lines · Madhavan T. Venkataraman
Quoted 6 lines
In a general sense, I've never looked at DWARF's reliability, even for just normal C code. It would be good to have some way of knowing that DWARF looks mostly sane for both GCC and Clang. For example, maybe somehow cross-checking it with objtool's knowledge. And then of course we'd have to hope that it stays bug-free in future compilers.
Quoted 8 lines
This is a valid point. So far, I find that gcc generates reliable DWARF information. But there are two bugs in what Clang generates. I have added workarounds in my parser to compensate.
So, I think a DWARF verifier is an option that architectures can use. At this point, I don't want to mandate a verifier on every architecture. But that is a discussion that we can have once I have a verifier ready.
I'm concerning that depending on compilers to generate correct information can become a trouble because we linux kernel side can rarely fix what compilers make. That's also why the gcc plugin idea was objected in the objtool migration.
If your parser can solve this it sounds more doable.
Quoted 25 lines
Quoted 8 lines
I'd also be somewhat concerned about assembly. Since there's nothing ensuring the unwind hints are valid, and will stay valid over time, I wonder how likely it would be for that to break, and what the implications would be. Most likely I guess it would break silently, but then get caught by the frame pointer cross-checking. So a broken hint might not get noticed for a long time, but at least it (hopefully) wouldn't break reliable unwinding.
Yes. That is my thinking as well. When the unwinder checks the actual FP with the computed FP, any mismatch will be treated as unreliable code for unwind. So, apart from some retries during the livepatch process, this is most probably not a problem.
Now, I set a flag for an unwind hint so that the unwinder knows that it is processing an unwind hint. I could generate a warning if an unwind hint does not result in a reliable unwind of the frame. This would bring the broken hint to people's attention.
Quoted 5 lines
Also, inline asm can sometimes do stack hacks like "push;do_something;pop" which isn't visible to the toolchain. But again, hopefully the frame pointer checking would fail and mark it unreliable.
Quoted 6 lines
Quoted 3 lines
So I do have some worries about DWARF, but the fact that it's getting "fact checked" by frame pointers might be sufficient.
Exactly.
I'm wondering how much functions will give a unreliable result because any unreliable function shows in stack trace will cause livepatch fail/retry. IIUC all unmarked assembly functions will considered unreliable and cause problem. It can be a burden to mark all of them.
Quoted 4 lines
- No software is bug free. So, even if static analysis is implemented for an architecture, it would be good to have another method of verifying the unwind rules generated from the static analysis. DWARF can provide that additional verification.
I'm wondering how much functions will give a unreliable result because any unreliable function shows in stack trace will cause livepatch fail/retry. IIUC all unmarked assembly functions will considered unreliable and cause problem. It can be a burden to mark all of them.
Quoted 3 lines
So, it is just frame pointer validation for livepatch I am trying to look at.
My support reason for FP with validation is that it provides a guarantee for FP unwinder. FP and ORC use absolute and relative for stack unwind to unwind stack respectively, however FP has been considered unreliable. Is there any feature depends on FP? If so it can be more persuasive.
Also this patch is much more completed than migration for objtool. It would be nice if this could be put into use quickly. The objtool-arm64 is less than half done, but I'm going to relies as much as possible on current objtool components, so no more feasibility validation is required.
By the way, I was thinking about a corner case, because arm64 CALL instruction won't push LR onto stack atomically as x86. Before push LR, FP to save frame there still can be some instructions such as bti, paciasp. If an irq happens here, the stack frame is not constructed so the FP unwinder will omit this function and provides a wrong stack trace to livepatch.
It's just a guess and I have not built the test case. But I think it's a defect on arm64 that FP unwinder can't work properly on prologue and epilogue. Do you have any idea about this?
Thanks for your time,
Chen
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 9 lines · Chen Zhongjin
By the way, I was thinking about a corner case, because arm64 CALL instruction won't push LR onto stack atomically as x86. Before push LR, FP to save frame there still can be some instructions such as bti, paciasp. If an irq happens here, the stack frame is not constructed so the FP unwinder will omit this function and provides a wrong stack trace to livepatch.
It's just a guess and I have not built the test case. But I think it's a defect on arm64 that FP unwinder can't work properly on prologue and epilogue. Do you have any idea about this?
x86 has similar issues with frame pointers, if for example preemption or page fault exception occurs in a leaf function, or in a function prologue or epilogue, before or after the frame pointer setup.
This issue is solved by the "reliable" unwinder which detects irqs/exceptions on the stack and reports the stack as unreliable.
Signature · 7 lines
Josh _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Hi Josh,
IIUC, ORC on x86 can make reliable stack unwind for this scenario because objtool validates BP state.
I'm thinking that on arm64 there's no guarantee that LR will be pushed onto stack. When we meet similar scenario on arm64, we should recover (LR, FP) on pt_regs and continue to unwind the stack. And this is reliable only after we validate (LR, FP).
So should we track LR on arm64 additionally as track BP on x86? Or can we just treat (LR, FP) as a pair? because as I know they are always set up together.
Quoted 11 lines · Josh Poimboeuf
Quoted 9 lines · Chen Zhongjin
By the way, I was thinking about a corner case, because arm64 CALL instruction won't push LR onto stack atomically as x86. Before push LR, FP to save frame there still can be some instructions such as bti, paciasp. If an irq happens here, the stack frame is not constructed so the FP unwinder will omit this function and provides a wrong stack trace to livepatch.
It's just a guess and I have not built the test case. But I think it's a defect on arm64 that FP unwinder can't work properly on prologue and epilogue. Do you have any idea about this?
Quoted 7 lines
x86 has similar issues with frame pointers, if for example preemption or page fault exception occurs in a leaf function, or in a function prologue or epilogue, before or after the frame pointer setup.
This issue is solved by the "reliable" unwinder which detects irqs/exceptions on the stack and reports the stack as unreliable.
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 5 lines · Chen Zhongjin
Hi Josh,
IIUC, ORC on x86 can make reliable stack unwind for this scenario because objtool validates BP state.
Quoted 8 lines
I'm thinking that on arm64 there's no guarantee that LR will be pushed onto stack. When we meet similar scenario on arm64, we should recover (LR, FP) on
pt_regsand continue to unwind the stack. And this is reliable only after we validate (LR, FP).So should we track LR on arm64 additionally as track BP on x86? Or can we just treat (LR, FP) as a pair? because as I know they are always set up together.
Does the arm64 unwinder have a way to detect kernel pt_regs on the stack? If so, the simplest solution is to mark all stacks with kernel regs as unreliable. That's what the x86 FP unwinder does.
Signature · 1 line
Josh
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 11 lines · Josh Poimboeuf
Quoted 10 lines · Chen Zhongjin
Hi Josh,
IIUC, ORC on x86 can make reliable stack unwind for this scenario because objtool validates BP state.
I'm thinking that on arm64 there's no guarantee that LR will be pushed onto stack. When we meet similar scenario on arm64, we should recover (LR, FP) on
pt_regsand continue to unwind the stack. And this is reliable only after we validate (LR, FP).
Quoted 8 lines
Quoted 3 lines
So should we track LR on arm64 additionally as track BP on x86? Or can we just treat (LR, FP) as a pair? because as I know they are always set up together.
Does the arm64 unwinder have a way to detect kernel
pt_regson the stack? If so, the simplest solution is to mark all stacks with kernel regs as unreliable. That's what the x86 FP unwinder does.
AFAICT, only the task pt_regs can be detected. For detecting the other pt_regs, we would have to set a bit in the FP. IIRC, I had a proposal where I set the LSB in the FP stored on the stack. The arm64 folks did not like that approach as it would be indistinguishable from a corrupted FP, however unlikely the corruption may be.
Unwind hints can be used for these cases to unwind reliably through them. That is probably the current thinking. Mark Rutland can confirm.
Madhavan
A message that is not in the archive (sent off-list or not yet received): [email protected]
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 8 lines · Chen Zhongjin
Hi Madhaven,
Quoted 5 lines · Madhavan T. Venkataraman
This is a valid point. So far, I find that gcc generates reliable DWARF information. But there are two bugs in what Clang generates. I have added workarounds in my parser to compensate.
Quoted 9 lines
Quoted 3 lines
So, I think a DWARF verifier is an option that architectures can use. At this point, I don't want to mandate a verifier on every architecture. But that is a discussion that we can have once I have a verifier ready.
I'm concerning that depending on compilers to generate correct information can become a trouble because we linux kernel side can rarely fix what compilers make. That's also why the gcc plugin idea was objected in the objtool migration.
If your parser can solve this it sounds more doable.
So far, I find that gcc generates reliable DWARF information. Clang did have two bugs for which the parser compensates.
So, what is needed is a DWARF verifier which can find buggy DWARF information. I am working on it.
Having said that, I think the DWARF information for the stack and frame pointer is a *lot* simpler than the other debug stuff. So, there may be a couple of existing bugs that need to be discovered and fixed. But I think the likelihood of bugs appearing in this area in the future is low but it can happen. I agree that there needs to be a way to discover and flag the bugs when they do appear.
But compiler bugs can also affect objtool and cause problems in it. If I am not mistaken, they ran into this multiple times on the X86 side and had to get fixes done. Josh knows better. Compiler bugs and optimizations have always been problematic from this perspective and they will potentially continue to be.
Quoted 17 lines
Quoted 12 lines
Yes. That is my thinking as well. When the unwinder checks the actual FP with the computed FP, any mismatch will be treated as unreliable code for unwind. So, apart from some retries during the livepatch process, this is most probably not a problem.
Now, I set a flag for an unwind hint so that the unwinder knows that it is processing an unwind hint. I could generate a warning if an unwind hint does not result in a reliable unwind of the frame. This would bring the broken hint to people's attention.
Quoted 5 lines
Also, inline asm can sometimes do stack hacks like "push;do_something;pop" which isn't visible to the toolchain. But again, hopefully the frame pointer checking would fail and mark it unreliable.
Quoted 4 lines
I'm wondering how much functions will give a unreliable result because any unreliable function shows in stack trace will cause livepatch fail/retry. IIUC all unmarked assembly functions will considered unreliable and cause problem. It can be a burden to mark all of them.
It is not a burden to mark all of them. For instance, I have submitted a patch where I mark all the SYM_CODE*() functions by overriding the SYM_CODE_START()/END() macros in arm64. So, the changes are very small and self-contained.
A good part of the assembly functions are defined with SYM_CODE_*(). These, by definition, are low-level functions that do not follow ABI rules. IIRC, Objtool does not perform static analysis on these today. These need to be recognized by the unwinder in the kernel and handled. Josh, please correct me if I am wrong. So, this is a problem even if we had static analysis in Objtool for arm64.
As for functions defined with SYM_FUNC_*(), they are supposed to have proper frame setup and teardown. But most of them do not appear to have a proper frame pointer prolog and epilog today in arm64. Some of these will probably never have an FP prolog or epilog because they are high performance functions or specialized functions and the extra overhead may be unacceptable. Some of the SYM_FUNC*() functions are leaf functions that don't need an FP prolog or epilog.
With static analysis, Objtool will flag all such functions. Either a proper FP prolog and epilog have to be introduced in the code or the functions need to be flagged as unreliable from an unwind perspective. If any of these functions occurs frequently in stack traces, then, either a proper FP prolog and epilog have to be introduced in the function code. Or, unwind hints have to be placed at strategic points. In either case, there is a maintenance burden although developers may prefer one over the other on a case-by-case basis.
The DWARF situation is the same. For the frequently occurring assembly functions, unwind hints need to be defined. Currently, I have undertaken to study the SYM_FUNC*() functions in arm64 to see if I can determine which ones belong to this category. Also, I am going to be doing targeted livepatch testing to see if any of these functions will cause many retries during the livepatch process. If they don't, then this is not a problem.
Quoted 8 lines
Quoted 3 lines
- No software is bug free. So, even if static analysis is implemented for an architecture, it would be good to have another method of verifying the unwind rules generated from the static analysis. DWARF can provide that additional verification.
To me verifying ORC with DWARF a little odd, cuz they are running with different unwind mechanism. For normal scenario which calling convention is obeyed, ORC can give a promised reliable stack trace, while when it easily involve bug in assembly codes, DWARF also can't work.
I am not sure I follow. With both DWARF and ORC, stack pointer and frame pointer offsets are recorded for every instruction address. These offsets have to be the same regardless of which one you use.
The only difference is that for an assembly function that has a proper FP prolog and epilog, Objtool static analysis is able to generate those offsets. With DWARF, the compiler does not generate any offsets for assembly functions. I have to rely on unwind hints. BTW, I only need to do this for functions that occur frequently in stack traces.
Quoted 4 lines
My support for FP with validation is that it provides a guarantee for FP unwinder. FP and ORC use absolute and relative for stack unwind to unwind stack respectively, however FP has been considered unreliable. Is there any feature depends on FP? If so it can be more persuasive.
Yes. Static analysis makes sure that functions are following ABI rules. So, it provides a static guarantee. And that is great.
However, with DWARF, even if some functions don't follow ABI rules, a reliable unwinder can still be provided as long as the DWARF information generated by the compiler is correct. For instance, let us say that the compiler generates code for a function with a call to another function before the FP has been setup properly. If the DWARF information is correctly generated, the unwinder can see that a stack trace involving the called function is unreliable.
Also, hypothetically, if a buggy kernel function corrupts the frame pointer or the stack pointer, dynamic validation can catch it.
Quoted 6 lines
Also this patch is much more completed than migration for objtool. It would be
nice if this could be put into use quickly. The objtool-arm64 is less than half done, but I'm going to relies as much as possible on current objtool components, so no more feasibility validation is required.
The approach in your patch series is certainly feasible. I don't deny that at all. And, believe me, I would like the community to take interest in it and review it. If I get a chance, I will also participate in that review.
As I mentioned in a previous email, my attempt is to come up with a largely architecture independent solution to the FP validation problem with a quicker time to market. That is all.
Quoted 6 lines
By the way, I was thinking about a corner case, because arm64 CALL instruction won't push LR onto stack atomically as x86. Before push LR, FP to save frame there still can be some instructions such as bti, paciasp. If an irq happens here, the stack frame is not constructed
so the FP unwinder will omit this function and provides a wrong stack trace to livepatch.
With DWARF, the unwinder will see that there are no DWARF rules associated with those PCs that occur before the FP is completely setup. It will mark the stack trace as unreliable. So, these cases are already handled as I have explained in my cover letter.
Quoted 3 lines
It's just a guess and I have not built the test case. But I think it's a defect on arm64 that FP unwinder can't work properly on prologue and epilogue. Do you have any idea about this?
There is no defect. The frame pointer prolog can have multiple instructions before the frame is set up. Any interrupt or exception happening on those instructions will have an unreliable stack trace by definition. A reliable unwinder must be able to recognize that case and mark the stack trace as unreliable. That is all.
Thanks for your comments.
Madhavan
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to Madhavan T. VenkataramanQuoted 7 lines · Madhavan T. Venkataraman
Quoted 4 lines
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
I will certainly look into it. So, if I decide to merge the two, I might want to make a minor change to the ORC structure. Would that be OK with you?
Yes, in fact I would expect it, since ORC is quite x86-specific at the moment. So it would need some abstractions to make it more multi-arch friendly.
Signature · 7 lines
Josh _______________________________________________ linux-arm-kernel mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to Josh PoimboeufHi Josh, Peter,
I have decided to accept your comment that using the compiler generated DWARF info is probably not reliable. I can write a DWARF verifier. But I decided that if I can write a DWARF verifier, I can use that same code to generate the same information as DWARF CFI.
So, I am going to implement this in the traditional way as you wanted. Fortunately, I only need to decode a small subset of the instruction formats (just the ones that affect the SP and FP) and branch and return instructions to be able to compute the SP and FP offsets at every instruction address. I only need a small part of the static analysis code.
In other words, I am removing the crazy from my patch series. I am still retaining the idea of dynamic FP validation rather than static validation. IMO, that will be able to handle even non-ABI compliant functions and FP corruptions from buggy kernel functions.
Huawei has resubmitted the objtool patch set. When the full blown static analysis is implemented by them and accepted by the community, my changes can be easily merged with theirs. So, my solution is not a competing solution. In fact, it will provide an additional level of robustness.
I will make these changes, test and send out version 2.
Thanks for your comments.
Madhavan
Quoted 135 lines · Josh Poimboeuf
Quoted 7 lines · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
The solution
============The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Quoted 8 lines
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Objtool can be invoked as follows:
objtool dwarf generate <object-file>
Hi Madhaven,
This is quite interesting. And it's exactly the kind of crazy idea I can appreciate ;-)
Some initial thoughts:
1)
I have some concerns about DWARF's reliability, especially considering
a) inline asm, b) regular asm, and c) the kernel's tendency to push compilers to their limits.BUT, supplementing the frame pointer unwinding with DWARF, rather than just relying on DWARF alone, does help a LOT.
I guess the hope is that cross-checking two "mostly reliable" things against each other (frame pointers and DWARF) will give a reliable result ;-)
In a general sense, I've never looked at DWARF's reliability, even for just normal C code. It would be good to have some way of knowing that DWARF looks mostly sane for both GCC and Clang. For example, maybe somehow cross-checking it with objtool's knowledge. And then of course we'd have to hope that it stays bug-free in future compilers.
I'd also be somewhat concerned about assembly. Since there's nothing ensuring the unwind hints are valid, and will stay valid over time, I wonder how likely it would be for that to break, and what the implications would be. Most likely I guess it would break silently, but then get caught by the frame pointer cross-checking. So a broken hint might not get noticed for a long time, but at least it (hopefully) wouldn't break reliable unwinding.
Also, inline asm can sometimes do stack hacks like "push;do_something;pop" which isn't visible to the toolchain. But again, hopefully the frame pointer checking would fail and mark it unreliable.
So I do have some worries about DWARF, but the fact that it's getting "fact checked" by frame pointers might be sufficient.
2)
If I understand correctly, objtool is converting parts of DWARF to a new format which can then be read by the kernel. In that case, please don't call it DWARF as that will cause a lot of confusion.
There are actually several similarities between your new format and ORC, which is also an objtool-created DWARF alternative. It would be interesting to see if they could be combined somehow.
3)
Objtool has become an integral part of x86-64, due to security and performance features and toolchain workarounds.
Not *all* of its features require the full "branch validation" which follows all code paths -- and was the hardest part to get right -- but several features *do* need that: stack validation, ORC, uaccess validation, noinstr validation.
Objtool has been picking up a lot of steam (and features) lately, with more features currently in active development. And lately there have been renewed patches for porting it to powerpc and arm64 (and rumors of s390).
If arm64 ever wants one of those features -- particularly a "branch validation" based feature -- I think it would make more sense to just do the stack validation in objtool, rather than the DWARF supplementation approach.
Just to give an idea of what objtool already supports and how useful it has become for x86, here's an excerpt from some documentation I've been working on, since I'm in the middle of rewriting the interface to make it more modular. This is a list of all its current features:
Features
--------Objtool has the following features:
- Stack unwinding metadata validation -- useful for helping to ensure stack traces are reliable for live patching
- ORC unwinder metadata generation -- a faster and more precise alternative to frame pointer based unwinding
- Retpoline validation -- ensures that all indirect calls go through retpoline thunks, for Spectre v2 mitigations
- Retpoline call site annotation -- annotates all retpoline thunk call sites, enabling the kernel to patch them inline, to prevent "thunk funneling" for both security and performance reasons
- Non-instrumentation validation -- validates non-instrumentable ("noinstr") code rules, preventing unexpected instrumentation in low-level C entry code
- Static call annotation -- annotates static call sites, enabling the kernel to implement inline static calls, a faster alternative to some indirect branches
- Uaccess validation -- validates uaccess rules for a proper safe implementation of Supervisor Mode Access Protection (SMAP)
- Straight Line Speculation validation -- validates certain SLS mitigations
- Indirect Branch Tracking validation -- validates Intel CET IBT rules to ensure that all functions referenced by function pointers have corresponding ENDBR instructions
Quoted 9 lines
- Indirect Branch Tracking annotation -- annotates unused ENDBR instruction sites, enabling the kernel to "seal" them (replace them with NOPs) to further harden IBT
- Function entry annotation -- annotates function entries, enabling kernel function tracing
- Other toolchain hacks which will go unmentioned at this time...
_______________________________________________
linux-arm-kernel mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-arm-kernel
Peter Zijlstra
maintainerRe: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to [email protected]Quoted 1 line · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
[-- application/octet-stream is unsupported (use 'v' to view this part) --]
Your emails are unreadable :-(
Peter Zijlstra
maintainerRe: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 5 lines · Peter Zijlstra
Quoted 1 line · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
[-- application/octet-stream is unsupported (use 'v' to view this part) --]
Your emails are unreadable :-(
List copy is OK, so perhaps it's due to how Josh bounced them..
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 8 lines · Peter Zijlstra
Quoted 5 lines · Peter Zijlstra
Quoted 1 line · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
[-- application/octet-stream is unsupported (use 'v' to view this part) --]
Your emails are unreadable :-(
List copy is OK, so perhaps it's due to how Josh bounced them..
Corporate email Mimecast fail when I bounced them, sorry :-/
Signature · 1 line
Josh
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to Peter ZijlstraQuoted 5 lines · Peter Zijlstra
Quoted 1 line · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
[-- application/octet-stream is unsupported (use 'v' to view this part) --]
Your emails are unreadable :-(
I am not sure why the emails are unreadable. Any suggestions? Should I resend? Please let me know. Sorry about this.
Madhavan
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 11 lines · Madhavan T. Venkataraman
Quoted 5 lines · Peter Zijlstra
Quoted 1 line · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
[-- application/octet-stream is unsupported (use 'v' to view this part) --]
Your emails are unreadable :-(
I am not sure why the emails are unreadable. Any suggestions? Should I resend? Please let me know. Sorry about this.
That was actually my (company's) fault when I bounced the patches to Peter.
Signature · 1 line
Josh
Peter Zijlstra
maintainerRe: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
In reply to [email protected]Quoted 14 lines · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
The solution
============The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Objtool can be invoked as follows:
Quoted 8 lines
objtool dwarf generate <object-file>
The version of the DWARF standard supported in this work is version 4. The official documentation for this version is here:
https://dwarfstd.org/doc/DWARF4.pdf
Section 6.4 contains the description of the CFI.
The problem is of course that DWARF is only available for compiler generated code and doesn't cover assembly code, of which is there is always lots.
I suppose you can go add DWARF annotations to all the assembly, but IIRC those are pretty terrible. We were *REALLY* happy to delete all that nasty from the x86 code.
On top of that, AFAIK compilers don't generally consider DWARF generation to be a correctness issue. For them it's debug info and having it be correct is nice but not required. So using it as input for something that's required to be correct, seems unfortunate.
Re: [RFC PATCH v1 0/9] arm64: livepatch: Use DWARF Call Frame Information for frame pointer validation
Quoted 20 lines · Peter Zijlstra
Quoted 19 lines · On Thu, Apr 07, 2022 at 03:25:09PM -0500, [email protected] wrote:
The solution
============The goal here is to use the absolute minimum CFI needed to compute the FP at every instruction address. The unwinder can compute the FP in each frame, compare the actual FP with the computed one and validate the actual FP.
Objtool is enhanced to parse the CFI, extract just the rules required, encode them in compact data structures and create special sections for the rules. The unwinder uses the special sections to find the rules for a given instruction address and compute the FP.
Objtool can be invoked as follows:
objtool dwarf generate <object-file>
The version of the DWARF standard supported in this work is version 4. The official documentation for this version is here:
Quoted 8 lines
Quoted 3 lines
https://dwarfstd.org/doc/DWARF4.pdf
Section 6.4 contains the description of the CFI.
The problem is of course that DWARF is only available for compiler generated code and doesn't cover assembly code, of which is there is always lots.
Yes. But assembly functions are of two types:
SYM_CODE_*() functions
SYM_FUNC_*() functions
SYM_CODE functions are, by definition, special functions that don't follow any ABI rules. They don't set up a frame. Based on the opinion of ARM64 experts, these need to be recognized by the unwinder and, if they are present in a stack trace, the stack trace must be considered unreliable. I have, in fact, submitted a patch to implement that.
So, only SYM_FUNC*() functions are relevant for this part. I will look into these for arm64 and check if any of them can occur frequently in stack traces. If any of them is likely to occur frequently in stack traces, I must address them. If there are only a few such functions, unwind hints may be sufficient. I will get back to you on this.
Quoted 4 lines
I suppose you can go add DWARF annotations to all the assembly, but IIRC those are pretty terrible. We were *REALLY* happy to delete all that nasty from the x86 code.
DWARF annotations are a PITA to maintain. I will never recommend that!
Quoted 4 lines
On top of that, AFAIK compilers don't generally consider DWARF generation to be a correctness issue. For them it's debug info and having it be correct is nice but not required. So using it as input for something that's required to be correct, seems unfortunate.
It is only debug info. But if that info can be verified, then it is usable for livepatch purposes. I am thinking of implementing a verifier since DWARF reliability is a valid concern. I will keep you posted.
Thanks!
Madhavan