How to Trace User Space Stacks with eBPF? – Free Linux Device Driver Training

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →
Inspecting User Space Stack and eBPF Stack Tracing in Linux 6.x | Free Linux Kernel Course

User Space Stack & eBPF Stack Tracing
Modern Linux Process Debugging — Free Linux Kernel Programming Course
Level
Intermediate
Kernel
Linux 6.x
Tools
GDB + eBPF

How to Inspect the Linux User Space Stack and Trace Both Stacks with eBPF

In the previous lecture, we explored the kernel mode stack — the private stack every process uses while executing inside the Linux kernel. Now we turn to the user space stack and learn how to inspect it. We also introduce eBPF — the modern, powerful technology built into Linux 6.x that lets you trace both the kernel stack and the user space stack of a live process simultaneously, without modifying the process or the kernel. This is a critical skill for anyone pursuing a free Linux kernel development course or writing Linux device drivers.

🎓 What You Will Learn

  • What the user space stack contains and how it differs from the kernel stack
  • How to use gdb to inspect the user space stack of a live process
  • What eBPF (extended Berkeley Packet Filter) is and why it matters for Linux kernel developers
  • How the BCC toolkit provides easy-to-use eBPF frontends
  • How to use bpftrace to trace function calls and stacks
  • How to read a combined kernel + user stack trace from an eBPF tool
  • The security implications of eBPF and the kernel lockdown feature in Linux 6.x
  • When to use strace, ltrace, gdb versus eBPF for stack analysis
✅ Prerequisites
Previous lecture: Kernel mode stack Basic GDB knowledge Linux command line C programming Linux 4.6+ or Linux 6.x system

The User Space Stack: What Is It?

Every running process has a user space stack — sometimes just called “the stack” in general programming. This is the memory region used when user-mode functions call each other. Each function call pushes a stack frame onto the stack. The frame holds the function’s local variables, the return address (where to go after the function returns), and the saved state of CPU registers.

The user space stack grows downward (towards lower memory addresses) on most architectures including x86_64 and ARM64. It starts at a high virtual address and expands downward each time a new function is called. When a function returns, its frame is popped off and the stack shrinks back.

How Is the User Space Stack Different from the Kernel Stack?

Characteristic User Space Stack Kernel Mode Stack
Used when Process runs in user mode (normal code) Process runs in kernel mode (system calls, interrupts)
Size Dynamic, can grow up to ulimit (default 8MB) Fixed at 8 or 16 KiB — never grows
Memory type Virtual memory, demand-paged Physically contiguous kernel memory
Accessible by kernel? Yes, via copy_from_user / copy_to_user Directly accessible
Corrupted by user bug? Yes (buffer overflow, etc.) Not directly — kernel stack is separate
Inspect tool gdb, bpftrace, pstack /proc/PID/stack, bpftrace

Inspecting the User Space Stack with GDB

The most reliable and widely available tool for inspecting the user space stack of a live process is GDB (GNU Debugger). GDB allows you to attach to a running process without stopping it permanently, take a backtrace snapshot, and detach — all without modifying the process.

Attaching GDB to a Live Process

The steps are straightforward. You find the process ID, attach GDB to it, print the backtrace, then detach:

# Step 1: Find the PID of the target process (e.g., bash)
$ pgrep bash
7842

# Step 2: Attach GDB to the live process (requires root or ptrace permission)
$ sudo gdb -p 7842

# Inside GDB prompt — show the backtrace of the current thread
(gdb) bt

# Output example (bash waiting for child):
# #0  0x00007f3c2a8754eb in waitpid () from /lib/x86_64-linux-gnu/libc.so.6
# #1  0x000055a3c1b03629 in ?? ()
# #2  0x000055a3c1b04cc3 in wait_for ()
# #3  0x000055a3c1b0375c in execute_command_internal ()
# #4  0x000055a3c1b039b6 in execute_command ()
# #5  0x000055a3c1adb389 in reader_loop ()
# #6  0x000055a3c1ad9b69 in main ()

# For multi-threaded processes — show all threads' stacks
(gdb) thread apply all bt

