You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nuttx.apache.org by "xiaoxiang781216 (via GitHub)" <gi...@apache.org> on 2026/03/13 15:02:35 UTC

[PR] tools: replace showstack.sh with stackusage.py. [nuttx]

xiaoxiang781216 opened a new pull request, #18538:
URL: https://github.com/apache/nuttx/pull/18538

   ## Summary
   
   * Replace `tools/showstack.sh` with `tools/stackusage.py` for puncover-like
     static stack analysis with call graph based worst-case estimation.
   * Combines GCC `-fstack-usage` `.su` files with `objdump` call graph to compute
     worst-case total stack depth (self + deepest callee chain).
   * Supports all 18 NuttX architectures (ARM, ARM64, RISC-V, x86, Xtensa, MIPS,
     AVR, z80, z16, OpenRISC, SPARC, TriCore, HC, Renesas, CEVA, etc.).
   * Flags uncertain cases: dynamic/alloca, recursion, indirect calls (function
     pointers), and missing `.su` data.
   * Summary reasons by default, `--detail` for full call chain info.
   * Adds `Documentation/debugging/stackusage.rst`.
   
   ## Impact
   
   * New feature added? YES — `stackusage.py` with call graph analysis replaces
     the simple `showstack.sh` which only sorted `.su` files by size.
   * User impact? YES — `showstack.sh` removed, use `stackusage.py` instead.
   * Build impact? NO
   * Hardware impact? NO
   * Documentation update needed? YES — included (`stackusage.rst`).
   * Security implications? NO
   * Backward compatibility? `showstack.sh` is removed and replaced by `stackusage.py`.
   
   ## Testing
   
   Build Host(s): Linux x86_64, GCC (arm-none-eabi-gcc)
   Target(s): arm, nucleo-f429zi:trace (CONFIG_STACK_USAGE=y)
   
   Testing logs after change:
   ```
   $ python3 tools/stackusage.py -n 20 -d arm-none-eabi-objdump -e nuttx .
   
   Function                       Self  Total     File:Line                          Reasons
   -----------------------------  ----  -----  -  ---------------------------------  ---------------------------
   nxtask_start                   32    1180   *  task/task_start.c:68               indirect, recursion, no .su
   noteram_read                   320   1180   *  note/noteram_driver.c:471          no .su, recursion, indirect
   start                          0     1156   *  armv7-m/arm_vectors.c:61           no .su, recursion, indirect
   __start                        16    1156   *  chip/stm32_start.c:114             no .su, recursion, indirect
   nxtask_startup                 24    1148   *  sched/task_startup.c:58            indirect, recursion, no .su
   nx_start                       24    1140   *  include/nuttx/init.h:107           no .su, recursion, indirect
   group_cancel_children_handler  24    1132   *  group/group_killchildren.c:93      indirect, recursion, no .su
   dhcpc_showusage                0     1124   *                                     no .su, recursion, indirect
   telnetd_main                   0     1124   *                                     no .su, recursion, indirect
   renew_main                     0     1124   *                                     no .su, recursion, indirect
   exit                           16    1124   *  include/stdlib.h:169               indirect, recursion, no .su
   show_usage                     0     1124   *                                     no .su, indirect, recursion
   trace_main                     0     1124   *                                     no .su, recursion, indirect
   ping_main                      0     1124   *                                     no .su, recursion, indirect
   nsh_consoleexit                0     1124   *                                     no .su, indirect, recursion
   nx_bringup                     8     1116   *  init/nx_bringup.c:496              no .su, recursion, indirect
   task_setcancelstate            24    1108   *  include/sched.h:236                indirect, recursion, no .su
   pthread_cancel                 24    1108   *  include/pthread.h:571              indirect, recursion, no .su
   nx_workqueues                  8     1108   *  init/nx_bringup.c:191              no .su, recursion, indirect
   work_start_highpri             16    1100   *  wqueue/kwork_thread.c:555          no .su, recursion, indirect
   ```
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "linguini1 (via GitHub)" <gi...@apache.org>.
linguini1 commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4057296584

   > > Why is copilot reviewing this PR? Is the feature enabled on the NuttX repo?
   > 
   > I request Coplit review my patch
   
   Okay! Makes sense, thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "xiaoxiang781216 (via GitHub)" <gi...@apache.org>.
