File: lldbinrepl.py

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (224 lines) | stat: -rw-r--r-- 7,027 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
from __future__ import print_function
from __future__ import absolute_import

import re

import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
import lldbsuite.test.test_categories as test_categories
# System modules
import os
import sys

# Third-party modules

# LLDB modules
import lldb
from .lldbtest import *
from . import configuration
from . import lldbutil
from .decorators import *


def inputFile():
    return "input.swift"


def mainSourceFile():
    return "main.swift"


def breakpointMarker():
    return "Set breakpoint here."


class CommandParser:

    def __init__(self, test):
        self.breakpoint = None
        self.exprs_and_regexps = []
        self.test = test

    def parse_input(self):
        file_handle = open(inputFile(), 'r')
        lines = file_handle.readlines()
        current_expression = None
        for line in lines:
            if line.startswith('///'):
                regexp = line[3:]
                if current_expression:
                    self.exprs_and_regexps.append(
                        {'expr': current_expression, 'regexps': [regexp.strip()]})
                    current_expression = None
                else:
                    if len(self.exprs_and_regexps):
                        self.exprs_and_regexps[-1][
                            'regexps'].append(regexp.strip())
                    else:
                        sys.exit("Failure parsing test: regexp with no command")
            else:
                if current_expression:
                    current_expression += line
                else:
                    current_expression = line

    def set_breakpoint(self, target):
        self.breakpoint = target.BreakpointCreateBySourceRegex(
            breakpointMarker(), lldb.SBFileSpec(mainSourceFile()))

    def handle_breakpoint(self, test, thread, breakpoint_id):
        if self.breakpoint.GetID() == breakpoint_id:
            frame = thread.GetSelectedFrame()
            if test.TraceOn():
                print('Stopped at: %s' % frame)
            options = lldb.SBExpressionOptions()
            options.SetLanguage(lldb.eLanguageTypeSwift)
            options.SetREPLMode(True)
            options.SetFetchDynamicValue(lldb.eDynamicDontRunTarget)

            for expr_and_regexp in self.exprs_and_regexps:
                ret = frame.EvaluateExpression(
                    expr_and_regexp['expr'], options)
                desc_stream = lldb.SBStream()
                ret.GetDescription(desc_stream)
                desc = desc_stream.GetData()
                if test.TraceOn():
                    print("%s --> %s" % (expr_and_regexp['expr'], desc))
                for regexp in expr_and_regexp['regexps']:
                    test.assertTrue(
                        re.search(
                            regexp,
                            desc),
                        "Output of REPL input\n" +
                        expr_and_regexp['expr'] +
                        "was\n" +
                        desc +
                        "which didn't match regexp " +
                        regexp)

            return


class REPLTest(TestBase):
    # Internal implementation

    def getRerunArgs(self):
        # The -N option says to NOT run a if it matches the option argument, so
        # if we are using dSYM we say to NOT run dwarf (-N dwarf) and vice
        # versa.
        if self.using_dsym is None:
            # The test was skipped altogether.
            return ""
        elif self.using_dsym:
            return "-N dwarf %s" % (self.mydir)
        else:
            return "-N dsym %s" % (self.mydir)

    def BuildSourceFile(self):
        if os.path.exists(mainSourceFile()):
            return

        source_file = open(mainSourceFile(), 'w+')
        source_file.write("func stop_here() {\n")
        source_file.write("  // " + breakpointMarker() + "\n")
        source_file.write("}\n")
        source_file.write("stop_here()\n")
        source_file.close()

        return

    def BuildMakefile(self):
        if os.path.exists("Makefile"):
            return

        makefile = open("Makefile", 'w+')

        level = os.sep.join(
            [".."] * len(self.mydir.split(os.sep))) + os.sep + "make"

        makefile.write("LEVEL = " + level + "\n")
        makefile.write("SWIFT_SOURCES := " + mainSourceFile() + "\n")

        makefile.write("include $(LEVEL)/Makefile.rules\n")
        makefile.flush()
        makefile.close()

    @skipUnlessDarwin
    def __test_with_dsym(self):
        return

    def __test_with_dwarf(self):
        self.using_dsym = False
        self.BuildSourceFile()
        self.BuildMakefile()
        self.build()
        self.do_test()

    def __test_with_dwo(self):
        return

    def __test_with_gmodules(self):
        return

    def execute_user_command(self, __command):
        exec(__command, globals(), locals())

    def do_test(self):
        exe_name = "a.out"
        exe = self.getBuildArtifact(exe_name)
        target = self.dbg.CreateTarget(exe)

        parser = CommandParser(self)
        parser.parse_input()
        parser.set_breakpoint(target)

        process = target.LaunchSimple(None, None, os.getcwd())

        while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint):
            thread = lldbutil.get_stopped_thread(
                process, lldb.eStopReasonBreakpoint)
            breakpoint_id = thread.GetStopReasonDataAtIndex(0)
            parser.handle_breakpoint(self, thread, breakpoint_id)
            process.Continue()


def ApplyDecoratorsToFunction(func, decorators):
    tmp = func
    if isinstance(decorators, list):
        for decorator in decorators:
            tmp = decorator(tmp)
    elif hasattr(decorators, '__call__'):
        tmp = decorators(tmp)
    return tmp


def MakeREPLTest(__file, __globals, decorators=None):
    # Adjust the filename if it ends in .pyc.  We want filenames to
    # reflect the source python file, not the compiled variant.
    if __file is not None and __file.endswith(".pyc"):
        # Strip the trailing "c"
        __file = __file[0:-1]

    # Derive the test name from the current file name
    file_basename = os.path.basename(__file)
    REPLTest.mydir = TestBase.compute_mydir(__file)

    test_name, _ = os.path.splitext(file_basename)
    # Build the test case
    test = type(test_name, (REPLTest,), {'using_dsym': None})
    test.name = test_name

    target_platform = lldb.selected_platform.GetTriple().split('-')[2]
    if test_categories.is_supported_on_platform(
            "dwarf", target_platform, configuration.compiler):
        test.test_with_dwarf = ApplyDecoratorsToFunction(
            test._REPLTest__test_with_dwarf, decorators)

    # Add the test case to the globals, and hide REPLTest
    __globals.update({test_name: test})

    # Keep track of the original test filename so we report it
    # correctly in test results.
    test.test_filename = __file
    return test