xref: /freebsd/contrib/llvm-project/lldb/bindings/python/python-wrapper.swig (revision 734e82fe33aa764367791a7d603b383996c6b40b)
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::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 = ToSWIGWrapper(frame_sp);
41  PythonObject bp_loc_arg = 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, 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::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(ToSWIGWrapper(frame_sp), 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::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(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::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 = 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, ToSWIGWrapper(*options_sp));
175
176  retval = result.Str().GetString().str();
177
178  return true;
179}
180
181PythonObject lldb_private::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::make_unique<lldb::SBValue>(valobj_sp);
199  sb_value->SetPreferSyntheticValue(false);
200
201  PythonObject val_arg = 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::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(ToSWIGWrapper(std::move(debugger_sp)), dict);
230}
231
232PythonObject lldb_private::LLDBSwigPythonCreateScriptedObject(
233    const char *python_class_name, const char *session_dictionary_name,
234    lldb::ExecutionContextRefSP exe_ctx_sp,
235    const lldb_private::StructuredDataImpl &args_impl,
236    std::string &error_string) {
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    error_string.append("could not find script class: ");
250    error_string.append(python_class_name);
251    return PythonObject();
252  }
253
254  llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
255  if (!arg_info) {
256    llvm::handleAllErrors(
257        arg_info.takeError(),
258        [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
259        [&](const llvm::ErrorInfoBase &E) {
260          error_string.append(E.message());
261        });
262    return PythonObject();
263  }
264
265  PythonObject result = {};
266  if (arg_info.get().max_positional_args == 2) {
267      result = pfunc(ToSWIGWrapper(exe_ctx_sp), ToSWIGWrapper(args_impl));
268  } else {
269    error_string.assign("wrong number of arguments in __init__, should be 2 "
270                        "(not including self)");
271  }
272  return result;
273}
274
275PythonObject lldb_private::LLDBSwigPythonCreateScriptedThreadPlan(
276    const char *python_class_name, const char *session_dictionary_name,
277    const lldb_private::StructuredDataImpl &args_impl,
278    std::string &error_string, const lldb::ThreadPlanSP &thread_plan_sp) {
279  if (python_class_name == NULL || python_class_name[0] == '\0' ||
280      !session_dictionary_name)
281    return PythonObject();
282
283  PyErr_Cleaner py_err_cleaner(true);
284
285  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
286      session_dictionary_name);
287  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
288      python_class_name, dict);
289
290  if (!pfunc.IsAllocated()) {
291    error_string.append("could not find script class: ");
292    error_string.append(python_class_name);
293    return PythonObject();
294  }
295
296  PythonObject tp_arg = ToSWIGWrapper(thread_plan_sp);
297
298  llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
299  if (!arg_info) {
300    llvm::handleAllErrors(
301        arg_info.takeError(),
302        [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
303        [&](const llvm::ErrorInfoBase &E) {
304          error_string.append(E.message());
305        });
306    return PythonObject();
307  }
308
309  PythonObject result = {};
310  auto args_sb = std::make_unique<lldb::SBStructuredData>(args_impl);
311  if (arg_info.get().max_positional_args == 2) {
312    if (args_sb->IsValid()) {
313      error_string.assign(
314          "args passed, but __init__ does not take an args dictionary");
315      return PythonObject();
316    }
317    result = pfunc(tp_arg, dict);
318  } else if (arg_info.get().max_positional_args >= 3) {
319    result = pfunc(tp_arg, ToSWIGWrapper(std::move(args_sb)), dict);
320  } else {
321    error_string.assign("wrong number of arguments in __init__, should be 2 or "
322                        "3 (not including self)");
323    return PythonObject();
324  }
325
326  // FIXME: At this point we should check that the class we found supports all
327  // the methods that we need.
328
329  return result;
330}
331
332bool lldb_private::LLDBSWIGPythonCallThreadPlan(
333    void *implementor, const char *method_name, lldb_private::Event *event,
334    bool &got_error) {
335  got_error = false;
336
337  PyErr_Cleaner py_err_cleaner(false);
338  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
339  auto pfunc = self.ResolveName<PythonCallable>(method_name);
340
341  if (!pfunc.IsAllocated())
342    return false;
343
344  PythonObject result;
345  if (event != nullptr) {
346    ScopedPythonObject<SBEvent> event_arg = ToSWIGWrapper(event);
347    result = pfunc(event_arg.obj());
348  } else
349    result = pfunc();
350
351  if (PyErr_Occurred()) {
352    got_error = true;
353    printf("Return value was neither false nor true for call to %s.\n",
354           method_name);
355    PyErr_Print();
356    return false;
357  }
358
359  if (result.get() == Py_True)
360    return true;
361  else if (result.get() == Py_False)
362    return false;
363
364  // Somebody returned the wrong thing...
365  got_error = true;
366  printf("Wrong return value type for call to %s.\n", method_name);
367  return false;
368}
369
370PythonObject lldb_private::LLDBSwigPythonCreateScriptedBreakpointResolver(
371    const char *python_class_name, const char *session_dictionary_name,
372    const StructuredDataImpl &args_impl,
373    const lldb::BreakpointSP &breakpoint_sp) {
374
375  if (python_class_name == NULL || python_class_name[0] == '\0' ||
376      !session_dictionary_name)
377    return PythonObject();
378
379  PyErr_Cleaner py_err_cleaner(true);
380
381  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
382      session_dictionary_name);
383  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
384      python_class_name, dict);
385
386  if (!pfunc.IsAllocated())
387    return PythonObject();
388
389  PythonObject result =
390      pfunc(ToSWIGWrapper(breakpoint_sp), ToSWIGWrapper(args_impl), dict);
391  // FIXME: At this point we should check that the class we found supports all
392  // the methods that we need.
393
394  if (result.IsAllocated()) {
395    // Check that __callback__ is defined:
396    auto callback_func = result.ResolveName<PythonCallable>("__callback__");
397    if (callback_func.IsAllocated())
398      return result;
399  }
400  return PythonObject();
401}
402
403unsigned int lldb_private::LLDBSwigPythonCallBreakpointResolver(
404    void *implementor, const char *method_name,
405    lldb_private::SymbolContext *sym_ctx) {
406  PyErr_Cleaner py_err_cleaner(false);
407  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
408  auto pfunc = self.ResolveName<PythonCallable>(method_name);
409
410  if (!pfunc.IsAllocated())
411    return 0;
412
413  PythonObject result = sym_ctx ? pfunc(ToSWIGWrapper(*sym_ctx)) : pfunc();
414
415  if (PyErr_Occurred()) {
416    PyErr_Print();
417    PyErr_Clear();
418    return 0;
419  }
420
421  // The callback will return a bool, but we're need to also return ints
422  // so we're squirrelling the bool through as an int...  And if you return
423  // nothing, we'll continue.
424  if (strcmp(method_name, "__callback__") == 0) {
425    if (result.get() == Py_False)
426      return 0;
427    else
428      return 1;
429  }
430
431  long long ret_val = unwrapOrSetPythonException(As<long long>(result));
432
433  if (PyErr_Occurred()) {
434    PyErr_Print();
435    PyErr_Clear();
436    return 0;
437  }
438
439  return ret_val;
440}
441
442PythonObject lldb_private::LLDBSwigPythonCreateScriptedStopHook(
443    lldb::TargetSP target_sp, const char *python_class_name,
444    const char *session_dictionary_name, const StructuredDataImpl &args_impl,
445    Status &error) {
446  if (python_class_name == NULL || python_class_name[0] == '\0') {
447    error.SetErrorString("Empty class name.");
448    return PythonObject();
449  }
450  if (!session_dictionary_name) {
451    error.SetErrorString("No session dictionary");
452    return PythonObject();
453  }
454
455  PyErr_Cleaner py_err_cleaner(true);
456
457  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
458      session_dictionary_name);
459  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
460      python_class_name, dict);
461
462  if (!pfunc.IsAllocated()) {
463    error.SetErrorStringWithFormat("Could not find class: %s.",
464                                   python_class_name);
465    return PythonObject();
466  }
467
468  PythonObject result =
469      pfunc(ToSWIGWrapper(target_sp), ToSWIGWrapper(args_impl), dict);
470
471  if (result.IsAllocated()) {
472    // Check that the handle_stop callback is defined:
473    auto callback_func = result.ResolveName<PythonCallable>("handle_stop");
474    if (callback_func.IsAllocated()) {
475      if (auto args_info = callback_func.GetArgInfo()) {
476        size_t num_args = (*args_info).max_positional_args;
477        if (num_args != 2) {
478          error.SetErrorStringWithFormat(
479              "Wrong number of args for "
480              "handle_stop callback, should be 2 (excluding self), got: %zu",
481              num_args);
482          return PythonObject();
483        } else
484          return result;
485      } else {
486        error.SetErrorString("Couldn't get num arguments for handle_stop "
487                             "callback.");
488        return PythonObject();
489      }
490      return result;
491    } else {
492      error.SetErrorStringWithFormat("Class \"%s\" is missing the required "
493                                     "handle_stop callback.",
494                                     python_class_name);
495    }
496  }
497  return PythonObject();
498}
499
500bool lldb_private::LLDBSwigPythonStopHookCallHandleStop(
501    void *implementor, lldb::ExecutionContextRefSP exc_ctx_sp,
502    lldb::StreamSP stream) {
503  // handle_stop will return a bool with the meaning "should_stop"...
504  // If you return nothing we'll assume we are going to stop.
505  // Also any errors should return true, since we should stop on error.
506
507  PyErr_Cleaner py_err_cleaner(false);
508  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
509  auto pfunc = self.ResolveName<PythonCallable>("handle_stop");
510
511  if (!pfunc.IsAllocated())
512    return true;
513
514  auto *sb_stream = new lldb::SBStream();
515  PythonObject sb_stream_arg =
516      ToSWIGWrapper(std::unique_ptr<lldb::SBStream>(sb_stream));
517  PythonObject result =
518      pfunc(ToSWIGWrapper(std::move(exc_ctx_sp)), sb_stream_arg);
519
520  if (PyErr_Occurred()) {
521    stream->PutCString("Python error occurred handling stop-hook.");
522    PyErr_Print();
523    PyErr_Clear();
524    return true;
525  }
526
527  // Now add the result to the output stream.  SBStream only
528  // makes an internally help StreamString which I can't interpose, so I
529  // have to copy it over here.
530  stream->PutCString(sb_stream->GetData());
531
532  if (result.get() == Py_False)
533    return false;
534  else
535    return true;
536}
537
538// wrapper that calls an optional instance member of an object taking no
539// arguments
540static PyObject *LLDBSwigPython_CallOptionalMember(
541    PyObject * implementor, char *callee_name,
542    PyObject *ret_if_not_found = Py_None, bool *was_found = NULL) {
543  PyErr_Cleaner py_err_cleaner(false);
544
545  PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
546  auto pfunc = self.ResolveName<PythonCallable>(callee_name);
547
548  if (!pfunc.IsAllocated()) {
549    if (was_found)
550      *was_found = false;
551    Py_XINCREF(ret_if_not_found);
552    return ret_if_not_found;
553  }
554
555  if (was_found)
556    *was_found = true;
557
558  PythonObject result = pfunc();
559  return result.release();
560}
561
562size_t lldb_private::LLDBSwigPython_CalculateNumChildren(PyObject * implementor,
563                                                         uint32_t max) {
564  PythonObject self(PyRefType::Borrowed, implementor);
565  auto pfunc = self.ResolveName<PythonCallable>("num_children");
566
567  if (!pfunc.IsAllocated())
568    return 0;
569
570  auto arg_info = pfunc.GetArgInfo();
571  if (!arg_info) {
572    llvm::consumeError(arg_info.takeError());
573    return 0;
574  }
575
576  size_t ret_val;
577  if (arg_info.get().max_positional_args < 1)
578    ret_val = unwrapOrSetPythonException(As<long long>(pfunc.Call()));
579  else
580    ret_val = unwrapOrSetPythonException(
581        As<long long>(pfunc.Call(PythonInteger(max))));
582
583  if (PyErr_Occurred()) {
584    PyErr_Print();
585    PyErr_Clear();
586    return 0;
587  }
588
589  if (arg_info.get().max_positional_args < 1)
590    ret_val = std::min(ret_val, static_cast<size_t>(max));
591
592  return ret_val;
593}
594
595PyObject *lldb_private::LLDBSwigPython_GetChildAtIndex(PyObject * implementor,
596                                                       uint32_t idx) {
597  PyErr_Cleaner py_err_cleaner(true);
598
599  PythonObject self(PyRefType::Borrowed, implementor);
600  auto pfunc = self.ResolveName<PythonCallable>("get_child_at_index");
601
602  if (!pfunc.IsAllocated())
603    return nullptr;
604
605  PythonObject result = pfunc(PythonInteger(idx));
606
607  if (!result.IsAllocated())
608    return nullptr;
609
610  lldb::SBValue *sbvalue_ptr = nullptr;
611  if (SWIG_ConvertPtr(result.get(), (void **)&sbvalue_ptr,
612                      SWIGTYPE_p_lldb__SBValue, 0) == -1)
613    return nullptr;
614
615  if (sbvalue_ptr == nullptr)
616    return nullptr;
617
618  return result.release();
619}
620
621int lldb_private::LLDBSwigPython_GetIndexOfChildWithName(
622    PyObject * implementor, const char *child_name) {
623  PyErr_Cleaner py_err_cleaner(true);
624
625  PythonObject self(PyRefType::Borrowed, implementor);
626  auto pfunc = self.ResolveName<PythonCallable>("get_child_index");
627
628  if (!pfunc.IsAllocated())
629    return UINT32_MAX;
630
631  llvm::Expected<PythonObject> result = pfunc.Call(PythonString(child_name));
632
633  long long retval =
634      unwrapOrSetPythonException(As<long long>(std::move(result)));
635
636  if (PyErr_Occurred()) {
637    PyErr_Clear(); // FIXME print this? do something else
638    return UINT32_MAX;
639  }
640
641  if (retval >= 0)
642    return (uint32_t)retval;
643
644  return UINT32_MAX;
645}
646
647bool lldb_private::LLDBSwigPython_UpdateSynthProviderInstance(PyObject *
648                                                              implementor) {
649  bool ret_val = false;
650
651  static char callee_name[] = "update";
652
653  PyObject *py_return =
654      LLDBSwigPython_CallOptionalMember(implementor, callee_name);
655
656  if (py_return == Py_True)
657    ret_val = true;
658
659  Py_XDECREF(py_return);
660
661  return ret_val;
662}
663
664bool lldb_private::LLDBSwigPython_MightHaveChildrenSynthProviderInstance(
665    PyObject * implementor) {
666  bool ret_val = false;
667
668  static char callee_name[] = "has_children";
669
670  PyObject *py_return =
671      LLDBSwigPython_CallOptionalMember(implementor, callee_name, Py_True);
672
673  if (py_return == Py_True)
674    ret_val = true;
675
676  Py_XDECREF(py_return);
677
678  return ret_val;
679}
680
681PyObject *lldb_private::LLDBSwigPython_GetValueSynthProviderInstance(
682    PyObject * implementor) {
683  PyObject *ret_val = nullptr;
684
685  static char callee_name[] = "get_value";
686
687  PyObject *py_return =
688      LLDBSwigPython_CallOptionalMember(implementor, callee_name, Py_None);
689
690  if (py_return == Py_None || py_return == nullptr)
691    ret_val = nullptr;
692
693  lldb::SBValue *sbvalue_ptr = NULL;
694
695  if (SWIG_ConvertPtr(py_return, (void **)&sbvalue_ptr,
696                      SWIGTYPE_p_lldb__SBValue, 0) == -1)
697    ret_val = nullptr;
698  else if (sbvalue_ptr == NULL)
699    ret_val = nullptr;
700  else
701    ret_val = py_return;
702
703  Py_XDECREF(py_return);
704  return ret_val;
705}
706
707void *lldb_private::LLDBSWIGPython_CastPyObjectToSBData(PyObject * data) {
708  lldb::SBData *sb_ptr = nullptr;
709
710  int valid_cast =
711      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBData, 0);
712
713  if (valid_cast == -1)
714    return NULL;
715
716  return sb_ptr;
717}
718
719void *lldb_private::LLDBSWIGPython_CastPyObjectToSBError(PyObject * data) {
720  lldb::SBError *sb_ptr = nullptr;
721
722  int valid_cast =
723      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBError, 0);
724
725  if (valid_cast == -1)
726    return NULL;
727
728  return sb_ptr;
729}
730
731void *lldb_private::LLDBSWIGPython_CastPyObjectToSBValue(PyObject * data) {
732  lldb::SBValue *sb_ptr = NULL;
733
734  int valid_cast =
735      SWIG_ConvertPtr(data, (void **)&sb_ptr, SWIGTYPE_p_lldb__SBValue, 0);
736
737  if (valid_cast == -1)
738    return NULL;
739
740  return sb_ptr;
741}
742
743void *lldb_private::LLDBSWIGPython_CastPyObjectToSBMemoryRegionInfo(PyObject *
744                                                                    data) {
745  lldb::SBMemoryRegionInfo *sb_ptr = NULL;
746
747  int valid_cast = SWIG_ConvertPtr(data, (void **)&sb_ptr,
748                                   SWIGTYPE_p_lldb__SBMemoryRegionInfo, 0);
749
750  if (valid_cast == -1)
751    return NULL;
752
753  return sb_ptr;
754}
755
756bool lldb_private::LLDBSwigPythonCallCommand(
757    const char *python_function_name, const char *session_dictionary_name,
758    lldb::DebuggerSP debugger, const char *args,
759    lldb_private::CommandReturnObject &cmd_retobj,
760    lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
761
762  PyErr_Cleaner py_err_cleaner(true);
763  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
764      session_dictionary_name);
765  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
766      python_function_name, dict);
767
768  if (!pfunc.IsAllocated())
769    return false;
770
771  auto argc = pfunc.GetArgInfo();
772  if (!argc) {
773    llvm::consumeError(argc.takeError());
774    return false;
775  }
776  PythonObject debugger_arg = ToSWIGWrapper(std::move(debugger));
777  auto cmd_retobj_arg = ToSWIGWrapper(cmd_retobj);
778
779  if (argc.get().max_positional_args < 5u)
780    pfunc(debugger_arg, PythonString(args), cmd_retobj_arg.obj(), dict);
781  else
782    pfunc(debugger_arg, PythonString(args),
783          ToSWIGWrapper(std::move(exe_ctx_ref_sp)), cmd_retobj_arg.obj(), dict);
784
785  return true;
786}
787
788bool lldb_private::LLDBSwigPythonCallCommandObject(
789    PyObject *implementor, lldb::DebuggerSP debugger, const char *args,
790    lldb_private::CommandReturnObject &cmd_retobj,
791    lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
792
793  PyErr_Cleaner py_err_cleaner(true);
794
795  PythonObject self(PyRefType::Borrowed, implementor);
796  auto pfunc = self.ResolveName<PythonCallable>("__call__");
797
798  if (!pfunc.IsAllocated())
799    return false;
800
801  auto cmd_retobj_arg = ToSWIGWrapper(cmd_retobj);
802
803  pfunc(ToSWIGWrapper(std::move(debugger)), PythonString(args),
804        ToSWIGWrapper(exe_ctx_ref_sp), cmd_retobj_arg.obj());
805
806  return true;
807}
808
809PythonObject lldb_private::LLDBSWIGPythonCreateOSPlugin(
810    const char *python_class_name, const char *session_dictionary_name,
811    const lldb::ProcessSP &process_sp) {
812  if (python_class_name == NULL || python_class_name[0] == '\0' ||
813      !session_dictionary_name)
814    return PythonObject();
815
816  PyErr_Cleaner py_err_cleaner(true);
817
818  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
819      session_dictionary_name);
820  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
821      python_class_name, dict);
822
823  if (!pfunc.IsAllocated())
824    return PythonObject();
825
826  return pfunc(ToSWIGWrapper(process_sp));
827}
828
829PythonObject lldb_private::LLDBSWIGPython_CreateFrameRecognizer(
830    const char *python_class_name, const char *session_dictionary_name) {
831  if (python_class_name == NULL || python_class_name[0] == '\0' ||
832      !session_dictionary_name)
833    return PythonObject();
834
835  PyErr_Cleaner py_err_cleaner(true);
836
837  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
838      session_dictionary_name);
839  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
840      python_class_name, dict);
841
842  if (!pfunc.IsAllocated())
843    return PythonObject();
844
845  return pfunc();
846}
847
848PyObject *lldb_private::LLDBSwigPython_GetRecognizedArguments(
849    PyObject * implementor, const lldb::StackFrameSP &frame_sp) {
850  static char callee_name[] = "get_recognized_arguments";
851
852  PythonObject arg = ToSWIGWrapper(frame_sp);
853
854  PythonString str(callee_name);
855  PyObject *result =
856      PyObject_CallMethodObjArgs(implementor, str.get(), arg.get(), NULL);
857  return result;
858}
859
860void *lldb_private::LLDBSWIGPython_GetDynamicSetting(
861    void *module, const char *setting, const lldb::TargetSP &target_sp) {
862  if (!module || !setting)
863    Py_RETURN_NONE;
864
865  PyErr_Cleaner py_err_cleaner(true);
866  PythonObject py_module(PyRefType::Borrowed, (PyObject *)module);
867  auto pfunc = py_module.ResolveName<PythonCallable>("get_dynamic_setting");
868
869  if (!pfunc.IsAllocated())
870    Py_RETURN_NONE;
871
872  auto result = pfunc(ToSWIGWrapper(target_sp), PythonString(setting));
873
874  return result.release();
875}
876
877bool lldb_private::LLDBSWIGPythonRunScriptKeywordProcess(
878    const char *python_function_name, const char *session_dictionary_name,
879    const lldb::ProcessSP &process, std::string &output) {
880
881  if (python_function_name == NULL || python_function_name[0] == '\0' ||
882      !session_dictionary_name)
883    return false;
884
885  PyErr_Cleaner py_err_cleaner(true);
886
887  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
888      session_dictionary_name);
889  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
890      python_function_name, dict);
891
892  if (!pfunc.IsAllocated())
893    return false;
894
895  auto result = pfunc(ToSWIGWrapper(process), dict);
896
897  output = result.Str().GetString().str();
898
899  return true;
900}
901
902std::optional<std::string> lldb_private::LLDBSWIGPythonRunScriptKeywordThread(
903    const char *python_function_name, const char *session_dictionary_name,
904    lldb::ThreadSP thread) {
905  if (python_function_name == NULL || python_function_name[0] == '\0' ||
906      !session_dictionary_name)
907    return std::nullopt;
908
909  PyErr_Cleaner py_err_cleaner(true);
910
911  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
912      session_dictionary_name);
913  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
914      python_function_name, dict);
915
916  if (!pfunc.IsAllocated())
917    return std::nullopt;
918
919  auto result = pfunc(ToSWIGWrapper(std::move(thread)), dict);
920
921  return result.Str().GetString().str();
922}
923
924bool lldb_private::LLDBSWIGPythonRunScriptKeywordTarget(
925    const char *python_function_name, const char *session_dictionary_name,
926    const lldb::TargetSP &target, std::string &output) {
927
928  if (python_function_name == NULL || python_function_name[0] == '\0' ||
929      !session_dictionary_name)
930    return false;
931
932  PyErr_Cleaner py_err_cleaner(true);
933
934  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
935      session_dictionary_name);
936  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
937      python_function_name, dict);
938
939  if (!pfunc.IsAllocated())
940    return false;
941
942  auto result = pfunc(ToSWIGWrapper(target), dict);
943
944  output = result.Str().GetString().str();
945
946  return true;
947}
948
949std::optional<std::string> lldb_private::LLDBSWIGPythonRunScriptKeywordFrame(
950    const char *python_function_name, const char *session_dictionary_name,
951    lldb::StackFrameSP frame) {
952  if (python_function_name == NULL || python_function_name[0] == '\0' ||
953      !session_dictionary_name)
954    return std::nullopt;
955
956  PyErr_Cleaner py_err_cleaner(true);
957
958  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
959      session_dictionary_name);
960  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
961      python_function_name, dict);
962
963  if (!pfunc.IsAllocated())
964    return std::nullopt;
965
966  auto result = pfunc(ToSWIGWrapper(std::move(frame)), dict);
967
968  return result.Str().GetString().str();
969}
970
971bool lldb_private::LLDBSWIGPythonRunScriptKeywordValue(
972    const char *python_function_name, const char *session_dictionary_name,
973    const lldb::ValueObjectSP &value, std::string &output) {
974
975  if (python_function_name == NULL || python_function_name[0] == '\0' ||
976      !session_dictionary_name)
977    return false;
978
979  PyErr_Cleaner py_err_cleaner(true);
980
981  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
982      session_dictionary_name);
983  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
984      python_function_name, dict);
985
986  if (!pfunc.IsAllocated())
987    return false;
988
989  auto result = pfunc(ToSWIGWrapper(value), dict);
990
991  output = result.Str().GetString().str();
992
993  return true;
994}
995
996bool lldb_private::LLDBSwigPythonCallModuleInit(
997    const char *python_module_name, const char *session_dictionary_name,
998    lldb::DebuggerSP debugger) {
999  std::string python_function_name_string = python_module_name;
1000  python_function_name_string += ".__lldb_init_module";
1001  const char *python_function_name = python_function_name_string.c_str();
1002
1003  PyErr_Cleaner py_err_cleaner(true);
1004
1005  auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(
1006      session_dictionary_name);
1007  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
1008      python_function_name, dict);
1009
1010  // This method is optional and need not exist.  So if we don't find it,
1011  // it's actually a success, not a failure.
1012  if (!pfunc.IsAllocated())
1013    return true;
1014
1015  pfunc(ToSWIGWrapper(std::move(debugger)), dict);
1016
1017  return true;
1018}
1019
1020lldb::ValueObjectSP lldb_private::LLDBSWIGPython_GetValueObjectSPFromSBValue(
1021    void *data) {
1022  lldb::ValueObjectSP valobj_sp;
1023  if (data) {
1024    lldb::SBValue *sb_ptr = (lldb::SBValue *)data;
1025    valobj_sp = sb_ptr->GetSP();
1026  }
1027  return valobj_sp;
1028}
1029
1030// For the LogOutputCallback functions
1031static void LLDBSwigPythonCallPythonLogOutputCallback(const char *str,
1032                                                      void *baton) {
1033  if (baton != Py_None) {
1034    SWIG_PYTHON_THREAD_BEGIN_BLOCK;
1035    PyObject *result = PyObject_CallFunction(
1036        reinterpret_cast<PyObject *>(baton), const_cast<char *>("s"), str);
1037    Py_XDECREF(result);
1038    SWIG_PYTHON_THREAD_END_BLOCK;
1039  }
1040}
1041%}
1042