Skip to main content

Comprehensive Python debugging and analysis toolkit for NuttX RTOS - includes GDB extensions, memory analysis, crash diagnostics, trace parsing, and remote debugging capabilities

Project description

PyNuttX - NuttX/Vela GDB Extension Toolkit

Python Version License Version

A comprehensive Python-based GDB debugging toolkit for NuttX RTOS, providing powerful extensions for thread analysis, memory debugging, crash diagnostics, filesystem inspection, and much more.

Production Ready: Extensively used in Xiaomi Vela OS for embedded systems debugging, crash analysis, and performance profiling.


๐Ÿ“‹ Table of Contents


๐ŸŽฏ Introduction

PyNuttX implements numerous custom GDB commands under nuttx/tools/pynuttx/, primarily focused on:

  • Thread Management: Thread inspection, backtrace, context switching
  • Memory Analysis: Memory dumps, leak detection, heap validation
  • System Inspection: Process status, filesystem, network, sensors, and more

Key Features

โœ… 100+ Custom GDB Commands covering all aspects of embedded debugging โœ… Post-Mortem Analysis via coredump and memory dump files โœ… Multi-Architecture Support: ARM, RISC-V, Xtensa, Tricore, and more โœ… Production Tested in commercial IoT products (Xiaomi Vela OS) โœ… Extensible Framework for custom command development


๐Ÿš€ Installation & Setup

Prerequisites

GDB Version Requirement:

  • GDB 11 or higher with python enabled is required
# Use prebuilt gdb-multiarch (recommended)
trunk/prebuilts/gcc/linux/gdb-multiarch/bin/gdb-multiarch

# Special architectures require specific GDB:
# - Tricore: prebuilts/gcc/linux/tricore/bin/tricore-gdb
# - Xtensa: xtensa-esp32s3-elf-gdb (xt-gdb does NOT support Python extensions)

โš ๏ธ Note: Some vendor toolchains may have compilation issues causing missing libpython support, preventing Python module usage.

Install Dependencies

Install required Python packages:

# Install dependencies (Linux)
/usr/bin/python3 -m pip install -r nuttx/tools/pynuttx/requirements.txt

# Or via pip if pynuttx is installed
pip install pynuttx

Important Notes

  1. Code-Tool Compatibility: โš ๏ธ Always match your code version with tool version

    • Don't use stable tools to analyze dev branch code
    • Keep tool and firmware in sync
  2. Architecture-Specific Tools: Use the correct GDB for your target architecture

    • Tricore: tricore-gdb
    • Xtensa: xtensa-esp32s3-elf-gdb (see reference)
    • ARM: gdb-multiarch or arm-none-eabi-gdb

๐Ÿ“ฅ Loading GDB Extensions

Method 1: Load via -ex Parameter (Recommended)

# Start GDB with automatic loading
gdb-multiarch nuttx/vela_ap.elf -ex "source nuttx/tools/pynuttx/gdbinit.py"

# Or load manually in GDB shell
(gdb) source nuttx/tools/pynuttx/gdbinit.py

Method 2: Import as Python Module

# Set PYTHONPATH so Python can find the module
export PYTHONPATH=/myworkspace/nuttx/tools/pynuttx:$PYTHONPATH

# Option 1: Load during GDB startup
gdb-multiarch nuttx/nuttx.elf -ex "py import nxgdb"

# Option 2: Import after GDB starts
(gdb) py import nxgdb

Verify Installation

# Check available custom commands
(gdb) help user-defined

# Get help for specific command
(gdb) memdump --help
(gdb) info nxthread --help

๐ŸŽช Usage Scenarios

PyNuttX works in multiple debugging contexts:

Scenario Description Use Case
Online Debugging Live device via JTAG/SWD JLink, OpenOCD, TRACE32
GDB Stub Serial/USB debugging Embedded GDB stub on target
Post-Mortem Crash dump analysis Load memory dumps via gdbserver.py
Coredump ELF coredump files Analyze with gdb <elf> <coredump>

Example: Connect to Live Target