xiaoxiang781216 commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4057268164

   > Why is copilot reviewing this PR? Is the feature enabled on the NuttX repo?
   
   I request Coplit review my patch


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#discussion_r2931838868


##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)

Review Comment:
   The call-site matcher hard-requires a literal tab (`r\"\\t\"`) before the mnemonic. Many `objdump -d` formats use variable spaces (or different tab placement) depending on toolchain/arch, which can cause the call graph to be empty/incomplete and make totals misleading. Consider allowing generic leading whitespace (e.g., `\\s+`) before the mnemonic (while still keeping the pattern anchored tightly enough to avoid matching non-instruction text).



##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)
+
+# Direct call target: optional hex address then <function_name>
+DIRECT_TARGET_RE = re.compile(r"(?:[0-9a-fA-F]+\s+)?<([^>+-]+)(?:[+-][^>]*)?>")
+
+
+def parse_su_files(dirs):
+    """Parse all .su files under given directories.
+
+    Returns dict mapping function name to info dict with keys:
+      file, line, self, qualifier, reasons
+    """
+
+    funcs = {}
+    for d in dirs:
+        for root, _, files in os.walk(d):
+            for f in files:
+                if not f.endswith(".su"):
+                    continue
+                path = os.path.join(root, f)
+                with open(path) as fh:
+                    for line in fh:
+                        line = line.rstrip("\n")
+                        m = SU_LINE_RE.match(line)
+                        if not m:
+                            continue
+
+                        filename = m.group(1)
+                        lineno = m.group(2)
+                        funcname = m.group(4)
+                        size = int(m.group(5))
+                        qualifier = m.group(6)
+
+                        reasons = []
+                        if "dynamic" in qualifier:
+                            if "bounded" in qualifier:
+                                reasons.append("dynamic stack (bounded estimate)")
+                            else:
+                                reasons.append("dynamic stack (alloca/VLA)")
+
+                        # Keep entry with largest self size per function
+                        if funcname in funcs and funcs[funcname]["self"] >= size:
+                            continue
+
+                        funcs[funcname] = {
+                            "file": filename,
+                            "line": lineno,
+                            "self": size,
+                            "qualifier": qualifier,
+                            "reasons": reasons,
+                        }
+    return funcs
+
+
+def parse_call_graph(objdump_bin, elf_path):
+    """Build call graph from objdump disassembly.
+
+    Returns dict mapping caller -> set of (callee_name_or_None, is_indirect).
+    """
+
+    result = subprocess.run(
+        [objdump_bin, "-d", elf_path],
+        capture_output=True,
+        text=True,
+    )
+
+    if result.returncode != 0:
+        print(
+            "Error running objdump: %s" % result.stderr.strip(),
+            file=sys.stderr,
+        )
+        sys.exit(1)
+
+    graph = {}
+    current_func = None
+
+    for line in result.stdout.splitlines():

Review Comment:
   `subprocess.run(..., capture_output=True)` buffers the entire disassembly in memory, which can be very large for NuttX ELFs and may impact runtime/memory significantly. To reduce peak memory, prefer streaming parsing via `subprocess.Popen(stdout=PIPE, ...)` and iterate over output lines as they are produced.



##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)
+
+# Direct call target: optional hex address then <function_name>
+DIRECT_TARGET_RE = re.compile(r"(?:[0-9a-fA-F]+\s+)?<([^>+-]+)(?:[+-][^>]*)?>")
+
+
+def parse_su_files(dirs):
+    """Parse all .su files under given directories.
+
+    Returns dict mapping function name to info dict with keys:
+      file, line, self, qualifier, reasons
+    """
+
+    funcs = {}
+    for d in dirs:
+        for root, _, files in os.walk(d):
+            for f in files:
+                if not f.endswith(".su"):
+                    continue
+                path = os.path.join(root, f)
+                with open(path) as fh:
+                    for line in fh:
+                        line = line.rstrip("\n")
+                        m = SU_LINE_RE.match(line)
+                        if not m:
+                            continue
+
+                        filename = m.group(1)
+                        lineno = m.group(2)
+                        funcname = m.group(4)
+                        size = int(m.group(5))
+                        qualifier = m.group(6)
+
+                        reasons = []
+                        if "dynamic" in qualifier:
+                            if "bounded" in qualifier:
+                                reasons.append("dynamic stack (bounded estimate)")
+                            else:
+                                reasons.append("dynamic stack (alloca/VLA)")
+
+                        # Keep entry with largest self size per function
+                        if funcname in funcs and funcs[funcname]["self"] >= size:
+                            continue
+
+                        funcs[funcname] = {
+                            "file": filename,
+                            "line": lineno,
+                            "self": size,
+                            "qualifier": qualifier,
+                            "reasons": reasons,
+                        }
+    return funcs
+
+
+def parse_call_graph(objdump_bin, elf_path):
+    """Build call graph from objdump disassembly.
+
+    Returns dict mapping caller -> set of (callee_name_or_None, is_indirect).
+    """
+
+    result = subprocess.run(
+        [objdump_bin, "-d", elf_path],
+        capture_output=True,
+        text=True,
+    )

