Skip to content

Commit ee67f3a

Browse files
committed
[lldb] Support CommandInterpreter print callbacks
Xcode uses a pseudoterminal for the debugger console. - The upside of this apporach is that it means that it can rely on LLDB's IOHandlers for multiline and script input. - The downside of this approach is that the command output is printed to the PTY and you don't get a SBCommandReturnObject. Adrian added support for inline diagnostics in llvm#110901 and we'd like to access those from the IDE. This patch adds support for registering a callback in the command interpreter that gives access to the (SB)CommandReturnObject right before it will be printed. The callback implementation can choose whether it likes to handle printing the result or defer to lldb. If the callback indicated it handled the result, the command interpreter will skip printing the result. We considered a few other alternatives to solve this problem: - The most obvious one is using `HandleCommand`, which returns a `SBCommandReturnObject`. The problem with this approach is the multiline input mentioned above. We would need a way to tell the IDE that it should expect multiline input, which isn't known until LLDB starts handling the command. - To address the multiline issue,we considered exposing (some of the) IOHandler machinery through the SB API. To solve this particular issue, that would require reimplementing a ton of logic that already exists today in the CommandInterpeter. Furthermore that seems like overkill compared to the proposed solution. rdar://141254310
1 parent e1e8d14 commit ee67f3a

File tree

14 files changed

+238
-32
lines changed

14 files changed

+238
-32
lines changed

lldb/bindings/python/python-swigsafecast.swig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ PythonObject SWIGBridge::ToSWIGWrapper(std::unique_ptr<lldb::SBValue> value_sb)
99
return ToSWIGHelper(value_sb.release(), SWIGTYPE_p_lldb__SBValue);
1010
}
1111

12+
PythonObject SWIGBridge::ToSWIGWrapper(std::unique_ptr<lldb::SBCommandReturnObject> result_up) {
13+
return ToSWIGHelper(result_up.release(), SWIGTYPE_p_lldb__SBCommandReturnObject);
14+
}
15+
1216
PythonObject SWIGBridge::ToSWIGWrapper(lldb::ValueObjectSP value_sp) {
1317
return ToSWIGWrapper(std::unique_ptr<lldb::SBValue>(new lldb::SBValue(value_sp)));
1418
}

lldb/bindings/python/python-typemaps.swig

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,25 @@ template <> bool SetNumberFromPyObject<double>(double &number, PyObject *obj) {
476476
$1 = $1 || PyCallable_Check(reinterpret_cast<PyObject *>($input));
477477
}
478478

479+
// For lldb::SBCommandPrintCallback
480+
%typemap(in) (lldb::SBCommandPrintCallback callback, void *baton) {
481+
if (!($input == Py_None ||
482+
PyCallable_Check(reinterpret_cast<PyObject *>($input)))) {
483+
PyErr_SetString(PyExc_TypeError, "Need a callable object or None!");
484+
SWIG_fail;
485+
}
486+
487+
// Don't lose the callback reference.
488+
Py_INCREF($input);
489+
$1 = LLDBSwigPythonCallPythonCommandPrintCallback;
490+
$2 = $input;
491+
}
492+
493+
%typemap(typecheck) (lldb::SBCommandPrintCallback callback, void *baton) {
494+
$1 = $input == Py_None;
495+
$1 = $1 || PyCallable_Check(reinterpret_cast<PyObject *>($input));
496+
}
497+
479498
%typemap(in) (lldb::CommandOverrideCallback callback, void *baton) {
480499
if (!($input == Py_None ||
481500
PyCallable_Check(reinterpret_cast<PyObject *>($input)))) {

lldb/bindings/python/python-wrapper.swig

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -727,7 +727,7 @@ lldb_private::python::SWIGBridge::LLDBSwigPythonHandleOptionArgumentCompletionFo
727727
dict_sp->AddBooleanItem("no-completion", true);
728728
return dict_sp;
729729
}
730-
730+
731731

732732
// Convert the return dictionary to a DictionarySP.
733733
StructuredData::ObjectSP result_obj_sp = result.CreateStructuredObject();
@@ -753,7 +753,7 @@ bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
753753
auto pfunc = self.ResolveName<PythonCallable>("__call__");
754754

755755
if (!pfunc.IsAllocated()) {
756-
cmd_retobj.AppendError("Could not find '__call__' method in implementation class");
756+
cmd_retobj.AppendError("Could not find '__call__' method in implementation class");
757757
return false;
758758
}
759759

@@ -1012,6 +1012,26 @@ static void LLDBSwigPythonCallPythonLogOutputCallback(const char *str,
10121012
}
10131013
}
10141014