# Via OpenOCD (JTAG/SWD)
openocd -f interface/jlink.cfg -f target/stm32f4x.cfg &
gdb-multiarch nuttx -ex "target remote :3333" -ex "source tools/pynuttx/gdbinit.py"

# Via Serial GDB Stub
gdb-multiarch nuttx -ex "target remote /dev/ttyUSB0" -ex "source tools/pynuttx/gdbinit.py"

Example: Post-Mortem Analysis

# Start gdbserver with memory dumps
python3 tools/pynuttx/gdbserver.py \
    -a arm \
    -e nuttx.elf \
    -r ram.bin:0x20000000 psram.bin:0x60000000 \
    -p 6667

# Connect and analyze
gdb-multiarch nuttx.elf -ex "target remote :6667" -ex "source tools/pynuttx/gdbinit.py"

๐Ÿ“š Command Reference

๐Ÿงต Thread & Scheduling

Command Description Documentation Status
info nxthread Display NuttX threads with Vela-specific data (replaces info threads for better NuttX integration) thread โœ… Done
nxthread <id> Switch to specific thread context thread โœ… Done
setregs <addr> Restore register context from saved state - โœ… Done
deadlock Detect deadlock conditions - โœ… Done
critmon Critical section monitor (same as device critmon) shell โœ… Done
ps Process status (same as device ps) - โœ… Done
crash busyloop Detect busy-loop threads Crash Analysis โœ… Done

Example:

(gdb) info nxthread
  PID GROUP PRI POLICY   TYPE    NPX STATE   EVENT      SIGMASK  STACKBASE  STACKSIZE   USED  FILLED  COMMAND
    0     0   0 FIFO     Kthread -   Running            00000000 0x00000000         0      0    0.0%!  Idle_Task
    1     1 100 RR       Task    -   Waiting Semaphore  00000000 0x20600000      2048    824   40.2%   nsh_main

(gdb) nxthread 1
(gdb) bt

๐Ÿ’พ Memory Management

Command Description Documentation Status
memdump Dump memory allocation info (same as device memdump) memdump โœ… Done
memleak Detect memory leaks by analyzing unreachable allocations memleak โœ… Done
memcheck Verify heap integrity and core data structures memcheck โœ… Done
memfind <pattern> Search for pattern in heap/bss/data (auto address range) memfind โœ… Done
kasan KASAN helper to check address tag accessibility kasan โœ… Done
memclassify Classify memory by backtrace to identify module usage memclassify โœ… Done
mm visualize Visualize memory state with size distribution charts memmap & visualize โœ… Done
dump ram Export memory data to file dump ram โœ… Done
mm range Show memory regions in current system memrange โœ… Done
crash stackoverflow Detect stack overflow conditions Crash Analysis โœ… Done

Example:

# Show top 20 memory consumers without backtrace (faster)
(gdb) memdump --top 20 --no-backtrace

# Detect memory leaks
(gdb) memleak
Searching for leaked memory, please wait a moment...
Leak catch!, use '*' mark pid is not exist:
   CNT   PID        Size    Sequence    Address Callstack
    34    30         256        8810 0x3d52f080  [0x00c3210e0] <malloc+12>
...

# Check heap integrity
(gdb) mm check

# Visualize memory fragmentation
(gdb) mm visualize

๐Ÿ–ฅ๏ธ System & Diagnostics

