Skip to content

Commit 25e184d

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 b8741cc commit 25e184d

25 files changed

+979
-17
lines changed

lldb/include/lldb/API/SBProcess.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ class LLDB_API SBProcess {
160160

161161
lldb::SBError Continue();
162162

163+
lldb::SBError ReverseContinue();
164+
163165
lldb::SBError Stop();
164166

165167
lldb::SBError Kill();

lldb/include/lldb/Target/Process.h

Lines changed: 22 additions & 3 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
///
@@ -1136,6 +1136,22 @@ class Process : public std::enable_shared_from_this<Process>,
11361136
return error;
11371137
}
11381138

1139+
/// Like DoResume() but executes in reverse if supported.
1140+
///
1141+
/// \return
1142+
/// Returns \b true if the process successfully resumes using
1143+
/// the thread run control actions, \b false otherwise.
1144+
///
1145+
/// \see Thread:Resume()
1146+
/// \see Thread:Step()
1147+
/// \see Thread:Suspend()
1148+
virtual Status DoResumeReverse() {
1149+
Status error;
1150+
error.SetErrorStringWithFormatv(
1151+
"error: {0} does not support reverse execution of processes", GetPluginName());
1152+
return error;
1153+
}
1154+
11391155
/// Called after resuming a process.
11401156
///
11411157
/// Allow Process plug-ins to execute some code after resuming a process.
@@ -2367,6 +2383,8 @@ class Process : public std::enable_shared_from_this<Process>,
23672383

23682384
bool IsRunning() const;
23692385

2386+
lldb::RunDirection GetLastRunDirection() { return m_last_run_direction; }
2387+
23702388
DynamicCheckerFunctions *GetDynamicCheckers() {
23712389
return m_dynamic_checkers_up.get();
23722390
}
@@ -2861,7 +2879,7 @@ void PruneThreadPlans();
28612879
///
28622880
/// \return
28632881
/// An Status object describing the success or failure of the resume.
2864-
Status PrivateResume();
2882+
Status PrivateResume(lldb::RunDirection direction = lldb::eRunForward);
28652883

28662884
// Called internally
28672885
void CompleteAttach();
@@ -3139,6 +3157,7 @@ void PruneThreadPlans();
31393157
// m_currently_handling_do_on_removals are true,
31403158
// Resume will only request a resume, using this
31413159
// flag to check.
3160+
lldb::RunDirection m_last_run_direction;
31423161

31433162
/// This is set at the beginning of Process::Finalize() to stop functions
31443163
/// 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: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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+
self.port = self.get_next_port()
66+
lldb_server_exe = lldbgdbserverutils.get_lldb_server_exe()
67+
if lldb_server_exe is None:
68+
self.debug_monitor_exe = lldbgdbserverutils.get_debugserver_exe()
69+
self.assertTrue(self.debug_monitor_exe is not None)
70+
self.debug_monitor_extra_args = []
71+
else:
72+
self.debug_monitor_exe = lldb_server_exe
73+
self.debug_monitor_extra_args = ["gdbserver"]
74+
75+
self.server = MockGDBServer(self.server_socket_class())
76+
self.server.responder = self
77+
78+
def tearDown(self):
79+
# TestBase.tearDown will kill the process, but we need to kill it early
80+
# so its client connection closes and we can stop the server before
81+
# finally calling the base tearDown.
82+
if self.process() is not None:
83+
self.process().Kill()
84+
self.server.stop()
85+
86+
self.logger.removeHandler(self._verbose_log_handler)
87+
self._verbose_log_handler = None
88+
89+
TestBase.tearDown(self)
90+
91+
def isVerboseLoggingRequested(self):
92+
# We will report our detailed logs if the user requested that the "gdb-remote" channel is
93+
# logged.
94+
return any(("gdb-remote" in channel) for channel in lldbtest_config.channels)
95+
96+
def connect(self, target):
97+
"""
98+
Create a process by connecting to the mock GDB server.
99+
"""
100+
self.prep_debug_monitor_and_inferior()
101+
self.server.start()
102+
103+
listener = self.dbg.GetListener()
104+
error = lldb.SBError()
105+
process = target.ConnectRemote(
106+
listener, self.server.get_connect_url(), "gdb-remote", error
107+
)
108+
self.assertTrue(error.Success(), error.description)
109+
self.assertTrue(process, PROCESS_IS_VALID)
110+
return process
111+
112+
def get_next_port(self):
113+
return 12000 + random.randint(0, 3999)
114+
115+
def prep_debug_monitor_and_inferior(self):
116+
inferior_exe_path = self.getBuildArtifact("a.out")
117+
self.connect_to_debug_monitor([inferior_exe_path])
118+
self.assertIsNotNone(self.monitor_server)
119+
self.initial_handshake()
120+
121+
def initial_handshake(self):
122+
self.monitor_server.send_packet(seven.bitcast_to_bytes("+"))
123+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
124+
self.assertEqual(reply, "+")
125+
self.monitor_server.send_packet(seven.bitcast_to_bytes("QStartNoAckMode"))
126+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
127+
self.assertEqual(reply, "+")
128+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
129+
self.assertEqual(reply, "OK")
130+
self.monitor_server.send_packet(seven.bitcast_to_bytes("+"))
131+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
132+
self.assertEqual(reply, "+")
133+
134+
def get_debug_monitor_command_line_args(self, connect_address, launch_args):
135+
return self.debug_monitor_extra_args + ["--reverse-connect", connect_address] + launch_args
136+
137+
def launch_debug_monitor(self, launch_args):
138+
family, type, proto, _, addr = socket.getaddrinfo(
139+
"localhost", 0, proto=socket.IPPROTO_TCP
140+
)[0]
141+
sock = socket.socket(family, type, proto)
142+
sock.settimeout(self.DEFAULT_TIMEOUT)
143+
sock.bind(addr)
144+
sock.listen(1)
145+
addr = sock.getsockname()
146+
connect_address = "[{}]:{}".format(*addr)
147+
148+
commandline_args = self.get_debug_monitor_command_line_args(
149+
connect_address, launch_args
150+
)
151+
152+
# Start the server.
153+
self.logger.info(f"Spawning monitor {commandline_args}")
154+
monitor_process = self.spawnSubprocess(
155+
self.debug_monitor_exe, commandline_args, install_remote=False
156+
)
157+
self.assertIsNotNone(monitor_process)
158+
159+
self.monitor_sock = sock.accept()[0]
160+
self.monitor_sock.settimeout(self.DEFAULT_TIMEOUT)
161+
return monitor_process
162+
163+
def connect_to_debug_monitor(self, launch_args):
164+
monitor_process = self.launch_debug_monitor(launch_args)
165+
self.monitor_server = lldbgdbserverutils.Server(self.monitor_sock, monitor_process)
166+
167+
def respond(self, packet):
168+
"""Subclasses can override this to change how packets are handled."""
169+
return self.pass_through(packet)
170+
171+
def pass_through(self, packet):
172+
self.logger.info(f"Sending packet {packet}")
173+
self.monitor_server.send_packet(seven.bitcast_to_bytes(packet))
174+
reply = seven.bitcast_to_string(self.monitor_server.get_normal_packet())
175+
self.logger.info(f"Received reply {reply}")
176+
return reply

0 commit comments

Comments
 (0)