Skip to content

Commit 0269307

Browse files
committed
[lldb] Implement basic support for reverse-continue
This commit only adds support for the `SBProcess::ReverseContinue()` API. A user-accessible command for this will follow in a later commit. This feature depends on a gdbserver implementation (e.g. `rr`) providing support for the `bc` and `bs` packets. `lldb-server` does not support those packets, and there is no plan to change that. So, for testing purposes, `lldbreverse.py` wraps `lldb-server` with a Python implementation of *very limited* record-and-replay functionality.
1 parent 404ca22 commit 0269307

32 files changed

+972
-44
lines changed

lldb/include/lldb/API/SBProcess.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ class LLDB_API SBProcess {
158158

159159
lldb::SBError Destroy();
160160

161-
lldb::SBError Continue();
161+
lldb::SBError Continue(RunDirection direction = RunDirection::eRunForward);
162162

163163
lldb::SBError Stop();
164164

lldb/include/lldb/Target/Process.h

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -874,10 +874,10 @@ class Process : public std::enable_shared_from_this<Process>,
874874
/// \see Thread:Resume()
875875
/// \see Thread:Step()
876876
/// \see Thread:Suspend()
877-
Status Resume();
877+
Status Resume(lldb::RunDirection direction = lldb::eRunForward);
878878

879879
/// Resume a process, and wait for it to stop.
880-
Status ResumeSynchronous(Stream *stream);
880+
Status ResumeSynchronous(Stream *stream, lldb::RunDirection direction = lldb::eRunForward);
881881

882882
/// Halts a running process.
883883
///
@@ -1129,10 +1129,15 @@ class Process : public std::enable_shared_from_this<Process>,
11291129
/// \see Thread:Resume()
11301130
/// \see Thread:Step()
11311131
/// \see Thread:Suspend()
1132-
virtual Status DoResume() {
1132+
virtual Status DoResume(lldb::RunDirection direction) {
11331133
Status error;
1134-
error.SetErrorStringWithFormatv(
1135-
"error: {0} does not support resuming processes", GetPluginName());
1134+
if (direction == lldb::RunDirection::eRunForward) {
1135+
error.SetErrorStringWithFormatv(
1136+
"error: {0} does not support resuming processes", GetPluginName());
1137+
} else {
1138+
error.SetErrorStringWithFormatv(
1139+
"error: {0} does not support reverse execution of processes", GetPluginName());
1140+
}
11361141
return error;
11371142
}
11381143

@@ -2367,6 +2372,8 @@ class Process : public std::enable_shared_from_this<Process>,
23672372

23682373
bool IsRunning() const;
23692374

2375+
lldb::RunDirection GetLastRunDirection() { return m_last_run_direction; }
2376+
23702377
DynamicCheckerFunctions *GetDynamicCheckers() {
23712378
return m_dynamic_checkers_up.get();
23722379
}
@@ -2861,7 +2868,7 @@ void PruneThreadPlans();
28612868
///
28622869
/// \return
28632870
/// An Status object describing the success or failure of the resume.
2864-
Status PrivateResume();
2871+
Status PrivateResume(lldb::RunDirection direction = lldb::eRunForward);
28652872

28662873
// Called internally
28672874
void CompleteAttach();
@@ -3139,6 +3146,7 @@ void PruneThreadPlans();
31393146
// m_currently_handling_do_on_removals are true,
31403147
// Resume will only request a resume, using this
31413148
// flag to check.
3149+
lldb::RunDirection m_last_run_direction;
31423150

31433151
/// This is set at the beginning of Process::Finalize() to stop functions
31443152
/// from looking up or creating things during or after a finalize call.

lldb/include/lldb/Target/StopInfo.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,9 @@ class StopInfo : public std::enable_shared_from_this<StopInfo> {
138138
static lldb::StopInfoSP
139139
CreateStopReasonProcessorTrace(Thread &thread, const char *description);
140140

141+
static lldb::StopInfoSP
142+
CreateStopReasonHistoryBoundary(Thread &thread, const char *description);
143+
141144
static lldb::StopInfoSP CreateStopReasonFork(Thread &thread,
142145
lldb::pid_t child_pid,
143146
lldb::tid_t child_tid);

lldb/include/lldb/lldb-enumerations.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ FLAGS_ENUM(LaunchFlags){
135135
/// Thread Run Modes.
136136
enum RunMode { eOnlyThisThread, eAllThreads, eOnlyDuringStepping };
137137

138+
/// Execution directions
139+
enum RunDirection { eRunForward, eRunReverse };
140+
138141
/// Byte ordering definitions.
139142
enum ByteOrder {
140143
eByteOrderInvalid = 0,
@@ -253,6 +256,9 @@ enum StopReason {
253256
eStopReasonFork,
254257
eStopReasonVFork,
255258
eStopReasonVForkDone,
259+
// Indicates that execution stopped because the debugger backend relies
260+
// on recorded data and we reached the end of that data.
261+
eStopReasonHistoryBoundary,
256262
};
257263

258264
/// Command Return Status Types.

lldb/packages/Python/lldbsuite/test/gdbclientutils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -510,8 +510,9 @@ def start(self):
510510
self._thread.start()
511511

512512
def stop(self):
513-
self._thread.join()
514-
self._thread = None
513+
if self._thread is not None:
514+
self._thread.join()
515+
self._thread = None
515516

516517
def get_connect_address(self):
517518
return self._socket.get_connect_address()
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import logging
2+
import os
3+
import os.path
4+
import random
5+
6+
import lldb
7+
from lldbsuite.test.lldbtest import *
8+
from lldbsuite.test.gdbclientutils import *
9+
import lldbgdbserverutils
10+
from lldbsuite.support import seven
11+
12+
13+
class GDBProxyTestBase(TestBase):
14+
"""
15+
Base class for gdbserver proxy tests.
16+
17+
This class will setup and start a mock GDB server for the test to use.
18+
It pases through requests to a regular lldb-server/debugserver and
19+
forwards replies back to the LLDB under test.
20+
"""
21+
22+
"""The gdbserver that we implement."""
23+
server = None
24+
"""The inner lldb-server/debugserver process that we proxy requests into."""
25+
monitor_server = None
26+
monitor_sock = None
27+
28+
server_socket_class = TCPServerSocket
29+
30+
DEFAULT_TIMEOUT = 20 * (10 if ("ASAN_OPTIONS" in os.environ) else 1)
31+
32+
_verbose_log_handler = None
33+
_log_formatter = logging.Formatter(fmt="%(asctime)-15s %(levelname)-8s %(message)s")
34+
35+
def setUpBaseLogging(self):
36+
self.logger = logging.getLogger(__name__)
37+
38+
if len(self.logger.handlers) > 0:
39+
return # We have set up this handler already
40+
41+
self.logger.propagate = False
42+
self.logger.setLevel(logging.DEBUG)
43+
44+
# log all warnings to stderr
45+
handler = logging.StreamHandler()
46+
handler.setLevel(logging.WARNING)
47+
handler.setFormatter(self._log_formatter)
48+
self.logger.addHandler(handler)
49+
50+
def setUp(self):
51+
TestBase.setUp(self)
52+
53+
self.setUpBaseLogging()
54+
55+
if self.isVerboseLoggingRequested():
56+
# If requested, full logs go to a log file
57+
log_file_name = self.getLogBasenameForCurrentTest() + "-proxy.log"
58+
self._verbose_log_handler = logging.FileHandler(
59+
log_file_name
60+
)
61+
self._verbose_log_handler.setFormatter(self._log_formatter)
62+
self._verbose_log_handler.setLevel(logging.DEBUG)
63+
self.logger.addHandler(self._verbose_log_handler)
64+
65+
lldb_server_exe = lldbgdbserverutils.get_lldb_server_exe()
66+
if lldb_server_exe is None:
67+
self.debug_monitor_exe = lldbgdbserverutils.get_debugserver_exe()
68+
self.assertTrue(self.debug_monitor_exe is not None)
69+
self.debug_monitor_extra_args = []
70+
else:
71+
self.debug_monitor_exe = lldb_server_exe
72+
self.debug_monitor_extra_args = ["gdbserver"]
73+
74+
self.server = MockGDBServer(self.server_socket_class())
75+
self.server.responder = self
76+
77+
def tearDown(self):
78+
# TestBase.tearDown will kill the process, but we need to kill it early
79+
# so its client connection closes and we can stop the server before
80+
# finally calling the base tearDown.
81+
if self.process() is not None:
82+
self.process().Kill()
83+
self.server.stop()
84+
85+
self.logger.removeHandler(self._verbose_log_handler)
86+
self._verbose_log_handler = None
87+
88+
TestBase.tearDown(self)
89+
90+
def isVerboseLoggingRequested(self):
91+
# We will report our detailed logs if the user requested that the "gdb-remote" channel is
92+
# logged.
93+
return any(("gdb-remote" in channel) for channel in lldbtest_config.channels)
94+
95+
def connect(self, target):
96+
"""
97+
Create a process by connecting to the mock GDB server.
98+
"""
99+
self.prep_debug_monitor_and_inferior()
100+
self.server.start()
101+
102+
listener = self.dbg.GetListener()
103+
error = lldb.SBError()
104+
process = target.ConnectRemote(
105+
listener, self.server.get_connect_url(), "gdb-remote", error
106+
)
107+
self.assertTrue(error.Success(), error.description)
108+
self.assertTrue(process, PROCESS_IS_VALID)
109+
return process
110+
111+
def get_next_port(self):
112+
return 12000 + random.randint(0, 3999)
113+
114+
def prep_debug_monitor_and_inferior(self):
115+
inferior_exe_path = self.getBuildArtifact("a.out")
116+
self.connect_to_debug_monitor([inferior_exe_path])
117+
self.assertIsNotNone(self.monitor_server)
118+
self.initial_handshake()
119+
120+
def initial_handshake(self):
121+
self.monitor_server.send_packet(seven.bitcast_to_bytes("+"))
122+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
123+
self.assertEqual(reply, "+")
124+
self.monitor_server.send_packet(seven.bitcast_to_bytes("QStartNoAckMode"))
125+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
126+
self.assertEqual(reply, "+")
127+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
128+
self.assertEqual(reply, "OK")
129+
self.monitor_server.send_packet(seven.bitcast_to_bytes("+"))
130+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
131+
self.assertEqual(reply, "+")
132+
133+
def get_debug_monitor_command_line_args(self, connect_address, launch_args):
134+
return self.debug_monitor_extra_args + ["--reverse-connect", connect_address] + launch_args
135+
136+
def launch_debug_monitor(self, launch_args):
137+
family, type, proto, _, addr = socket.getaddrinfo(
138+
"localhost", 0, proto=socket.IPPROTO_TCP
139+
)[0]
140+
sock = socket.socket(family, type, proto)
141+
sock.settimeout(self.DEFAULT_TIMEOUT)
142+
sock.bind(addr)
143+
sock.listen(1)
144+
addr = sock.getsockname()
145+
connect_address = "[{}]:{}".format(*addr)
146+
147+
commandline_args = self.get_debug_monitor_command_line_args(
148+
connect_address, launch_args
149+
)
150+
151+
# Start the server.
152+
self.logger.info(f"Spawning monitor {commandline_args}")
153+
monitor_process = self.spawnSubprocess(
154+
self.debug_monitor_exe, commandline_args, install_remote=False
155+
)
156+
self.assertIsNotNone(monitor_process)
157+
158+
self.monitor_sock = sock.accept()[0]
159+
self.monitor_sock.settimeout(self.DEFAULT_TIMEOUT)
160+
return monitor_process
161+
162+
def connect_to_debug_monitor(self, launch_args):
163+
monitor_process = self.launch_debug_monitor(launch_args)
164+
self.monitor_server = lldbgdbserverutils.Server(self.monitor_sock, monitor_process)
165+
166+
def respond(self, packet):
167+
"""Subclasses can override this to change how packets are handled."""
168+
return self.pass_through(packet)
169+
170+
def pass_through(self, packet):
171+
self.logger.info(f"Sending packet {packet}")
172+
self.monitor_server.send_packet(seven.bitcast_to_bytes(packet))
173+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
174+
self.logger.info(f"Received reply {reply}")
175+
return reply

0 commit comments

Comments
 (0)