Review Comment:
   `subprocess.run(..., capture_output=True)` buffers the entire disassembly in memory, which can be very large for NuttX ELFs and may impact runtime/memory significantly. To reduce peak memory, prefer streaming parsing via `subprocess.Popen(stdout=PIPE, ...)` and iterate over output lines as they are produced.



##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)
+
+# Direct call target: optional hex address then <function_name>
+DIRECT_TARGET_RE = re.compile(r"(?:[0-9a-fA-F]+\s+)?<([^>+-]+)(?:[+-][^>]*)?>")
+
+
+def parse_su_files(dirs):
+    """Parse all .su files under given directories.
+
+    Returns dict mapping function name to info dict with keys:
+      file, line, self, qualifier, reasons
+    """
+
+    funcs = {}
+    for d in dirs:
+        for root, _, files in os.walk(d):
+            for f in files:
+                if not f.endswith(".su"):
+                    continue
+                path = os.path.join(root, f)
+                with open(path) as fh:
+                    for line in fh:
+                        line = line.rstrip("\n")
+                        m = SU_LINE_RE.match(line)
+                        if not m:
+                            continue
+
+                        filename = m.group(1)
+                        lineno = m.group(2)
+                        funcname = m.group(4)
+                        size = int(m.group(5))
+                        qualifier = m.group(6)
+
+                        reasons = []
+                        if "dynamic" in qualifier:
+                            if "bounded" in qualifier:
+                                reasons.append("dynamic stack (bounded estimate)")
+                            else:
+                                reasons.append("dynamic stack (alloca/VLA)")
+
+                        # Keep entry with largest self size per function
+                        if funcname in funcs and funcs[funcname]["self"] >= size:
+                            continue
+
+                        funcs[funcname] = {
+                            "file": filename,
+                            "line": lineno,
+                            "self": size,
+                            "qualifier": qualifier,
+                            "reasons": reasons,
+                        }

Review Comment:
   Keying `.su` entries only by `funcname` can conflate distinct functions that share the same name (notably `static` functions in different translation units), producing objectively incorrect self/total values. If disambiguation by address isn’t feasible, a concrete mitigation is to detect duplicates (same `funcname` with different `file:line`) and mark the function as uncertain/ambiguous (and/or keep a list of definitions) rather than silently picking the largest.
   



##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)
+
+# Direct call target: optional hex address then <function_name>
+DIRECT_TARGET_RE = re.compile(r"(?:[0-9a-fA-F]+\s+)?<([^>+-]+)(?:[+-][^>]*)?>")
+
+
+def parse_su_files(dirs):
+    """Parse all .su files under given directories.
+
+    Returns dict mapping function name to info dict with keys:
+      file, line, self, qualifier, reasons
+    """
+
+    funcs = {}
+    for d in dirs:
+        for root, _, files in os.walk(d):
+            for f in files:
+                if not f.endswith(".su"):
+                    continue
+                path = os.path.join(root, f)
+                with open(path) as fh:

Review Comment:
   For deterministic behavior across host locales, consider opening `.su` files with an explicit encoding (e.g., UTF-8) and a defined error handler. This avoids unexpected decode failures if paths/symbols contain non-ASCII bytes.
   



