xref: /freebsd/contrib/llvm-project/lldb/bindings/python/python-wrapper.swig (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1%header %{
2
3class PyErr_Cleaner {
4public:
5  PyErr_Cleaner(bool print = false) : m_print(print) {}
6
7  ~PyErr_Cleaner() {
8    if (PyErr_Occurred()) {
9      if (m_print && !PyErr_ExceptionMatches(PyExc_SystemExit))
10        PyErr_Print();
11      PyErr_Clear();
12    }
13  }
14
15private:
16  bool m_print;
17};
18
19llvm::Expected<bool> lldb_private::python::SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction(
20    const char *python_function_name, const char *session_dictionary_name,
21    const lldb::StackFrameSP &frame_sp,
22    const lldb::BreakpointLocationSP &bp_loc_sp,
23    const lldb_private::StructuredDataImpl &args_impl) {
24  using namespace llvm;
25
26  lldb::SBBreakpointLocation sb_bp_loc(bp_loc_sp);
27
28  PyErr_Cleaner py_err_cleaner(true);
29  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
30      session_dictionary_name);
31  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
32      python_function_name, dict);
33
34  unsigned max_positional_args;
35  if (auto arg_info = pfunc.GetArgInfo())
36    max_positional_args = arg_info.get().max_positional_args;
37  else
38    return arg_info.takeError();
39
40  PythonObject frame_arg = SWIGBridge::ToSWIGWrapper(frame_sp);
41  PythonObject bp_loc_arg = SWIGBridge::ToSWIGWrapper(bp_loc_sp);
42
43  auto result =
44      max_positional_args < 4
45          ? pfunc.Call(frame_arg, bp_loc_arg, dict)
46          : pfunc.Call(frame_arg, bp_loc_arg, SWIGBridge::ToSWIGWrapper(args_impl), dict);
47
48  if (!result)
49    return result.takeError();
50
51  // Only False counts as false!
52  return result.get().get() != Py_False;
53}
54
55// resolve a dotted Python name in the form
56// foo.bar.baz.Foobar to an actual Python object
57// if pmodule is NULL, the __main__ module will be used
58// as the starting point for the search
59
60// This function is called by
61// lldb_private::ScriptInterpreterPython::BreakpointCallbackFunction(...) and is
62// used when a script command is attached to a breakpoint for execution.
63
64// This function is called by
65// lldb_private::ScriptInterpreterPython::WatchpointCallbackFunction(...) and is
66// used when a script command is attached to a watchpoint for execution.
67
68bool lldb_private::python::SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction(
69    const char *python_function_name, const char *session_dictionary_name,
70    const lldb::StackFrameSP &frame_sp, const lldb::WatchpointSP &wp_sp) {
71
72  bool stop_at_watchpoint = true;
73
74  PyErr_Cleaner py_err_cleaner(true);
75
76  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
77      session_dictionary_name);
78  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
79      python_function_name, dict);
80
81  if (!pfunc.IsAllocated())
82    return stop_at_watchpoint;
83
84  PythonObject result =
85      pfunc(SWIGBridge::ToSWIGWrapper(frame_sp), SWIGBridge::ToSWIGWrapper(wp_sp), dict);
86
87  if (result.get() == Py_False)
88    stop_at_watchpoint = false;
89
90  return stop_at_watchpoint;
91}
92
93// This function is called by
94// ScriptInterpreterPython::FormatterMatchingCallbackFunction and it's used when
95// a data formatter provides the name of a callback to inspect a candidate type
96// before considering a match.
97bool lldb_private::python::SWIGBridge::LLDBSwigPythonFormatterCallbackFunction(
98    const char *python_function_name, const char *session_dictionary_name,
99    lldb::TypeImplSP type_impl_sp) {
100
101  PyErr_Cleaner py_err_cleaner(true);
102
103  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
104      session_dictionary_name);
105  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
106      python_function_name, dict);
107
108  if (!pfunc.IsAllocated())
109    return false;
110
111  PythonObject result =
112      pfunc(SWIGBridge::ToSWIGWrapper(type_impl_sp), dict);
113
114  // Only if everything goes okay and the function returns True we'll consider
115  // it a match.
116  return result.get() == Py_True;
117}
118
119bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallTypeScript(
120    const char *python_function_name, const void *session_dictionary,
121    const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
122    const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval) {
123
124  retval.clear();
125
126  if (!python_function_name || !session_dictionary)
127    return false;
128
129  PyObject *pfunc_impl = nullptr;
130
131  if (pyfunct_wrapper && *pyfunct_wrapper &&
132      PyFunction_Check(*pyfunct_wrapper)) {
133    pfunc_impl = (PyObject *)(*pyfunct_wrapper);
134    if (pfunc_impl->ob_refcnt == 1) {
135      Py_XDECREF(pfunc_impl);
136      pfunc_impl = NULL;
137    }
138  }
139
140  PyObject *py_dict = (PyObject *)session_dictionary;
141  if (!PythonDictionary::Check(py_dict))
142    return true;
143
144  PythonDictionary dict(PyRefType::Borrowed, py_dict);
145
146  PyErr_Cleaner pyerr_cleanup(true); // show Python errors
147
148  PythonCallable pfunc(PyRefType::Borrowed, pfunc_impl);
149
150  if (!pfunc.IsAllocated()) {
151    pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
152        python_function_name, dict);
153    if (!pfunc.IsAllocated())
154      return false;
155
156    if (pyfunct_wrapper) {
157      *pyfunct_wrapper = pfunc.get();
158      Py_XINCREF(pfunc.get());
159    }
160  }
161
162  PythonObject result;
163  auto argc = pfunc.GetArgInfo();
164  if (!argc) {
165    llvm::consumeError(argc.takeError());
166    return false;
167  }
168
169  PythonObject value_arg = SWIGBridge::ToSWIGWrapper(valobj_sp);
170
171  if (argc.get().max_positional_args < 3)
172    result = pfunc(value_arg, dict);
173  else
174    result = pfunc(value_arg, dict, SWIGBridge::ToSWIGWrapper(*options_sp));
175
176  retval = result.Str().GetString().str();
177
178  return true;
179}
180
181PythonObject lldb_private::python::SWIGBridge::LLDBSwigPythonCreateSyntheticProvider(
182    const char *python_class_name, const char *session_dictionary_name,
183    const lldb::ValueObjectSP &valobj_sp) {
184  if (python_class_name == NULL || python_class_name[0] == '\0' ||
185      !session_dictionary_name)
186    return PythonObject();
187
188  PyErr_Cleaner py_err_cleaner(true);
189
190  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
191      session_dictionary_name);
192  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
193      python_class_name, dict);
194
195  if (!pfunc.IsAllocated())
196    return PythonObject();
197
198  auto sb_value = std::unique_ptr<lldb::SBValue>(new lldb::SBValue(valobj_sp));
199  sb_value->SetPreferSyntheticValue(false);
200
201  PythonObject val_arg = SWIGBridge::ToSWIGWrapper(std::move(sb_value));
202  if (!val_arg.IsAllocated())
203    return PythonObject();
204
205  PythonObject result = pfunc(val_arg, dict);
206
207  if (result.IsAllocated())
208    return result;
209
210  return PythonObject();
211}
212
213PythonObject lldb_private::python::SWIGBridge::LLDBSwigPythonCreateCommandObject(
214    const char *python_class_name, const char *session_dictionary_name,
215    lldb::DebuggerSP debugger_sp) {
216  if (python_class_name == NULL || python_class_name[0] == '\0' ||
217      !session_dictionary_name)
218    return PythonObject();
219
220  PyErr_Cleaner py_err_cleaner(true);
221  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
222      session_dictionary_name);
223  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
224      python_class_name, dict);
225
226  if (!pfunc.IsAllocated())
227    return PythonObject();
228
229  return pfunc(SWIGBridge::ToSWIGWrapper(std::move(debugger_sp)), dict);
230}
231
232PythonObject lldb_private::python::SWIGBridge::LLDBSwigPythonCreateScriptedBreakpointResolver(
233    const char *python_class_name, const char *session_dictionary_name,
234    const StructuredDataImpl &args_impl,
235    const lldb::BreakpointSP &breakpoint_sp) {
236
237  if (python_class_name == NULL || python_class_name[0] == '\0' ||
238      !session_dictionary_name)
239    return PythonObject();
240
241  PyErr_Cleaner py_err_cleaner(true);
242
243  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
244      session_dictionary_name);
245  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
246      python_class_name, dict);
247
248  if (!pfunc.IsAllocated())
249    return PythonObject();
250
251  PythonObject result =
252      pfunc(SWIGBridge::ToSWIGWrapper(breakpoint_sp), SWIGBridge::ToSWIGWrapper(args_impl), dict);
253  // FIXME: At this point we should check that the class we found supports all
254  // the methods that we need.
255
256  if (result.IsAllocated()) {
257    // Check that __callback__ is defined:
258    auto callback_func = result.ResolveName<PythonCallable>("__callback__");
259    if (callback_func.IsAllocated())
260      return result;
261  }
262  return PythonObject();
263}
264
265unsigned int lldb_private::python::SWIGBridge::LLDBSwigPythonCallBreakpointResolver(
266    void *implementor, const char *method_name,
267    lldb_private::SymbolContext *sym_ctx) {
268  PyErr_Cleaner py_err_cleaner(false);
269  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
270  auto pfunc = self.ResolveName<PythonCallable>(method_name);
271
272  if (!pfunc.IsAllocated())
273    return 0;
274
275  PythonObject result = sym_ctx ? pfunc(SWIGBridge::ToSWIGWrapper(*sym_ctx)) : pfunc();
276
277  if (PyErr_Occurred()) {
278    PyErr_Print();
279    PyErr_Clear();
280    return 0;
281  }
282
283  // The callback will return a bool, but we're need to also return ints
284  // so we're squirrelling the bool through as an int...  And if you return
285  // nothing, we'll continue.
286  if (strcmp(method_name, "__callback__") == 0) {
287    if (result.get() == Py_False)
288      return 0;
289    else
290      return 1;
291  }
292
293  long long ret_val = unwrapOrSetPythonException(As<long long>(result));
294
295  if (PyErr_Occurred()) {
296    PyErr_Print();
297    PyErr_Clear();
298    return 0;
299  }
300
301  return ret_val;
302}
303
304PythonObject lldb_private::python::SWIGBridge::LLDBSwigPythonCreateScriptedStopHook(
305    lldb::TargetSP target_sp, const char *python_class_name,
306    const char *session_dictionary_name, const StructuredDataImpl &args_impl,
307    Status &error) {
308  if (python_class_name == NULL || python_class_name[0] == '\0') {
309    error.SetErrorString("Empty class name.");
310    return PythonObject();
311  }
312  if (!session_dictionary_name) {
313    error.SetErrorString("No session dictionary");
314    return PythonObject();
315  }
316
317  PyErr_Cleaner py_err_cleaner(true);
318
319  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
320      session_dictionary_name);
321  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
322      python_class_name, dict);
323
324  if (!pfunc.IsAllocated()) {
325    error.SetErrorStringWithFormat("Could not find class: %s.",
326                                   python_class_name);
327    return PythonObject();
328  }
329
330  PythonObject result =
331      pfunc(SWIGBridge::ToSWIGWrapper(target_sp), SWIGBridge::ToSWIGWrapper(args_impl), dict);
332
333  if (result.IsAllocated()) {
334    // Check that the handle_stop callback is defined:
335    auto callback_func = result.ResolveName<PythonCallable>("handle_stop");
336    if (callback_func.IsAllocated()) {
337      if (auto args_info = callback_func.GetArgInfo()) {
338        size_t num_args = (*args_info).max_positional_args;
339        if (num_args != 2) {
340          error.SetErrorStringWithFormat(
341              "Wrong number of args for "
342              "handle_stop callback, should be 2 (excluding self), got: %zu",
343              num_args);
344          return PythonObject();
345        } else
346          return result;
347      } else {
348        error.SetErrorString("Couldn't get num arguments for handle_stop "
349                             "callback.");
350        return PythonObject();
351      }
352      return result;
353    } else {
354      error.SetErrorStringWithFormat("Class \"%s\" is missing the required "
355                                     "handle_stop callback.",
356                                     python_class_name);
357    }
358  }
359  return PythonObject();
360}
361
362bool lldb_private::python::SWIGBridge::LLDBSwigPythonStopHookCallHandleStop(
363    void *implementor, lldb::ExecutionContextRefSP exc_ctx_sp,
364    lldb::StreamSP stream) {
365  // handle_stop will return a bool with the meaning "should_stop"...
366  // If you return nothing we'll assume we are going to stop.
367  // Also any errors should return true, since we should stop on error.
368
369  PyErr_Cleaner py_err_cleaner(false);
370  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
371  auto pfunc = self.ResolveName<PythonCallable>("handle_stop");
372
373  if (!pfunc.IsAllocated())
374    return true;
375
376  std::shared_ptr<lldb::SBStream> sb_stream = std::make_shared<lldb::SBStream>();
377  PythonObject sb_stream_arg = SWIGBridge::ToSWIGWrapper(sb_stream);
378  PythonObject result =
379      pfunc(SWIGBridge::ToSWIGWrapper(std::move(exc_ctx_sp)), sb_stream_arg);
380
381  if (PyErr_Occurred()) {
382    stream->PutCString("Python error occurred handling stop-hook.");
383    PyErr_Print();
384    PyErr_Clear();
385    return true;
386  }
387
388  // Now add the result to the output stream.  SBStream only
389  // makes an internally help StreamString which I can't interpose, so I
390  // have to copy it over here.
391  stream->PutCString(sb_stream->GetData());
392  sb_stream_arg.release();
393
394  if (result.get() == Py_False)
395    return false;
396  else
397    return true;
398}
399
400// wrapper that calls an optional instance member of an object taking no
401// arguments
402static PyObject *LLDBSwigPython_CallOptionalMember(
403    PyObject * implementor, char *callee_name,
404    PyObject *ret_if_not_found = Py_None, bool *was_found = NULL) {
405  PyErr_Cleaner py_err_cleaner(false);
406
407  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
408  auto pfunc = self.ResolveName<PythonCallable>(callee_name);
409
410  if (!pfunc.IsAllocated()) {
411    if (was_found)
412      *was_found = false;
413    Py_XINCREF(ret_if_not_found);
414    return ret_if_not_found;
415  }
416
417  if (was_found)
418    *was_found = true;
419
420  PythonObject result = pfunc();
421  return result.release();
422}
423
424size_t lldb_private::python::SWIGBridge::LLDBSwigPython_CalculateNumChildren(PyObject * implementor,
425                                                         uint32_t max) {
426  PythonObject self(PyRefType::Borrowed, implementor);
427  auto pfunc = self.ResolveName<PythonCallable>("num_children");
428
429  if (!pfunc.IsAllocated())
430    return 0;
431
432  auto arg_info = pfunc.GetArgInfo();
433  if (!arg_info) {
434    llvm::consumeError(arg_info.takeError());
435    return 0;
436  }
437
438  size_t ret_val;
439  if (arg_info.get().max_positional_args < 1)
440    ret_val = unwrapOrSetPythonException(As<long long>(pfunc.Call()));
441  else
442    ret_val = unwrapOrSetPythonException(
443        As<long long>(pfunc.Call(PythonInteger(max))));
444
445  if (PyErr_Occurred()) {
446    PyErr_Print();
447    PyErr_Clear();
448    return 0;
449  }
450
451  if (arg_info.get().max_positional_args < 1)
452    ret_val = std::min(ret_val, static_cast<size_t>(max));
453
454  return ret_val;
455}
456
457PyObject *lldb_private::python::SWIGBridge::LLDBSwigPython_GetChildAtIndex(PyObject * implementor,
458                                                       uint32_t idx) {
459  PyErr_Cleaner py_err_cleaner(true);
460
461  PythonObject self(PyRefType::Borrowed, implementor);
462  auto pfunc = self.ResolveName<PythonCallable>("get_child_at_index");
463
464  if (!pfunc.IsAllocated())
465    return nullptr;
466
467  PythonObject result = pfunc(PythonInteger(idx));
468
469  if (!result.IsAllocated())
470    return nullptr;
471
472  lldb::SBValue *sbvalue_ptr = nullptr;
473  if (SWIG_ConvertPtr(result.get(), (void **)&sbvalue_ptr,
474                      SWIGTYPE_p_lldb__SBValue, 0) == -1)
475    return nullptr;
476
477  if (sbvalue_ptr == nullptr)
478    return nullptr;
479
480  return result.release();
481}
482
483int lldb_private::python::SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(
484    PyObject * implementor, const char *child_name) {
485  PyErr_Cleaner py_err_cleaner(true);
486
487  PythonObject self(PyRefType::Borrowed, implementor);
488  auto pfunc = self.ResolveName<PythonCallable>("get_child_index");
489
490  if (!pfunc.IsAllocated())
491    return UINT32_MAX;
492
493  llvm::Expected<PythonObject> result = pfunc.Call(PythonString(child_name));
494
495  long long retval =
496      unwrapOrSetPythonException(As<long long>(std::move(result)));
497
498  if (PyErr_Occurred()) {
499    PyErr_Clear(); // FIXME print this? do something else
500    return UINT32_MAX;
501  }
502
503  if (retval >= 0)
504    return (uint32_t)retval;
505
506  return UINT32_MAX;
507}
508
509bool lldb_private::python::SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(PyObject *
510                                                              implementor) {
511  bool ret_val = false;
512
513  static char callee_name[] = "update";
514
515  PyObject *py_return =
516      LLDBSwigPython_CallOptionalMember(implementor, callee_name);
517
518  if (py_return == Py_True)
519    ret_val = true;
520
521  Py_XDECREF(py_return);
522
523  return ret_val;
524}
525
526bool lldb_private::python::SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
527    PyObject * implementor) {
528  bool ret_val = false;
529
530  static char callee_name[] = "has_children";
531
532  PyObject *py_return =
533      LLDBSwigPython_CallOptionalMember(implementor, callee_name, Py_True);
534
535  if (py_return == Py_True)
536    ret_val = true;
537
538  Py_XDECREF(py_return);
539
540  return ret_val;
541}
542
543PyObject *lldb_private::python::SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(
544    PyObject * implementor) {
545  PyObject *ret_val = nullptr;
546
547  static char callee_name[] = "get_value";
548
549  PyObject *py_return =
550      LLDBSwigPython_CallOptionalMember(implementor, callee_name, Py_None);
551
552  if (py_return == Py_None || py_return == nullptr)
553    ret_val = nullptr;
554
555  lldb::SBValue *sbvalue_ptr = NULL;
556
557  if (SWIG_ConvertPtr(py_return, (void **)&sbvalue_ptr,
558                      SWIGTYPE_p_lldb__SBValue, 0) == -1)
559    ret_val = nullptr;
560  else if (sbvalue_ptr == NULL)
561    ret_val = nullptr;
562  else
563    ret_val = py_return;
564
565  Py_XDECREF(py_return);
566  return ret_val;
567}
568
569void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBData(PyObject * data) {
570  lldb::SBData *sb_ptr = nullptr;
571
572  int valid_cast =
573      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBData, 0);
574
575  if (valid_cast == -1)
576    return NULL;
577
578  return sb_ptr;
579}
580
581void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBBreakpoint(PyObject * data) {
582  lldb::SBBreakpoint *sb_ptr = nullptr;
583
584  int valid_cast =
585      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBBreakpoint, 0);
586
587  if (valid_cast == -1)
588    return NULL;
589
590  return sb_ptr;
591}
592
593void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBAttachInfo(PyObject * data) {
594  lldb::SBAttachInfo *sb_ptr = nullptr;
595
596  int valid_cast =
597      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBAttachInfo, 0);
598
599  if (valid_cast == -1)
600    return NULL;
601
602  return sb_ptr;
603}
604
605void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBLaunchInfo(PyObject * data) {
606  lldb::SBLaunchInfo *sb_ptr = nullptr;
607
608  int valid_cast =
609      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBLaunchInfo, 0);
610
611  if (valid_cast == -1)
612    return NULL;
613
614  return sb_ptr;
615}
616
617void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBError(PyObject * data) {
618  lldb::SBError *sb_ptr = nullptr;
619
620  int valid_cast =
621      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBError, 0);
622
623  if (valid_cast == -1)
624    return NULL;
625
626  return sb_ptr;
627}
628
629void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBEvent(PyObject * data) {
630  lldb::SBEvent *sb_ptr = nullptr;
631
632  int valid_cast =
633      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBEvent, 0);
634
635  if (valid_cast == -1)
636    return NULL;
637
638  return sb_ptr;
639}
640
641void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBStream(PyObject * data) {
642  lldb::SBStream *sb_ptr = nullptr;
643
644  int valid_cast =
645      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBStream, 0);
646
647  if (valid_cast == -1)
648    return NULL;
649
650  return sb_ptr;
651}
652
653void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBValue(PyObject * data) {
654  lldb::SBValue *sb_ptr = NULL;
655
656  int valid_cast =
657      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBValue, 0);
658
659  if (valid_cast == -1)
660    return NULL;
661
662  return sb_ptr;
663}
664
665void *lldb_private::python::LLDBSWIGPython_CastPyObjectToSBMemoryRegionInfo(PyObject *
666                                                                    data) {
667  lldb::SBMemoryRegionInfo *sb_ptr = NULL;
668
669  int valid_cast = SWIG_ConvertPtr(data, (void **)&sb_ptr,
670                                   SWIGTYPE_p_lldb__SBMemoryRegionInfo, 0);
671
672  if (valid_cast == -1)
673    return NULL;
674
675  return sb_ptr;
676}
677
678bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallCommand(
679    const char *python_function_name, const char *session_dictionary_name,
680    lldb::DebuggerSP debugger, const char *args,
681    lldb_private::CommandReturnObject &cmd_retobj,
682    lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
683
684  PyErr_Cleaner py_err_cleaner(true);
685  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
686      session_dictionary_name);
687  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
688      python_function_name, dict);
689
690  if (!pfunc.IsAllocated())
691    return false;
692
693  auto argc = pfunc.GetArgInfo();
694  if (!argc) {
695    llvm::consumeError(argc.takeError());
696    return false;
697  }
698  PythonObject debugger_arg = SWIGBridge::ToSWIGWrapper(std::move(debugger));
699  auto cmd_retobj_arg = SWIGBridge::ToSWIGWrapper(cmd_retobj);
700
701  if (argc.get().max_positional_args < 5u)
702    pfunc(debugger_arg, PythonString(args), cmd_retobj_arg.obj(), dict);
703  else
704    pfunc(debugger_arg, PythonString(args),
705          SWIGBridge::ToSWIGWrapper(std::move(exe_ctx_ref_sp)), cmd_retobj_arg.obj(), dict);
706
707  return true;
708}
709
710bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallCommandObject(
711    PyObject *implementor, lldb::DebuggerSP debugger, const char *args,
712    lldb_private::CommandReturnObject &cmd_retobj,
713    lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
714
715  PyErr_Cleaner py_err_cleaner(true);
716
717  PythonObject self(PyRefType::Borrowed, implementor);
718  auto pfunc = self.ResolveName<PythonCallable>("__call__");
719
720  if (!pfunc.IsAllocated())
721    return false;
722
723  auto cmd_retobj_arg = SWIGBridge::ToSWIGWrapper(cmd_retobj);
724
725  pfunc(SWIGBridge::ToSWIGWrapper(std::move(debugger)), PythonString(args),
726        SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp), cmd_retobj_arg.obj());
727
728  return true;
729}
730
731std::optional<std::string>
732lldb_private::python::SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand(PyObject *implementor,
733                                               std::string &command) {
734  PyErr_Cleaner py_err_cleaner(true);
735
736  PythonObject self(PyRefType::Borrowed, implementor);
737  auto pfunc = self.ResolveName<PythonCallable>("get_repeat_command");
738  // If not implemented, repeat the exact command.
739  if (!pfunc.IsAllocated())
740    return std::nullopt;
741
742  PythonString command_str(command);
743  PythonObject result = pfunc(command_str);
744
745  // A return of None is the equivalent of nullopt - means repeat
746  // the command as is:
747  if (result.IsNone())
748    return std::nullopt;
749
750  return result.Str().GetString().str();
751}
752
753#include "lldb/Interpreter/CommandReturnObject.h"
754
755bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
756    PyObject *implementor, lldb::DebuggerSP debugger, lldb_private::StructuredDataImpl &args_impl,
757    lldb_private::CommandReturnObject &cmd_retobj,
758    lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
759
760  PyErr_Cleaner py_err_cleaner(true);
761
762  PythonObject self(PyRefType::Borrowed, implementor);
763  auto pfunc = self.ResolveName<PythonCallable>("__call__");
764
765  if (!pfunc.IsAllocated()) {
766    cmd_retobj.AppendError("Could not find '__call__' method in implementation class");
767    return false;
768  }
769
770  pfunc(SWIGBridge::ToSWIGWrapper(std::move(debugger)), SWIGBridge::ToSWIGWrapper(args_impl),
771        SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp), SWIGBridge::ToSWIGWrapper(cmd_retobj).obj());
772
773  return true;
774}
775
776PythonObject lldb_private::python::SWIGBridge::LLDBSWIGPythonCreateOSPlugin(
777    const char *python_class_name, const char *session_dictionary_name,
778    const lldb::ProcessSP &process_sp) {
779  if (python_class_name == NULL || python_class_name[0] == '\0' ||
780      !session_dictionary_name)
781    return PythonObject();
782
783  PyErr_Cleaner py_err_cleaner(true);
784
785  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
786      session_dictionary_name);
787  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
788      python_class_name, dict);
789
790  if (!pfunc.IsAllocated())
791    return PythonObject();
792
793  return pfunc(SWIGBridge::ToSWIGWrapper(process_sp));
794}
795
796PythonObject lldb_private::python::SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer(
797    const char *python_class_name, const char *session_dictionary_name) {
798  if (python_class_name == NULL || python_class_name[0] == '\0' ||
799      !session_dictionary_name)
800    return PythonObject();
801
802  PyErr_Cleaner py_err_cleaner(true);
803
804  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
805      session_dictionary_name);
806  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
807      python_class_name, dict);
808
809  if (!pfunc.IsAllocated())
810    return PythonObject();
811
812  return pfunc();
813}
814
815PyObject *lldb_private::python::SWIGBridge::LLDBSwigPython_GetRecognizedArguments(
816    PyObject * implementor, const lldb::StackFrameSP &frame_sp) {
817  static char callee_name[] = "get_recognized_arguments";
818
819  PythonObject arg = SWIGBridge::ToSWIGWrapper(frame_sp);
820
821  PythonString str(callee_name);
822  PyObject *result =
823      PyObject_CallMethodObjArgs(implementor, str.get(), arg.get(), NULL);
824  return result;
825}
826
827void *lldb_private::python::SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
828    void *module, const char *setting, const lldb::TargetSP &target_sp) {
829  if (!module || !setting)
830    Py_RETURN_NONE;
831
832  PyErr_Cleaner py_err_cleaner(true);
833  PythonObject py_module(PyRefType::Borrowed, (PyObject *)module);
834  auto pfunc = py_module.ResolveName<PythonCallable>("get_dynamic_setting");
835
836  if (!pfunc.IsAllocated())
837    Py_RETURN_NONE;
838
839  auto result = pfunc(SWIGBridge::ToSWIGWrapper(target_sp), PythonString(setting));
840
841  return result.release();
842}
843
844bool lldb_private::python::SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess(
845    const char *python_function_name, const char *session_dictionary_name,
846    const lldb::ProcessSP &process, std::string &output) {
847
848  if (python_function_name == NULL || python_function_name[0] == '\0' ||
849      !session_dictionary_name)
850    return false;
851
852  PyErr_Cleaner py_err_cleaner(true);
853
854  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
855      session_dictionary_name);
856  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
857      python_function_name, dict);
858
859  if (!pfunc.IsAllocated())
860    return false;
861
862  auto result = pfunc(SWIGBridge::ToSWIGWrapper(process), dict);
863
864  output = result.Str().GetString().str();
865
866  return true;
867}
868
869std::optional<std::string> lldb_private::python::SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread(
870    const char *python_function_name, const char *session_dictionary_name,
871    lldb::ThreadSP thread) {
872  if (python_function_name == NULL || python_function_name[0] == '\0' ||
873      !session_dictionary_name)
874    return std::nullopt;
875
876  PyErr_Cleaner py_err_cleaner(true);
877
878  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
879      session_dictionary_name);
880  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
881      python_function_name, dict);
882
883  if (!pfunc.IsAllocated())
884    return std::nullopt;
885
886  auto result = pfunc(SWIGBridge::ToSWIGWrapper(std::move(thread)), dict);
887
888  return result.Str().GetString().str();
889}
890
891bool lldb_private::python::SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget(
892    const char *python_function_name, const char *session_dictionary_name,
893    const lldb::TargetSP &target, std::string &output) {
894
895  if (python_function_name == NULL || python_function_name[0] == '\0' ||
896      !session_dictionary_name)
897    return false;
898
899  PyErr_Cleaner py_err_cleaner(true);
900
901  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
902      session_dictionary_name);
903  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
904      python_function_name, dict);
905
906  if (!pfunc.IsAllocated())
907    return false;
908
909  auto result = pfunc(SWIGBridge::ToSWIGWrapper(target), dict);
910
911  output = result.Str().GetString().str();
912
913  return true;
914}
915
916std::optional<std::string> lldb_private::python::SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame(
917    const char *python_function_name, const char *session_dictionary_name,
918    lldb::StackFrameSP frame) {
919  if (python_function_name == NULL || python_function_name[0] == '\0' ||
920      !session_dictionary_name)
921    return std::nullopt;
922
923  PyErr_Cleaner py_err_cleaner(true);
924
925  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
926      session_dictionary_name);
927  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
928      python_function_name, dict);
929
930  if (!pfunc.IsAllocated())
931    return std::nullopt;
932
933  auto result = pfunc(SWIGBridge::ToSWIGWrapper(std::move(frame)), dict);
934
935  return result.Str().GetString().str();
936}
937
938bool lldb_private::python::SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue(
939    const char *python_function_name, const char *session_dictionary_name,
940    const lldb::ValueObjectSP &value, std::string &output) {
941
942  if (python_function_name == NULL || python_function_name[0] == '\0' ||
943      !session_dictionary_name)
944    return false;
945
946  PyErr_Cleaner py_err_cleaner(true);
947
948  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
949      session_dictionary_name);
950  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
951      python_function_name, dict);
952
953  if (!pfunc.IsAllocated())
954    return false;
955
956  auto result = pfunc(SWIGBridge::ToSWIGWrapper(value), dict);
957
958  output = result.Str().GetString().str();
959
960  return true;
961}
962
963bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallModuleInit(
964    const char *python_module_name, const char *session_dictionary_name,
965    lldb::DebuggerSP debugger) {
966  std::string python_function_name_string = python_module_name;
967  python_function_name_string += ".__lldb_init_module";
968  const char *python_function_name = python_function_name_string.c_str();
969
970  PyErr_Cleaner py_err_cleaner(true);
971
972  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
973      session_dictionary_name);
974  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
975      python_function_name, dict);
976
977  // This method is optional and need not exist.  So if we don't find it,
978  // it's actually a success, not a failure.
979  if (!pfunc.IsAllocated())
980    return true;
981
982  pfunc(SWIGBridge::ToSWIGWrapper(std::move(debugger)), dict);
983
984  return true;
985}
986
987lldb::ValueObjectSP lldb_private::python::SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(
988    void *data) {
989  lldb::ValueObjectSP valobj_sp;
990  if (data) {
991    lldb::SBValue *sb_ptr = (lldb::SBValue *)data;
992    valobj_sp = sb_ptr->GetSP();
993  }
994  return valobj_sp;
995}
996
997// For the LogOutputCallback functions
998static void LLDBSwigPythonCallPythonLogOutputCallback(const char *str,
999                                                      void *baton) {
1000  if (baton != Py_None) {
1001    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
1002    PyObject *result = PyObject_CallFunction(
1003        reinterpret_cast<PyObject *>(baton), const_cast<char *>("s"), str);
1004    Py_XDECREF(result);
1005    SWIG_PYTHON_THREAD_END_BLOCK;
1006  }
1007}
1008
1009// For DebuggerTerminateCallback functions
1010static void LLDBSwigPythonCallPythonSBDebuggerTerminateCallback(lldb::user_id_t debugger_id,
1011                                                      void *baton) {
1012  if (baton != Py_None) {
1013    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
1014    PyObject *result = PyObject_CallFunction(
1015        reinterpret_cast<PyObject *>(baton), const_cast<char *>("l"), debugger_id);
1016    Py_XDECREF(result);
1017    SWIG_PYTHON_THREAD_END_BLOCK;
1018  }
1019}
1020
1021static bool LLDBSwigPythonCallPythonSBCommandInterpreterSetCommandOverrideCallback(void *baton, const char **argv) {
1022  bool ret_val = false;
1023  if (baton != Py_None) {
1024    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
1025    // Create a PyList of items since we're going to pass it to the callback as a tuple
1026    // of arguments.
1027    PyObject *py_argv = PyList_New(0);
1028    for (const char **arg = argv; arg && *arg; arg++) {
1029      std::string arg_string = *arg;
1030      PyObject *py_string = PyUnicode_FromStringAndSize(arg_string.c_str(), arg_string.size());
1031      PyList_Append(py_argv, py_string);
1032    }
1033
1034    PyObject *result = PyObject_CallObject(
1035        reinterpret_cast<PyObject *>(baton), PyList_AsTuple(py_argv));
1036    ret_val = result ? PyObject_IsTrue(result) : false;
1037    Py_XDECREF(result);
1038    SWIG_PYTHON_THREAD_END_BLOCK;
1039  }
1040  return ret_val;
1041}
1042
1043static SBError LLDBSwigPythonCallLocateModuleCallback(
1044    void *callback_baton, const SBModuleSpec &module_spec_sb,
1045    SBFileSpec &module_file_spec_sb, SBFileSpec &symbol_file_spec_sb) {
1046  SWIG_Python_Thread_Block swig_thread_block;
1047
1048  PyErr_Cleaner py_err_cleaner(true);
1049  PythonObject module_spec_arg = SWIGBridge::ToSWIGWrapper(
1050      std::make_unique<SBModuleSpec>(module_spec_sb));
1051  PythonObject module_file_spec_arg = SWIGBridge::ToSWIGWrapper(
1052      std::make_unique<SBFileSpec>(module_file_spec_sb));
1053  PythonObject symbol_file_spec_arg = SWIGBridge::ToSWIGWrapper(
1054      std::make_unique<SBFileSpec>(symbol_file_spec_sb));
1055
1056  PythonCallable callable =
1057      Retain<PythonCallable>(reinterpret_cast<PyObject *>(callback_baton));
1058  if (!callable.IsValid()) {
1059    return SBError("The callback callable is not valid.");
1060  }
1061
1062  PythonObject result = callable(module_spec_arg, module_file_spec_arg,
1063                                 symbol_file_spec_arg);
1064
1065  if (!result.IsAllocated())
1066    return SBError("No result.");
1067  lldb::SBError *sb_error_ptr = nullptr;
1068  if (SWIG_ConvertPtr(result.get(), (void **)&sb_error_ptr,
1069                      SWIGTYPE_p_lldb__SBError, 0) == -1) {
1070    return SBError("Result is not SBError.");
1071  }
1072
1073  if (sb_error_ptr->Success()) {
1074    lldb::SBFileSpec *sb_module_file_spec_ptr = nullptr;
1075    if (SWIG_ConvertPtr(module_file_spec_arg.get(),
1076                        (void **)&sb_module_file_spec_ptr,
1077                        SWIGTYPE_p_lldb__SBFileSpec, 0) == -1)
1078      return SBError("module_file_spec is not SBFileSpec.");
1079
1080    lldb::SBFileSpec *sb_symbol_file_spec_ptr = nullptr;
1081    if (SWIG_ConvertPtr(symbol_file_spec_arg.get(),
1082                        (void **)&sb_symbol_file_spec_ptr,
1083                        SWIGTYPE_p_lldb__SBFileSpec, 0) == -1)
1084      return SBError("symbol_file_spec is not SBFileSpec.");
1085
1086    module_file_spec_sb = *sb_module_file_spec_ptr;
1087    symbol_file_spec_sb = *sb_symbol_file_spec_ptr;
1088  }
1089
1090  return *sb_error_ptr;
1091}
1092%}
1093