Command Description Documentation Status
foreach list Traverse NuttX linked lists list โœ… Done
tlsdump Dump and verify TLS info / task info integrity tlsdump โœ… Done
nxgcore Pull device coredump (wraps GDB's gcore) nxgcore โœ… Done
free Show memory info (same as device free) shell โœ… Done
uname Display firmware version - โœ… Done
irqinfo Show IRQ statistics (same as device irqinfo) - โœ… Done
dmesg Display kernel log (ramlog) - โœ… Done
resetcause Show last reset reason - ๐Ÿšง Not started
wdog Show registered watchdog timer info - โœ… Done
worker Show registered worker info - โœ… Done
noteram View note trace data, perform notedump operations noteram โœ… Done
notesnap View task switching state before crash notesnap โœ… Done
target nxstub Connect to gdbserver via Vela proxy (native GDB thread support) target nxstub โœ… Done
diagnose Run all diagnostic commands, generate JSON report diagnose โœ… Done
watchdog View/control watchdog status during debugging - ๐Ÿšง Ongoing
circbuf View circular buffer state (libc/misc/lib_circbuf.c) - โœ… Done
pmconfig View PM configuration info pmconfig โœ… Done
elfimport Import ELF symbols elfimport โœ… Done
crash blame Analyze crash probability by module (for initial JIRA assignment) Crash Analysis ๐Ÿšง Ongoing
crash thread Identify which thread caused the crash Crash Analysis โœ… Done
crash memory Determine if crash was caused by memory issues Crash Analysis ๐Ÿšง Ongoing

Example:

# View kernel log
(gdb) dmesg

# Generate comprehensive diagnostic report
(gdb) diagnose

# Check system info
(gdb) uname
(gdb) free

๐Ÿ—‚๏ธ Filesystem

Command Description Documentation Status
fdinfo Show open file descriptors per task fdinfo โœ… Done
mount Display mount information mount โœ… Done
foreach inode Traverse inode tree foreach inode โœ… Done
info shm Show shared memory usage info shm โœ… Done
info yaffs View YAFFS partition context info yaffs โœ… Done
info romfs View ROMFS partition context info romfs โœ… Done
info fatfs View FAT filesystem partition context info fatfs โœ… Done
info lrofs View LROFS partition context info lrofs โœ… Done
unqlite tools View unqlite memory usage - ๐Ÿ“… Q1

Example:

# Check open files
(gdb) fdinfo

# View mount points
(gdb) mount

# Inspect filesystem partition
(gdb) info fatfs /dev/mmcsd0

๐ŸŒ Network & Connectivity

Command Description Documentation Status
netstats Print IOB and protocol/socket info net โœ… Done
netcheck Run network diagnostics net โœ… Done
btsocket Print Bluetooth IPC server/client cache queue btdiag โœ… Done
btdev Print Bluetooth adapter BLE/BREDR device info btdiag โœ… Done
bttimeval Print Bluetooth thread peak timestamp btdiag โœ… Done
btstack Print protocol stack list (e.g., GATT pending list) btdiag โœ… Done
btsnoop Convert Bluetooth /dev/tty circular buffer to HCI log btdiag โœ… Done
lyrainfo Display Lyra Lite connection, mesh, and transmission info lyrainfo โœ… Done

Example:

# Network statistics
(gdb) netstats

# Bluetooth diagnostics
(gdb) btdev
(gdb) btsnoop /dev/ttyBT0 output.hci

๐ŸŽจ Graphics (LVGL)

Command Description Documentation Status
imagecache View image cache memory with allocation backtrace - ๐Ÿšง Not started
info draw_unit View current draw unit info, verify rendering context lvgl โœ… Done
info style View LVGL object style and type information lvgl โœ… Done
dump obj Display LVGL object tree lvgl โœ… Done
show fb Display framebuffer content - ๐Ÿšง Not started

๐Ÿ“ก RPC & IPC

Command Description Documentation Status
rpmsgservice View RPMSG service information rpmsgdump โœ… Done
rptun View RPMSG virtio shared memory buffer - ๐Ÿšง Ongoing
rpmsgport View RPMSG port memory and debug info - ๐Ÿ“… Mar 31
rpmsg trace RPMSG trace enhancement with visualization - ๐Ÿ“… Mar 31

๐Ÿ“Š Sensors

Command Description Documentation Status
uorb View /dev/uorb/ node subscriptions and publications uorb โœ… Done

๐ŸŽฌ Media

Command Description Documentation Status
mediadump View pipeline filter EOF state and internal dump data mediadump โœ… Done

๐ŸชŸ XMS (Window Manager)

Command Description Documentation Status
wm dump Dump application window state and shared memory - ๐Ÿšง Ongoing

๐Ÿ“ฑ Application Frameworks

Command Description Documentation Status
dump aiotmemory Print Quick App JS memory usage dump aiotmemory โœ… Done

๐Ÿ”ง Development Tools

Command Description Documentation Status
profile Analyze Python function call time (performance profiling) profile โœ… Done
viztracer Capture Python trace data, view with Perfetto - โœ… Done
time Measure Python tool execution time (like shell time) - โœ… Done
addr2line Convert addresses/variables/expressions to backtrace utils โœ… Done
hexdump Dump memory at address with printable characters - โœ… Done
debugpy Debug Python code in IDE debugpy โœ… Done

๐Ÿš€ Quick Start Examples

Example 1: Memory Leak Detection

# Connect to target or load memory dump
gdb-multiarch nuttx.elf -ex "target remote :3333" -ex "source tools/pynuttx/gdbinit.py"

# Run memory leak detection
(gdb) memleak
Searching for leaked memory, please wait a moment
Searching global symbol in: /path/to/nuttx.elf
Search all memory use 28.98 seconds

Leak catch!, use '*' mark pid is not exist:
   CNT   PID        Size    Sequence    Address Callstack
    34    30         256        8810 0x3d52f080
        [0x00c3210e0] <malloc+12>
        [0x00c47c904] <lv_malloc+6>
        ...

Alloc 44 count, have 8 some backtrace leak, total leak memory is 10112 bytes

Example 2: Crash Analysis

# After a crash, connect to device
gdb-multiarch nuttx.elf -ex "target remote /dev/ttyUSB0" -ex "source tools/pynuttx/gdbinit.py"

# View kernel log
(gdb) dmesg
[  123.456] Assertion failed at file:line

# Check thread status
(gdb) info nxthread

# Identify crashing thread
(gdb) crash thread

# Run comprehensive diagnostics
(gdb) diagnose

# Check for memory corruption
(gdb) memcheck

# Detect stack overflow
(gdb) crash stackoverflow

Example 3: Post-Mortem Analysis

# 1. Collect memory dumps from crashed device
(gdb) dump memory ram.bin 0x20000000 0x20100000
(gdb) dump memory psram.bin 0x60000000 0x64000000

# 2. Start gdbserver with memory files
python3 tools/pynuttx/gdbserver.py \
    -a arm \
    -e nuttx.elf \
    -r ram.bin:0x20000000 psram.bin:0x60000000 \
    -p 6667

# 3. Connect and analyze
gdb-multiarch nuttx.elf \
    -ex "target remote :6667" \
    -ex "source tools/pynuttx/gdbinit.py"

# 4. Analyze the crash
(gdb) info nxthread
(gdb) bt
(gdb) memdump --top 20

Example 4: Filesystem Debugging

# Check open file descriptors
(gdb) fdinfo

# View mount points
(gdb) mount

# Inspect filesystem details
(gdb) info fatfs /dev/mmcsd0

# Traverse inode tree
(gdb) foreach inode

Example 5: Network Debugging

# View network statistics
(gdb) netstats

# Run network diagnostics
(gdb) netcheck

# Check Bluetooth status
(gdb) btdev
(gdb) btsocket

๐ŸŽ“ Advanced Features

Save Command Output to File

# Use pipe to save output
(gdb) pipe info nxthread | tee output.log
(gdb) pipe memdump | tee memdump.txt

View All Custom Commands

# List all user-defined commands
(gdb) help user-defined

# Get help for specific command
(gdb) <command> --help

GDB Proxy for Native Thread Support

# Connect via nxstub for better thread awareness
(gdb) target nxstub --proxy :1234 # For example, connect to qemu
(gdb) info threads  # Now shows NuttX threads correctly

Comprehensive Diagnostics

# Run all diagnostic commands and generate JSON report
(gdb) diagnose

# This automatically runs:
# - Thread analysis
# - Memory checks
# - System state inspection
# - Network diagnostics
# - And more...

โ“ FAQ

Q: How do I add my own custom commands?

A: Follow the GDB Python API to create custom commands.

Example:

import gdb

class MyCommand(gdb.Command):
    """My custom command description"""

    def __init__(self):
        super().__init__("mycommand", gdb.COMMAND_USER)

    def invoke(self, arg, from_tty):
        print("Hello from my command!")

MyCommand()

Save as mycommand.py and load:

(gdb) source mycommand.py
(gdb) mycommand

Q: Can thread functionality display in VSCode or other frontends?

A: Not yet perfectly. Current implementation replaces same-named commands which doesn't perfectly adapt to frontend tools. Frontend adaptation is under development.

Q: GDB version error or Python module not found?

A:

  1. Ensure GDB 11+ is installed
  2. Check GDB Python support: gdb --batch -ex "python import sys; print(sys.version)"
  3. Use prebuilt GDB from Vela repository
  4. Install dependencies: pip install -r requirements.txt

Q: Commands are slow on embedded target?

A: Use post-mortem analysis instead:

  1. Dump memory from target
  2. Use gdbserver.py to load dumps
  3. Analyze offline (much faster!)

Q: How to debug multi-core systems?

A:

  1. Dump memory from each core separately
  2. Load each core's memory with corresponding ELF file
  3. Use separate GDB sessions or load all in one gdbserver instance

Q: Code and tool version mismatch?

A: โš ๏ธ Always keep tool and firmware versions synchronized!

  • Use same branch for both code and tools
  • Don't mix stable branch tools with dev branch code

๐Ÿค Contributing

Contributions are welcome! PyNuttX is part of the Apache NuttX project.

Development Setup

# Clone repository
git clone https://github.com/apache/nuttx.git
cd nuttx/tools/pynuttx

# Install in development mode
pip install -e .

# Install development dependencies
pip install -r requirements.txt

Adding New Commands

  1. Create your command in appropriate module under nxgdb/
  2. Add documentation in docs/
  3. Add tests in tests/
  4. Submit pull request

See Contributing Guide for details.


๐Ÿ“– Resources


๐Ÿ“„ License

Licensed under the Apache License, Version 2.0. See LICENSE for details.


๐Ÿ™ Acknowledgments

Maintained by the Apache NuttX community and extensively developed by the Xiaomi Vela team.

Special Thanks To:

  • All contributors and maintainers
  • Xiaomi Vela OS team for production testing and enhancements
  • The embedded systems community

For support and questions, please refer to the NuttX Documentation or contact the community via mailing lists.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pynuttx-0.0.6a6.tar.gz (281.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pynuttx-0.0.6a6-py3-none-any.whl (361.7 kB view details)

Uploaded Python 3

File details

Details for the file pynuttx-0.0.6a6.tar.gz.

File metadata

  • Download URL: pynuttx-0.0.6a6.tar.gz
  • Upload date:
  • Size: 281.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.14

File hashes

Hashes for pynuttx-0.0.6a6.tar.gz
Algorithm Hash digest
SHA256 f5189539c7b9df6bcffd39ce2d59d5f209ea0c0c5d93cf8a3866bf6198761019
MD5 77b6566c6817a44adfc409980d8bb34f
BLAKE2b-256 c0e137d8b4a5356769d890d60f5a9c3d48a9184440a388a7d3c3d8fc7ecb4bd2

See more details on using hashes here.

File details

Details for the file pynuttx-0.0.6a6-py3-none-any.whl.

File metadata

  • Download URL: pynuttx-0.0.6a6-py3-none-any.whl
  • Upload date:
  • Size: 361.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.14

File hashes

Hashes for pynuttx-0.0.6a6-py3-none-any.whl
Algorithm Hash digest
SHA256 3f25d454567110e2fe9f7d87e236ea9285ab65c669e5755fb9679ab9ef6a2ea7
MD5 0f504c0fae174beebe40174131c0d1cd
BLAKE2b-256 206b99f89c058363d82202fcd92c82c0c8e0c3e45210fc932de2f009fc1cbeea

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page