xref: /llvm-project/lldb/examples/python/stacks.py (revision 2238dcc39358353cac21df75c3c3286ab20b8f53)
1#!/usr/bin/env python
2import lldb
3import optparse
4import shlex
5
6
7def stack_frames(debugger, command, result, dict):
8    command_args = shlex.split(command)
9    usage = "usage: %prog [options] <PATH> [PATH ...]"
10    description = """This command will enumerate all stack frames, print the stack size for each, and print an aggregation of which functions have the largest stack frame sizes at the end."""
11    parser = optparse.OptionParser(description=description, prog="ls", usage=usage)
12    parser.add_option(
13        "-v",
14        "--verbose",
15        action="store_true",
16        dest="verbose",
17        help="display verbose debug info",
18        default=False,
19    )
20    try:
21        (options, args) = parser.parse_args(command_args)
22    except:
23        return
24
25    target = debugger.GetSelectedTarget()
26    process = target.GetProcess()
27
28    frame_info = {}
29    for thread in process:
30        last_frame = None
31        print("thread %u" % (thread.id))
32        for frame in thread.frames:
33            if last_frame:
34                frame_size = 0
35                if frame.idx == 1:
36                    if frame.fp == last_frame.fp:
37                        # No frame one the first frame (might be right at the
38                        # entry point)
39                        first_frame_size = 0
40                        frame_size = frame.fp - frame.sp
41                    else:
42                        # First frame that has a valid size
43                        first_frame_size = last_frame.fp - last_frame.sp
44                    print("<%#7x> %s" % (first_frame_size, last_frame))
45                    if first_frame_size:
46                        name = last_frame.name
47                        if name not in frame_info:
48                            frame_info[name] = first_frame_size
49                        else:
50                            frame_info[name] += first_frame_size
51                else:
52                    # Second or higher frame
53                    frame_size = frame.fp - last_frame.fp
54                print("<%#7x> %s" % (frame_size, frame))
55                if frame_size > 0:
56                    name = frame.name
57                    if name not in frame_info:
58                        frame_info[name] = frame_size
59                    else:
60                        frame_info[name] += frame_size
61            last_frame = frame
62    print(frame_info)
63
64
65def __lldb_init_module(debugger, internal_dict):
66    debugger.HandleCommand("command script add -o -f stacks.stack_frames stack_frames")
67    print(
68        "A new command called 'stack_frames' was added, type 'stack_frames --help' for more information."
69    )
70