# Detach without killing the process
(gdb) detach
(gdb) quit
💡 Tip: GDB produces much better output when the binary was compiled with debug symbols (gcc -g). Without symbols, many frames show as ?? — not because GDB is broken, but because the symbol information was stripped from the binary, which is standard for production builds.

Reading the GDB Backtrace Output

Just like the kernel stack backtrace, the GDB user-space backtrace is read from bottom to top. In the example above, main() is at the bottom — it is where the program started. Moving upward, reader_loop() is the main loop of bash, then execute_command() was called, then wait_for(), and finally at the top, the process is blocked inside waitpid() — the glibc wrapper that calls the wait4 system call.

User Space Stack Call Chain — Bash Waiting for Child Process
waitpid() in libc.so  ← Currently blocked here
↑ calls
wait_for()
↑ calls
execute_command_internal()
↑ calls
execute_command()
↑ calls
reader_loop()  — bash’s main loop
↑ calls
main()  ← Program entry (oldest frame)
GDB shows: #0 = top (newest) → #N = bottom (oldest)
🔔 Note on ?? in GDB output: When you see #1 0x... in ?? (), it means GDB could not resolve the function name because the binary was stripped of debug symbols. This is very common in system binaries and is not an error. If you compile your own program with gcc -g -no-pie, GDB will show the actual function names instead.

Introduction to eBPF: The Modern Linux Tracing Revolution

eBPF stands for extended Berkeley Packet Filter. Despite its packet-filtering origins, modern eBPF is a general-purpose, in-kernel virtual machine that lets you run sandboxed programs inside the Linux kernel safely — without loading kernel modules and without modifying kernel source code. This makes it one of the most powerful additions to the Linux kernel in the last decade.

For Linux kernel developers and those studying free Linux device driver programming, eBPF opens a completely new world of observability: you can trace kernel functions, user-space functions, system calls, hardware performance counters, network events, and much more — all with minimal overhead and complete safety.

Key Characteristics of eBPF in Linux 6.x

  • eBPF programs are compiled to a bytecode that the kernel’s JIT compiler turns into native machine code — extremely fast.
  • Before loading, the kernel’s eBPF verifier checks the program exhaustively — it cannot crash the kernel, cannot loop forever, cannot access arbitrary memory.
  • Available since Linux 4.x. Significantly improved in 5.x and 6.x with new program types, map types, and CO-RE (Compile Once, Run Everywhere) support.
  • No kernel recompilation needed. No module loading (which means no kernel taint).
  • Root privilege (or CAP_BPF + CAP_PERFMON) required to load eBPF programs.
eBPF Architecture in Linux 6.x
USER SPACE
Your eBPF C program
or bpftrace script
clang / LLVM
compiles to eBPF bytecode
BCC tools / bpftrace
high-level frontends
↓ bpf() syscall
KERNEL SPACE
eBPF Verifier
Safety checks before load
JIT Compiler
Bytecode → native code
eBPF Maps
Shared data kernel↔user
kprobes / kretprobes
Kernel function tracing
uprobes / uretprobes
User function tracing
tracepoints
Static kernel probes
perf events
Hardware counters

BCC and bpftrace: Easy eBPF Frontends for Linux Developers

Writing raw eBPF programs in C and loading them manually is complex. The good news is that several high-level frontends make eBPF accessible. The two most important for kernel developers and anyone following a free Linux kernel programming course are BCC and bpftrace.

BCC (BPF Compiler Collection)

BCC is a collection of ready-to-use eBPF tools plus a Python and Lua API for writing your own. It ships with dozens of pre-built tools for CPU profiling, memory analysis, file system tracing, network analysis, and process tracing. For our purpose — stack tracing — BCC provides tools that can capture the call stacks of kernel and user-space functions as they execute.

# Install BCC tools on Ubuntu/Debian
$ sudo apt update
$ sudo apt install bpfcc-tools linux-headers-$(uname -r)

# Verify installation
$ sudo opensnoop-bpfcc --help
🔔 Note: BCC tools require the kernel headers matching your running kernel. The package linux-headers-$(uname -r) provides these. This works for distribution kernels (Ubuntu, Fedora, Debian). If you are running a custom-compiled kernel, you need to point BCC to your kernel build directory.

