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