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