bpftrace: One-Line eBPF Tracing

bpftrace is a high-level tracing language for eBPF, similar in spirit to DTrace. It allows you to write powerful one-liners or short scripts that trace kernel and user-space events in real time. It is particularly elegant for stack tracing:

# Install bpftrace on Ubuntu
$ sudo apt install bpftrace

# Example: Trace every call to do_sys_openat2 and print the kernel stack
$ sudo bpftrace -e 'kprobe:do_sys_openat2 { @[kstack] = count(); }'

# Example: Trace malloc calls in a process (PID 12345) and print user stack
$ sudo bpftrace -e 'uprobe:/lib/x86_64-linux-gnu/libc.so.6:malloc /pid == 12345/ { @[ustack] = count(); }'

# Example: Trace a syscall and show BOTH kernel and user stacks
$ sudo bpftrace -e 'tracepoint:syscalls:sys_enter_write /pid == 12345/ { print(kstack); print(ustack); }'
💡 Key built-ins: In bpftrace, kstack gives the kernel call stack and ustack gives the user-space call stack at the moment the probe fires. These are available in almost any probe type.

Viewing Both Kernel and User Space Stacks Together with eBPF

One of the most powerful capabilities of the eBPF approach is that it can show you the kernel stack and the user-space stack of a process at the same instant. This is something that traditional tools like gdb and /proc/PID/stack cannot do simultaneously — you need separate tools for each. With eBPF, a single probe fires at a kernel function, captures the kernel stack from that point back to the entry, AND simultaneously captures the user-space stack of the process that triggered the call.

Understanding the Combined Stack Output

When an eBPF tool prints both stacks together, a delimiter separates the two sections. The kernel stack appears first, and below the delimiter is the user-space stack. Here is how to understand the output structure:

# Illustrative eBPF combined stack output structure:
# (Kernel stack — read bottom up)
__kmalloc_reserve
alloc_skb_with_frags
sock_alloc_send_pskb
unix_stream_sendmsg
sock_sendmsg
sock_write_iter
do_iter_readv_writev
do_iter_write
vfs_writev
do_writev
sys_writev
do_syscall_64
entry_SYSCALL_64_after_hwframe
    --                           <--- This delimiter separates kernel from user stack
# (User space stack — read bottom up)
__writev                         <--- glibc wrapper for writev syscall
[unknown]                        <--- stripped binary, no symbol info
[unknown]
eBPF Combined Stack View: Kernel + User Space at One Instant
KERNEL STACK (read bottom ↑ to top)
__kmalloc_reserve   ← Currently here (most recent)
alloc_skb_with_frags
sock_alloc_send_pskb
unix_stream_sendmsg
sock_sendmsg → sock_write_iter
do_iter_write → vfs_writev → do_writev
sys_writev → do_syscall_64
entry_SYSCALL_64_after_hwframe   ← Kernel entry (oldest)
— (delimiter: boundary between kernel and user stack)
USER SPACE STACK (read bottom ↑ to top)
__writev (glibc)   ← User space call that triggered syscall
[unknown]   ← stripped binary, no debug symbols
[unknown]   ← program entry point (stripped)
Tip: Compile your own programs with gcc -g for full symbol resolution

Why User Space Frames Often Show as [unknown]

When using eBPF tools to trace user-space stacks, you frequently see [unknown] for most frames. This happens because production binaries are typically stripped — all debug symbol information (function names, file names, line numbers) is removed before shipping to reduce file size. Without symbols, the stack unwinder has addresses but cannot look up what function those addresses correspond to.

There are two solutions:

  • Compile your own programs with -g: When you compile with gcc -g your_program.c -o your_program, debug symbols are embedded, and bpftrace/BCC will resolve frame names correctly.
  • Install debug symbol packages: Many Linux distributions provide separate debug symbol packages (e.g., libc-dbg, bash-dbg) that add symbols back to system binaries. eBPF tools can use these automatically.

eBPF Security: Lockdown and CAP_BPF in Linux 6.x

eBPF is powerful, and with power comes responsibility. Linux 6.x includes several security controls around eBPF:

Kernel Lockdown Mode