##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)
+
+# Direct call target: optional hex address then <function_name>
+DIRECT_TARGET_RE = re.compile(r"(?:[0-9a-fA-F]+\s+)?<([^>+-]+)(?:[+-][^>]*)?>")
+
+
+def parse_su_files(dirs):
+    """Parse all .su files under given directories.
+
+    Returns dict mapping function name to info dict with keys:
+      file, line, self, qualifier, reasons
+    """
+
+    funcs = {}
+    for d in dirs:
+        for root, _, files in os.walk(d):
+            for f in files:
+                if not f.endswith(".su"):
+                    continue
+                path = os.path.join(root, f)
+                with open(path) as fh:
+                    for line in fh:
+                        line = line.rstrip("\n")
+                        m = SU_LINE_RE.match(line)
+                        if not m:
+                            continue
+
+                        filename = m.group(1)
+                        lineno = m.group(2)
+                        funcname = m.group(4)
+                        size = int(m.group(5))
+                        qualifier = m.group(6)
+
+                        reasons = []
+                        if "dynamic" in qualifier:
+                            if "bounded" in qualifier:
+                                reasons.append("dynamic stack (bounded estimate)")
+                            else:
+                                reasons.append("dynamic stack (alloca/VLA)")
+
+                        # Keep entry with largest self size per function
+                        if funcname in funcs and funcs[funcname]["self"] >= size:
+                            continue
+
+                        funcs[funcname] = {
+                            "file": filename,
+                            "line": lineno,
+                            "self": size,
+                            "qualifier": qualifier,
+                            "reasons": reasons,
+                        }
+    return funcs
+
+
+def parse_call_graph(objdump_bin, elf_path):
+    """Build call graph from objdump disassembly.
+
+    Returns dict mapping caller -> set of (callee_name_or_None, is_indirect).
+    """
+
+    result = subprocess.run(
+        [objdump_bin, "-d", elf_path],
+        capture_output=True,
+        text=True,
+    )
+
+    if result.returncode != 0:
+        print(
+            "Error running objdump: %s" % result.stderr.strip(),
+            file=sys.stderr,
+        )
+        sys.exit(1)
+
+    graph = {}
+    current_func = None
+
+    for line in result.stdout.splitlines():
+        fm = FUNC_RE.match(line)
+        if fm:
+            current_func = fm.group(1)
+            if current_func not in graph:
+                graph[current_func] = set()
+            continue
+
+        if current_func is None:
+            continue
+
+        cm = CALL_RE.search(line)
+        if not cm:
+            continue
+
+        operand = cm.group(1).strip()
+        tm = DIRECT_TARGET_RE.match(operand)
+        if tm:
+            callee = tm.group(1)
+            graph[current_func].add((callee, False))
+        else:
+            # Register operand = indirect call (function pointer)
+            graph[current_func].add((None, True))
+
+    return graph
+
+
+def compute_worst_stack(funcs, graph, recursion_depth):
+    """Compute worst-case total stack for every function via memoized DFS.
+
+    Args:
+        funcs: dict from parse_su_files
+        graph: dict from parse_call_graph
+        recursion_depth: how many times a recursive cycle body is counted
+                         (0 = back-edges contribute nothing)
+
+    Returns dict mapping function name to result dict with keys:
+      self, total, uncertain, reasons, file, line
+    """
+
+    cache = {}
+
+    def dfs(func, path):
+        if func in cache:
+            return cache[func]
+
+        info = funcs.get(func)
+        self_size = info["self"] if info else 0
+        reasons = list(info["reasons"]) if info else ["no .su data"]
+        uncertain = bool(reasons)
+
+        callees = graph.get(func, set())
+        worst_callee = 0
+
+        for callee, is_indirect in callees:
+            if is_indirect:
+                uncertain = True
+                if "indirect call (function pointer)" not in reasons:
+                    reasons.append("indirect call (function pointer)")
+                continue
+
+            if callee in path:
+                # Recursion detected
+                uncertain = True
+                idx = path.index(callee)
+                cycle = path[idx:] + [callee]
+                reason = "recursion: %s" % "->".join(cycle)
+                if reason not in reasons:
+                    reasons.append(reason)
+                if recursion_depth > 0:
+                    cycle_cost = sum(
+                        funcs[c]["self"] if c in funcs else 0 for c in cycle[:-1]
+                    )
+                    worst_callee = max(worst_callee, cycle_cost * recursion_depth)
+                continue
+
+            callee_total, callee_unc, callee_reasons = dfs(callee, path + [func])

