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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to