Linux 6.x includes a Kernel Lockdown feature (a Linux Security Module). When lockdown is enabled in confidentiality mode, certain eBPF operations are blocked — specifically, reading arbitrary kernel memory through eBPF programs. This protects against using eBPF to extract sensitive data from a locked-down system.

By default on most distributions, lockdown is disabled or set to integrity mode (which allows most eBPF operations). You can check the current lockdown level:

# Check current kernel lockdown level
$ cat /sys/kernel/security/lockdown
none [integrity] confidentiality

Capabilities Required for eBPF

Capability What it allows
CAP_BPF Load most eBPF programs and access eBPF maps (Linux 5.8+)
CAP_PERFMON Use eBPF for performance monitoring and tracing (Linux 5.8+)
CAP_SYS_ADMIN Older kernels: all eBPF operations; modern kernels: network eBPF programs
⚠ Security Warning: Never run untrusted eBPF programs on a production system. While the eBPF verifier prevents crashes, a malicious eBPF program with appropriate privileges could be used for exfiltration or surveillance. Always verify the source of eBPF tools you run.

Choosing the Right Tool: strace, ltrace, GDB, or eBPF?

Tool What it traces Overhead Best Use Case
strace System calls — names, arguments, return values High (ptrace overhead) Debugging what syscalls a process makes
ltrace Library function calls High (ptrace overhead) Tracing glibc and shared library calls
gdb User-space stack of any process Medium (stops process briefly) Snapshot debugging, interactive analysis
/proc/PID/stack Kernel stack of any process Very low (read-only snapshot) Quick kernel-side debugging
bpftrace Kernel + user stacks simultaneously Low (JIT compiled, in-kernel) Production tracing, complex event correlation
BCC tools Kernel + user stacks + system events Low to medium Rich pre-built analysis tools

Best Practices for Stack Tracing in Linux Kernel Development

  1. Start with /proc/PID/stack: It is the fastest, zero-overhead way to check where a process is blocked in the kernel. Use it first.
  2. Use GDB for user-space analysis: For understanding call chains in your own programs or in programs compiled with debug symbols, GDB bt is reliable and interactive.
  3. Use bpftrace for dynamic, production-safe tracing: When you need to trace behaviour across many processes or over time without stopping anything, bpftrace one-liners are the right choice on Linux 6.x.
  4. Always compile kernel modules and drivers with -g during development: This ensures stack traces involving your code show proper function names.
  5. Combine strace and /proc/PID/stack: strace shows you which system call was made. /proc/PID/stack shows you where inside the kernel that call is now executing. Together they give the full picture.
  6. Learn to read ?? intelligently: In user space, ?? usually means stripped symbols. In kernel space, ?? means an invalid frame artifact. Neither is a tool failure — both are expected.

Performance Considerations for eBPF Stack Tracing

eBPF is designed to be low overhead, but stack tracing in particular has some costs to be aware of:

  • Stack unwinding cost: Walking the call stack at probe fire time takes CPU cycles proportional to stack depth. Tracing every function call on a deep stack in a hot path can add measurable overhead.
  • Map operations: Storing stacks in eBPF maps (the typical pattern for aggregation) involves hash operations. Use BPF_MAP_TYPE_STACK_TRACE maps for efficient stack storage.
  • Sampling instead of tracing all events: For high-frequency events like malloc on a busy server, trace only 1-in-N calls using a counter check in the eBPF program to avoid saturating the output buffer.
  • Frame pointer compilation: eBPF stack unwinding on x86_64 works best when binaries are compiled with -fno-omit-frame-pointer. Modern compilers default to omitting frame pointers for performance, but this breaks simple stack unwinding. eBPF can use DWARF-based unwinding as a fallback, but it is slower.