Review Comment:
   The recursion-cycle detection is computing the cycle from `path`, but `path` does not include the current function (`func`). This produces incorrect cycles/reasons (e.g., missing the current node) and underestimates `cycle_cost`. A concrete fix is to treat `path` as the current recursion stack including `func` (push `func` when entering `dfs`), and build `cycle` from that stack so `A->B->A` is reported and costed correctly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "xiaoxiang781216 (via GitHub)" <gi...@apache.org>.
xiaoxiang781216 commented on code in PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#discussion_r2932215085


##########
tools/stackusage.py:
##########
@@ -0,0 +1,407 @@
+#!/usr/bin/env python3
+# tools/stackusage.py
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.  The
+# ASF licenses this file to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance with the
+# License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+
+"""Static stack usage analyzer combining GCC .su files with objdump call graphs.
+
+Reports per-function self stack usage and worst-case total stack depth through
+the call chain. Estimates and flags uncertain cases such as alloca/VLA,
+recursion, and indirect calls (function pointers).
+"""
+
+import argparse
+import csv
+import io
+import os
+import re
+import subprocess
+import sys
+
+# GCC .su file format: file.c:line:col:function_name\tsize\tqualifier
+SU_LINE_RE = re.compile(r"^(.*?\.[a-zA-Z]+):(\d+):(\d+):(.+)\t(\d+)\t(\S+)$")
+
+# objdump function header: 00000000 <function_name>:
+FUNC_RE = re.compile(r"^[0-9a-fA-F]+\s+<(.+)>:\s*$")
+
+# Universal call instruction regex covering all NuttX architectures:
+#   ARM:      bl, blx, b.w          ARM64:    bl, blr
+#   x86:      call, callq           RISC-V:   jal, jalr
+#   Xtensa:   call0/4/8/12,         MIPS:     jal, jalr
+#             callx0/4/8/12
+#   AVR:      rcall, call           z80/z16:  call
+#   OR1K:     l.jal, l.jalr         SPARC:    call, jmpl
+#   TriCore:  call, calli           HC/Ren:   bsr, jsr
+CALL_RE = re.compile(
+    r"\t"
+    r"(?:"
+    r"bl[rx]?|b\.w"  # ARM / ARM64
+    r"|callx?(?:0|4|8|12)"  # Xtensa
+    r"|callq?|calli?"  # x86 / TriCore
+    r"|jalr?|l\.jalr?"  # RISC-V / MIPS / OR1K
+    r"|rcall"  # AVR
+    r"|jmpl"  # SPARC
+    r"|[bj]sr"  # HC / Renesas
+    r")"
+    r"\s+(.*)"
+)

Review Comment:
   Fixed. Changed `CALL_RE` from requiring a literal tab (`\t`) to using `\s+` which accepts any whitespace before the mnemonic. This handles different toolchain/arch `objdump -d` output formats correctly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "acassis (via GitHub)" <gi...@apache.org>.
acassis commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4061192865

   > @acassis this PR is a completely different case. In this PR, we don't add Python as a dependency to the build system. This PR is about a debug tool; the debug tools in nuttx have been using Python for a long time.
   > 
   > Using Python for such tools is an obvious choice for me personally, it gives endless possibilities and is now easy to vibe-code
   
   Hi @raiden00pl thank you for explanation. Ok, so everything is fine for this PR


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "linguini1 (via GitHub)" <gi...@apache.org>.
linguini1 commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4056748427

   Why is copilot reviewing this PR? Is the feature enabled on the NuttX repo?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "acassis (via GitHub)" <gi...@apache.org>.
acassis commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4057481570

   @xiaoxiang781216 same comment @raiden00pl did here: https://github.com/apache/nuttx/pull/18396
   
   If this code is supposed to be integrated in the build system, it is better to avoid Python dependence.
   Not a BIG issue, but as he comment, we need to decide and vote if Python is a requirement for NuttX.
   
   In that PR @Abhishekmishra2808 rewrote this Python script as C file.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] tools: replace showstack.sh with stackusage.py. [nuttx]

Posted by "raiden00pl (via GitHub)" <gi...@apache.org>.
raiden00pl commented on PR #18538:
URL: https://github.com/apache/nuttx/pull/18538#issuecomment-4060055007

   @acassis this PR is a completely different case. In this PR, we don't add Python as a dependency to the build system. This PR is about a debug tool; the debug tools in nuttx have been using Python for a long time. 
   
   Using Python for such tools is an obvious choice for me personally, it gives endless possibilities and is now easy to vibe-code


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org