1015+
// For DebuggerTerminateCallback functions
1016+
static CommandReturnObjectCallbackResult LLDBSwigPythonCallPythonCommandPrintCallback(SBCommandReturnObject& result, void *callback_baton) {
1017+
SWIG_Python_Thread_Block swig_thread_block;
1018+
1019+
PyErr_Cleaner py_err_cleaner(true);
1020+
1021+
PythonObject result_arg = SWIGBridge::ToSWIGWrapper(
1022+
std::make_unique<SBCommandReturnObject>(result));
1023+
PythonCallable callable =
1024+
Retain<PythonCallable>(reinterpret_cast<PyObject *>(callback_baton));
1025+
1026+
if (!callable.IsValid())
1027+
return eCommandReturnObjectPrintCallbackSkipped;
1028+
1029+
PythonObject callback_result = callable(result_arg);
1030+
1031+
long long ret_val = unwrapOrSetPythonException(As<long long>(callback_result));
1032+
return (CommandReturnObjectCallbackResult)ret_val;
1033+
}
1034+
10151035
// For DebuggerTerminateCallback functions
10161036
static void LLDBSwigPythonCallPythonSBDebuggerTerminateCallback(lldb::user_id_t debugger_id,
10171037
void *baton) {

lldb/include/lldb/API/SBCommandInterpreter.h

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,13 +247,13 @@ class SBCommandInterpreter {
247247
lldb::SBStringList &matches,
248248
lldb::SBStringList &descriptions);
249249

250-
/// Returns whether an interrupt flag was raised either by the SBDebugger -
250+
/// Returns whether an interrupt flag was raised either by the SBDebugger -
251251
/// when the function is not running on the RunCommandInterpreter thread, or
252252
/// by SBCommandInterpreter::InterruptCommand if it is. If your code is doing
253-
/// interruptible work, check this API periodically, and interrupt if it
253+
/// interruptible work, check this API periodically, and interrupt if it
254254
/// returns true.
255255
bool WasInterrupted() const;
256-
256+
257257
/// Interrupts the command currently executing in the RunCommandInterpreter
258258
/// thread.
259259
///
@@ -331,6 +331,8 @@ class SBCommandInterpreter {
331331
/// this list. Otherwise this list is empty.
332332
SBStructuredData GetTranscript();
333333

334+
void SetPrintCallback(lldb::SBCommandPrintCallback callback, void *baton);
335+
334336
protected:
335337
friend class lldb_private::CommandPluginInterfaceImplementation;
336338

lldb/include/lldb/API/SBCommandReturnObject.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
namespace lldb_private {
1919
class CommandPluginInterfaceImplementation;
20+
class CommandPrintCallbackBaton;
2021
class SBCommandReturnObjectImpl;
2122
namespace python {
2223
class SWIGBridge;
@@ -138,6 +139,7 @@ class LLDB_API SBCommandReturnObject {
138139

139140
friend class lldb_private::CommandPluginInterfaceImplementation;
140141
friend class lldb_private::python::SWIGBridge;
142+
friend class lldb_private::CommandPrintCallbackBaton;
141143

142144
SBCommandReturnObject(lldb_private::CommandReturnObject &ref);
143145

lldb/include/lldb/API/SBDefines.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ typedef bool (*SBBreakpointHitCallback)(void *baton, lldb::SBProcess &process,
144144
typedef void (*SBDebuggerDestroyCallback)(lldb::user_id_t debugger_id,
145145
void *baton);
146146

147+
typedef CommandReturnObjectCallbackResult (*SBCommandPrintCallback)(
148+
lldb::SBCommandReturnObject &result, void *baton);
149+
147150
typedef lldb::SBError (*SBPlatformLocateModuleCallback)(
148151
void *baton, const lldb::SBModuleSpec &module_spec,
149152
lldb::SBFileSpec &module_file_spec, lldb::SBFileSpec &symbol_file_spec);

lldb/include/lldb/Interpreter/CommandInterpreter.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include "lldb/Interpreter/CommandObject.h"
1717
#include "lldb/Interpreter/ScriptInterpreter.h"
1818
#include "lldb/Utility/Args.h"
19+
#include "lldb/Utility/Baton.h"
1920
#include "lldb/Utility/Broadcaster.h"
2021
#include "lldb/Utility/CompletionRequest.h"
2122
#include "lldb/Utility/Event.h"
@@ -253,6 +254,9 @@ class CommandInterpreter : public Broadcaster,
253254
eCommandTypesAllThem = 0xFFFF //< all commands
254255
};
255256

257+
typedef lldb::CommandReturnObjectCallbackResult (
258+
*CommandReturnObjectCallback)(CommandReturnObject &, void *);
259+
256260
// The CommandAlias and CommandInterpreter both have a hand in
257261
// substituting for alias commands. They work by writing special tokens
258262
// in the template form of the Alias command, and then detecting them when the
@@ -664,6 +668,9 @@ class CommandInterpreter : public Broadcaster,
664668
++m_command_usages[cmd_obj.GetCommandName()];
665669
}
666670

671+
void SetPrintCallback(CommandReturnObjectCallback callback,
672+
lldb::BatonSP baton_sp);
673+
667674
llvm::json::Value GetStatistics();
668675
const StructuredData::Array &GetTranscript() const;
669676

@@ -774,6 +781,12 @@ class CommandInterpreter : public Broadcaster,
774781
std::vector<uint32_t> m_command_source_flags;
775782
CommandInterpreterRunResult m_result;
776783

784+
/// An optional callback to handle printing the CommandReturnObject.
785+
/// @{
786+
CommandReturnObjectCallback m_print_callback = nullptr;
787+
lldb::BatonSP m_print_callback_baton_sp;
788+
/// @}
789+
777790
// The exit code the user has requested when calling the 'quit' command.
778791
// No value means the user hasn't set a custom exit code so far.
779792
std::optional<int> m_quit_exit_code;

lldb/include/lldb/lldb-enumerations.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1368,6 +1368,15 @@ enum Severity {
13681368
eSeverityInfo, // Equivalent to Remark used in clang.
13691369
};
13701370

1371+
/// Callback return value, indicating whether it handled printing the
1372+
/// CommandReturnObject or deferred doing so to the CommandInterpreter.
1373+
enum CommandReturnObjectCallbackResult {
1374+
/// The callback deferred printing the command return object.
1375+
eCommandReturnObjectPrintCallbackSkipped = 0,
1376+
/// The callback handled printing the command return object.
1377+
eCommandReturnObjectPrintCallbackHandled = 1,
1378+
};
1379+
13711380
} // namespace lldb
13721381

13731382
#endif // LLDB_LLDB_ENUMERATIONS_H

lldb/source/API/SBCommandInterpreter.cpp

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ bool SBCommandInterpreter::WasInterrupted() const {
151151

152152
bool SBCommandInterpreter::InterruptCommand() {
153153
LLDB_INSTRUMENT_VA(this);
154-
154+
155155
return (IsValid() ? m_opaque_ptr->InterruptCommand() : false);
156156
}
157157

@@ -743,3 +743,41 @@ void SBCommand::SetFlags(uint32_t flags) {
743743
if (IsValid())
744744
m_opaque_sp->GetFlags().Set(flags);
745745
}
746+
747+
namespace lldb_private {
748+
struct CommandCallbackData {
749+
SBCommandPrintCallback callback;
750+
void *callback_baton;
751+
};
752+
753+
class CommandPrintCallbackBaton
754+
: public lldb_private::TypedBaton<CommandCallbackData> {
755+
public:
756+
CommandPrintCallbackBaton(SBCommandPrintCallback callback, void *baton)
757+
: TypedBaton(std::make_unique<CommandCallbackData>()) {
758+
getItem()->callback = callback;
759+
getItem()->callback_baton = baton;
760+
}
761+
762+
static lldb::CommandReturnObjectCallbackResult
763+
PrivateCallback(lldb_private::CommandReturnObject &result, void *baton) {
764+
if (baton) {
765+
CommandCallbackData *data = (CommandCallbackData *)baton;
766+
SBCommandReturnObject sb_result(result);
767+
return data->callback(sb_result, data->callback_baton);
768+
}
769+
return eCommandReturnObjectPrintCallbackSkipped;
770+
}
771+
};
772+
} // namespace lldb_private
773+
774+
void SBCommandInterpreter::SetPrintCallback(
775+
lldb::SBCommandPrintCallback callback, void *baton) {
776+
LLDB_INSTRUMENT_VA(this, callback, baton);
777+
778+
BatonSP baton_sp =
779+
std::make_shared<CommandPrintCallbackBaton>(callback, baton);
780+
if (m_opaque_ptr)
781+
return m_opaque_ptr->SetPrintCallback(
782+
&CommandPrintCallbackBaton::PrivateCallback, baton_sp);
783+
}

lldb/source/Interpreter/CommandInterpreter.cpp

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3182,30 +3182,44 @@ void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
31823182
if ((result.Succeeded() &&
31833183
io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
31843184
io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
3185-
// Display any inline diagnostics first.
3186-
const bool inline_diagnostics = !result.GetImmediateErrorStream() &&
3187-
GetDebugger().GetShowInlineDiagnostics();
3188-
if (inline_diagnostics) {
3189-
unsigned prompt_len = m_debugger.GetPrompt().size();
3190-
if (auto indent = result.GetDiagnosticIndent()) {
3191-
std::string diags =
3192-
result.GetInlineDiagnosticString(prompt_len + *indent);
3193-
PrintCommandOutput(io_handler, diags, true);
3185+
auto DefaultPrintCallback = [&](const CommandReturnObject &result) {
3186+
// Display any inline diagnostics first.
3187+
const bool inline_diagnostics = !result.GetImmediateErrorStream() &&
3188+
GetDebugger().GetShowInlineDiagnostics();
3189+
if (inline_diagnostics) {
3190+
unsigned prompt_len = m_debugger.GetPrompt().size();
3191+
if (auto indent = result.GetDiagnosticIndent()) {
3192+
std::string diags =
3193+
result.GetInlineDiagnosticString(prompt_len + *indent);
3194+
PrintCommandOutput(io_handler, diags, true);
3195+
}
31943196
}
3195-
}
31963197

3197-
// Display any STDOUT/STDERR _prior_ to emitting the command result text.
3198-
GetProcessOutput();
3198+
// Display any STDOUT/STDERR _prior_ to emitting the command result text.
3199+
GetProcessOutput();
31993200

3200-
if (!result.GetImmediateOutputStream()) {
3201-
llvm::StringRef output = result.GetOutputString();
3202-
PrintCommandOutput(io_handler, output, true);
3203-
}
3201+
if (!result.GetImmediateOutputStream()) {
3202+
llvm::StringRef output = result.GetOutputString();
3203+
PrintCommandOutput(io_handler, output, true);
3204+
}
32043205

3205-
// Now emit the command error text from the command we just executed.
3206-
if (!result.GetImmediateErrorStream()) {
3207-
std::string error = result.GetErrorString(!inline_diagnostics);
3208-
PrintCommandOutput(io_handler, error, false);
3206+
// Now emit the command error text from the command we just executed.
3207+
if (!result.GetImmediateErrorStream()) {
3208+
std::string error = result.GetErrorString(!inline_diagnostics);
3209+
PrintCommandOutput(io_handler, error, false);
3210+
}
3211+
};
3212+
3213+
if (m_print_callback) {
3214+
void *baton = m_print_callback_baton_sp
3215+
? m_print_callback_baton_sp->data()
3216+
: nullptr;
3217+
lldb::CommandReturnObjectCallbackResult callback_result =
3218+
m_print_callback(result, baton);
3219+
if (callback_result == eCommandReturnObjectPrintCallbackSkipped)
3220+
DefaultPrintCallback(result);
3221+
} else {
3222+
DefaultPrintCallback(result);
32093223
}
32103224
}
32113225

@@ -3656,3 +3670,9 @@ llvm::json::Value CommandInterpreter::GetStatistics() {
36563670
const StructuredData::Array &CommandInterpreter::GetTranscript() const {
36573671
return m_transcript;
36583672
}
3673+
3674+
void CommandInterpreter::SetPrintCallback(CommandReturnObjectCallback callback,
3675+
lldb::BatonSP baton_sp) {
3676+
m_print_callback = callback;
3677+
m_print_callback_baton_sp = baton_sp;
3678+
}

lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ template <typename T> class ScopedPythonObject : PythonObject {
8181
class SWIGBridge {
8282
public:
8383
static PythonObject ToSWIGWrapper(std::unique_ptr<lldb::SBValue> value_sb);
84+
static PythonObject
85+
ToSWIGWrapper(std::unique_ptr<lldb::SBCommandReturnObject> result_up);
8486
static PythonObject ToSWIGWrapper(lldb::ValueObjectSP value_sp);
8587
static PythonObject ToSWIGWrapper(lldb::TargetSP target_sp);
8688
static PythonObject ToSWIGWrapper(lldb::ProcessSP process_sp);
@@ -190,12 +192,11 @@ class SWIGBridge {
190192
lldb::DebuggerSP debugger, const char *args,
191193
lldb_private::CommandReturnObject &cmd_retobj,
192194
lldb::ExecutionContextRefSP exe_ctx_ref_sp);
193-
static bool
194-
LLDBSwigPythonCallParsedCommandObject(PyObject *implementor,
195-
lldb::DebuggerSP debugger,
196-
StructuredDataImpl &args_impl,
197-
lldb_private::CommandReturnObject &cmd_retobj,
198-
lldb::ExecutionContextRefSP exe_ctx_ref_sp);
195+
static bool LLDBSwigPythonCallParsedCommandObject(
196+
PyObject *implementor, lldb::DebuggerSP debugger,
197+
StructuredDataImpl &args_impl,
198+
lldb_private::CommandReturnObject &cmd_retobj,
199+
lldb::ExecutionContextRefSP exe_ctx_ref_sp);
199200

200201
static std::optional<std::string>
201202
LLDBSwigPythonGetRepeatCommandForScriptedCommand(PyObject *implementor,
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
C_SOURCES := main.c
2+
3+
include Makefile.rules

0 commit comments

Comments
 (0)