🏆 Key Takeaways

  • The user space stack is dynamic, can grow large, and holds user-mode function frames. It is separate from the kernel mode stack.
  • Use GDB bt to attach to a live process and snapshot its user-space call chain.
  • eBPF is the modern Linux observability technology — it runs sandboxed programs inside the kernel with zero modifications to the kernel or target processes.
  • bpftrace and BCC are the two primary eBPF frontends for practical use in Linux kernel development and device driver work.
  • eBPF can show kernel and user stacks simultaneously, separated by a delimiter — a capability no traditional tool provides.
  • [unknown] frames in user-space stacks mean the binary was stripped. Compile with -g or install debug packages to resolve them.
  • Linux 6.x uses CAP_BPF and CAP_PERFMON capabilities for finer-grained eBPF permission control.
  • Choose your tool based on the situation: /proc/PID/stack for quick kernel checks, GDB for user-space snapshots, bpftrace for production dynamic tracing.

Frequently Asked Questions (FAQ)

Q1: What is the difference between BCC and bpftrace?

BCC (BPF Compiler Collection) is a toolkit of ready-made tools plus a Python/Lua API for writing custom eBPF programs. It is powerful but requires Python and has higher setup complexity. bpftrace is a simpler, C-like scripting language designed for quick one-liners and short scripts. For beginners, start with bpftrace. For complex, production-grade tools, use BCC.

Q2: Does using bpftrace or BCC affect the performance of the traced process?

eBPF tools are designed for low overhead. For infrequent events (rare syscalls, error paths), the impact is negligible. For extremely high-frequency events (millions of calls per second), the overhead from the eBPF probe firing can become measurable. Use sampling (trace every Nth event) in hot paths to keep overhead acceptable.

Q3: Can I use eBPF without kernel headers installed?

With modern BPF CO-RE (Compile Once, Run Everywhere) and BTF (BPF Type Format), you can compile an eBPF program once and run it on any kernel that has BTF support (Linux 5.2+). You no longer need the specific kernel headers at runtime. bpftrace 0.16+ and libbpf-based BCC tools support CO-RE.

Q4: Why does my bpftrace script fail with “permission denied” even as root?

Check if kernel lockdown is enabled: cat /sys/kernel/security/lockdown. If it shows confidentiality, certain eBPF operations are blocked even for root. Also verify that CONFIG_BPF_SYSCALL=y and CONFIG_KPROBES=y are set in your kernel configuration.

Q5: What is the difference between kprobes and tracepoints in eBPF?

kprobes are dynamic — you can attach them to almost any kernel function at runtime, even functions that have no special instrumentation. Tracepoints are static — they are pre-defined hook points added by kernel developers at specific locations. Tracepoints are more stable across kernel versions; kprobes are more flexible but may break if the kernel function name or signature changes.

Q6: What does -fno-omit-frame-pointer mean and why does it matter for eBPF?

The frame pointer is a CPU register (RBP on x86_64) that points to the current stack frame’s base. Modern compilers omit maintaining this register to free it for other uses (a small performance win). But without frame pointers, walking the stack chain requires DWARF debug information, which is slower. For accurate eBPF user-space stack traces, compile your programs with gcc -fno-omit-frame-pointer.

Q7: Can eBPF replace kernel modules for device driver development?

Not for full device driver functionality. eBPF programs cannot directly access hardware, request IRQs, use DMA, or perform the full range of kernel operations that a driver needs. However, eBPF is extremely useful for tracing and debugging your device driver code — you can trace function calls inside your loaded module with kprobes without modifying the driver source.

Q8: Is strace or eBPF better for debugging system calls?

strace is simpler and shows full argument details for every syscall. But it uses ptrace, which stops the process for each syscall — significant overhead that can change timing and hide race conditions. eBPF-based syscall tracing has much lower overhead and does not stop the process. For production debugging or latency-sensitive tracing, eBPF wins. For simple development debugging, strace remains convenient.

Conclusion

In this lecture from our free Linux kernel programming course, you learned how to inspect the user-space stack of a live process using GDB, and you were introduced to eBPF — the technology that defines modern Linux observability. You now understand how eBPF programs work, what BCC and bpftrace provide, and how a combined kernel + user-space stack trace looks. You also learned when to choose each tool, and you understand the security controls Linux 6.x applies to eBPF through capability checks and kernel lockdown.

Together, the two lectures in this series — kernel mode stack inspection and user-space stack tracing with eBPF — give you a complete picture of Linux process execution: what the kernel is doing and what user code triggered it, all at the same time. This is foundational knowledge for Linux device driver development, kernel debugging, and performance analysis.

💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →