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