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    // I do not want the SBThreadPlan to be deallocated when going out of scope because python
275    // has ownership of it and will manage memory for this object by itself
276    lldb::SBThreadPlan *tp_value = new lldb::SBThreadPlan(thread_plan_sp);
277
278    PyErr_Cleaner py_err_cleaner(true);
279
280    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
281    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_class_name, dict);
282
283    if (!pfunc.IsAllocated()) {
284        error_string.append("could not find script class: ");
285        error_string.append(python_class_name);
286        return nullptr;
287    }
288
289    PythonObject tp_arg(PyRefType::Owned, SBTypeToSWIGWrapper(tp_value));
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        lldb::SBStructuredData *args_value = new lldb::SBStructuredData(args_impl);
316        PythonObject args_arg(PyRefType::Owned, SBTypeToSWIGWrapper(args_value));
317        result = pfunc(tp_arg, args_arg, dict);
318    } else {
319        error_string.assign("wrong number of arguments in __init__, should be 2 or 3 (not including self)");
320        Py_RETURN_NONE;
321    }
322
323    // FIXME: At this point we should check that the class we found supports all the methods
324    // that we need.
325
326    if (result.IsAllocated())
327        return result.release();
328    Py_RETURN_NONE;
329}
330
331SWIGEXPORT bool
332LLDBSWIGPythonCallThreadPlan
333(
334    void *implementor,
335    const char *method_name,
336    lldb_private::Event *event,
337    bool &got_error
338)
339{
340    got_error = false;
341
342    PyErr_Cleaner py_err_cleaner(false);
343    PythonObject self(PyRefType::Borrowed, static_cast<PyObject*>(implementor));
344    auto pfunc = self.ResolveName<PythonCallable>(method_name);
345
346    if (!pfunc.IsAllocated())
347        return false;
348
349    PythonObject result;
350    if (event != nullptr)
351    {
352        lldb::SBEvent sb_event(event);
353        PythonObject event_arg(PyRefType::Owned, SBTypeToSWIGWrapper(sb_event));
354        result = pfunc(event_arg);
355    }
356    else
357        result = pfunc();
358
359    if (PyErr_Occurred())
360    {
361        got_error = true;
362        printf ("Return value was neither false nor true for call to %s.\n", method_name);
363        PyErr_Print();
364        return false;
365    }
366
367    if (result.get() == Py_True)
368        return true;
369    else if (result.get() == Py_False)
370        return false;
371
372    // Somebody returned the wrong thing...
373    got_error = true;
374    printf ("Wrong return value type for call to %s.\n", method_name);
375    return false;
376}
377
378SWIGEXPORT void *
379LLDBSwigPythonCreateScriptedBreakpointResolver
380(
381    const char *python_class_name,
382    const char *session_dictionary_name,
383    lldb_private::StructuredDataImpl *args_impl,
384    lldb::BreakpointSP &breakpoint_sp
385)
386{
387    if (python_class_name == NULL || python_class_name[0] == '\0' || !session_dictionary_name)
388        Py_RETURN_NONE;
389
390    PyErr_Cleaner py_err_cleaner(true);
391
392    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
393    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_class_name, dict);
394
395    if (!pfunc.IsAllocated())
396        return nullptr;
397
398    lldb::SBBreakpoint *bkpt_value = new lldb::SBBreakpoint(breakpoint_sp);
399
400    PythonObject bkpt_arg(PyRefType::Owned, SBTypeToSWIGWrapper(bkpt_value));
401
402    lldb::SBStructuredData *args_value = new lldb::SBStructuredData(args_impl);
403    PythonObject args_arg(PyRefType::Owned, SBTypeToSWIGWrapper(args_value));
404
405    PythonObject result = pfunc(bkpt_arg, args_arg, dict);
406    // FIXME: At this point we should check that the class we found supports all the methods
407    // that we need.
408
409    if (result.IsAllocated())
410    {
411        // Check that __callback__ is defined:
412        auto callback_func = result.ResolveName<PythonCallable>("__callback__");
413        if (callback_func.IsAllocated())
414            return result.release();
415        else
416            result.release();
417    }
418    Py_RETURN_NONE;
419}
420
421SWIGEXPORT unsigned int
422LLDBSwigPythonCallBreakpointResolver
423(
424    void *implementor,
425    const char *method_name,
426    lldb_private::SymbolContext *sym_ctx
427)
428{
429    PyErr_Cleaner py_err_cleaner(false);
430    PythonObject self(PyRefType::Borrowed, static_cast<PyObject*>(implementor));
431    auto pfunc = self.ResolveName<PythonCallable>(method_name);
432
433    if (!pfunc.IsAllocated())
434        return 0;
435
436    PythonObject result;
437    if (sym_ctx != nullptr) {
438      lldb::SBSymbolContext sb_sym_ctx(sym_ctx);
439      PythonObject sym_ctx_arg(PyRefType::Owned, SBTypeToSWIGWrapper(sb_sym_ctx));
440      result = pfunc(sym_ctx_arg);
441    } else
442      result = pfunc();
443
444    if (PyErr_Occurred())
445    {
446        PyErr_Print();
447        PyErr_Clear();
448        return 0;
449    }
450
451    // The callback will return a bool, but we're need to also return ints
452    // so we're squirrelling the bool through as an int...  And if you return
453    // nothing, we'll continue.
454    if (strcmp(method_name, "__callback__") == 0) {
455        if (result.get() == Py_False)
456          return 0;
457        else
458          return 1;
459    }
460
461    long long ret_val = unwrapOrSetPythonException(As<long long>(result));
462
463    if (PyErr_Occurred()) {
464        PyErr_Print();
465        PyErr_Clear();
466        return 0;
467    }
468
469    return ret_val;
470}
471
472// wrapper that calls an optional instance member of an object taking no arguments
473static PyObject*
474LLDBSwigPython_CallOptionalMember
475(
476    PyObject* implementor,
477    char* callee_name,
478    PyObject* ret_if_not_found = Py_None,
479    bool* was_found = NULL
480)
481{
482    PyErr_Cleaner py_err_cleaner(false);
483
484    PythonObject self(PyRefType::Borrowed, static_cast<PyObject*>(implementor));
485    auto pfunc = self.ResolveName<PythonCallable>(callee_name);
486
487    if (!pfunc.IsAllocated())
488    {
489        if (was_found)
490            *was_found = false;
491        Py_XINCREF(ret_if_not_found);
492        return ret_if_not_found;
493    }
494
495    if (was_found)
496        *was_found = true;
497
498    PythonObject result = pfunc();
499    return result.release();
500}
501
502SWIGEXPORT size_t
503LLDBSwigPython_CalculateNumChildren
504(
505    PyObject *implementor,
506    uint32_t max
507)
508{
509    PythonObject self(PyRefType::Borrowed, implementor);
510    auto pfunc = self.ResolveName<PythonCallable>("num_children");
511
512    if (!pfunc.IsAllocated())
513        return 0;
514
515    auto arg_info = pfunc.GetArgInfo();
516    if (!arg_info) {
517        llvm::consumeError(arg_info.takeError());
518        return 0;
519    }
520
521    size_t ret_val;
522    if (arg_info.get().max_positional_args < 1)
523        ret_val = unwrapOrSetPythonException(As<long long>(pfunc.Call()));
524    else
525        ret_val = unwrapOrSetPythonException(As<long long>(pfunc.Call(PythonInteger(max))));
526
527    if (PyErr_Occurred())
528    {
529        PyErr_Print();
530        PyErr_Clear();
531        return 0;
532    }
533
534    if (arg_info.get().max_positional_args < 1)
535        ret_val = std::min(ret_val, static_cast<size_t>(max));
536
537    return ret_val;
538}
539
540SWIGEXPORT PyObject*
541LLDBSwigPython_GetChildAtIndex
542(
543    PyObject *implementor,
544    uint32_t idx
545)
546{
547    PyErr_Cleaner py_err_cleaner(true);
548
549    PythonObject self(PyRefType::Borrowed, implementor);
550    auto pfunc = self.ResolveName<PythonCallable>("get_child_at_index");
551
552    if (!pfunc.IsAllocated())
553        return nullptr;
554
555    PythonObject result = pfunc(PythonInteger(idx));
556
557    if (!result.IsAllocated())
558        return nullptr;
559
560    lldb::SBValue* sbvalue_ptr = nullptr;
561    if (SWIG_ConvertPtr(result.get(), (void**)&sbvalue_ptr, SWIGTYPE_p_lldb__SBValue, 0) == -1)
562        return nullptr;
563
564    if (sbvalue_ptr == nullptr)
565        return nullptr;
566
567    return result.release();
568}
569
570SWIGEXPORT int
571LLDBSwigPython_GetIndexOfChildWithName
572(
573    PyObject *implementor,
574    const char* child_name
575)
576{
577    PyErr_Cleaner py_err_cleaner(true);
578
579    PythonObject self(PyRefType::Borrowed, implementor);
580    auto pfunc = self.ResolveName<PythonCallable>("get_child_index");
581
582    if (!pfunc.IsAllocated())
583        return UINT32_MAX;
584
585    llvm::Expected<PythonObject> result = pfunc.Call(PythonString(child_name));
586
587    long long retval = unwrapOrSetPythonException(As<long long>(std::move(result)));
588
589    if (PyErr_Occurred()) { 
590        PyErr_Clear(); // FIXME print this? do something else
591        return UINT32_MAX;
592    }
593
594    if (retval >= 0)
595        return (uint32_t)retval;
596
597    return UINT32_MAX;
598}
599
600SWIGEXPORT bool
601LLDBSwigPython_UpdateSynthProviderInstance
602(
603    PyObject *implementor
604)
605{
606    bool ret_val = false;
607
608    static char callee_name[] = "update";
609
610    PyObject* py_return = LLDBSwigPython_CallOptionalMember(implementor,callee_name);
611
612    if (py_return == Py_True)
613        ret_val = true;
614
615    Py_XDECREF(py_return);
616
617    return ret_val;
618}
619
620SWIGEXPORT bool
621LLDBSwigPython_MightHaveChildrenSynthProviderInstance
622(
623    PyObject *implementor
624)
625{
626    bool ret_val = false;
627
628    static char callee_name[] = "has_children";
629
630    PyObject* py_return = LLDBSwigPython_CallOptionalMember(implementor,callee_name, Py_True);
631
632    if (py_return == Py_True)
633        ret_val = true;
634
635    Py_XDECREF(py_return);
636
637    return ret_val;
638}
639
640SWIGEXPORT PyObject*
641LLDBSwigPython_GetValueSynthProviderInstance
642(
643    PyObject *implementor
644)
645{
646    PyObject* ret_val = nullptr;
647
648    static char callee_name[] = "get_value";
649
650    PyObject* py_return = LLDBSwigPython_CallOptionalMember(implementor,callee_name, Py_None);
651
652    if (py_return == Py_None || py_return == nullptr)
653        ret_val = nullptr;
654
655    lldb::SBValue* sbvalue_ptr = NULL;
656
657    if (SWIG_ConvertPtr(py_return, (void**)&sbvalue_ptr, SWIGTYPE_p_lldb__SBValue, 0) == -1)
658        ret_val = nullptr;
659    else if (sbvalue_ptr == NULL)
660        ret_val = nullptr;
661    else
662        ret_val = py_return;
663
664    Py_XDECREF(py_return);
665    return ret_val;
666}
667
668SWIGEXPORT void*
669LLDBSWIGPython_CastPyObjectToSBValue
670(
671    PyObject* data
672)
673{
674    lldb::SBValue* sb_ptr = NULL;
675
676    int valid_cast = SWIG_ConvertPtr(data, (void**)&sb_ptr, SWIGTYPE_p_lldb__SBValue, 0);
677
678    if (valid_cast == -1)
679        return NULL;
680
681    return sb_ptr;
682}
683
684SWIGEXPORT bool
685LLDBSwigPythonCallCommand
686(
687    const char *python_function_name,
688    const char *session_dictionary_name,
689    lldb::DebuggerSP& debugger,
690    const char* args,
691    lldb_private::CommandReturnObject& cmd_retobj,
692    lldb::ExecutionContextRefSP exe_ctx_ref_sp
693)
694{
695    lldb::SBCommandReturnObject cmd_retobj_sb(cmd_retobj);
696    lldb::SBDebugger debugger_sb(debugger);
697    lldb::SBExecutionContext exe_ctx_sb(exe_ctx_ref_sp);
698
699    PyErr_Cleaner py_err_cleaner(true);
700    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
701    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name, dict);
702
703    if (!pfunc.IsAllocated())
704        return false;
705
706    // pass the pointer-to cmd_retobj_sb or watch the underlying object disappear from under you
707    // see comment above for SBCommandReturnObjectReleaser for further details
708    auto argc = pfunc.GetArgInfo();
709    if (!argc) {
710        llvm::consumeError(argc.takeError());
711        return false;
712    }
713    PythonObject debugger_arg(PyRefType::Owned, SBTypeToSWIGWrapper(debugger_sb));
714    PythonObject exe_ctx_arg(PyRefType::Owned, SBTypeToSWIGWrapper(exe_ctx_sb));
715    PythonObject cmd_retobj_arg(PyRefType::Owned, SBTypeToSWIGWrapper(&cmd_retobj_sb));
716
717    if (argc.get().max_positional_args < 5u)
718        pfunc(debugger_arg, PythonString(args), cmd_retobj_arg, dict);
719    else
720        pfunc(debugger_arg, PythonString(args), exe_ctx_arg, cmd_retobj_arg, dict);
721
722    return true;
723}
724
725SWIGEXPORT bool
726LLDBSwigPythonCallCommandObject
727(
728    PyObject *implementor,
729    lldb::DebuggerSP& debugger,
730    const char* args,
731    lldb_private::CommandReturnObject& cmd_retobj,
732    lldb::ExecutionContextRefSP exe_ctx_ref_sp
733)
734{
735    lldb::SBCommandReturnObject cmd_retobj_sb(cmd_retobj);
736    lldb::SBDebugger debugger_sb(debugger);
737    lldb::SBExecutionContext exe_ctx_sb(exe_ctx_ref_sp);
738
739    PyErr_Cleaner py_err_cleaner(true);
740
741    PythonObject self(PyRefType::Borrowed, implementor);
742    auto pfunc = self.ResolveName<PythonCallable>("__call__");
743
744    if (!pfunc.IsAllocated())
745        return false;
746
747    // pass the pointer-to cmd_retobj_sb or watch the underlying object disappear from under you
748    // see comment above for SBCommandReturnObjectReleaser for further details
749    PythonObject debugger_arg(PyRefType::Owned, SBTypeToSWIGWrapper(debugger_sb));
750    PythonObject exe_ctx_arg(PyRefType::Owned, SBTypeToSWIGWrapper(exe_ctx_sb));
751    PythonObject cmd_retobj_arg(PyRefType::Owned, SBTypeToSWIGWrapper(&cmd_retobj_sb));
752
753    pfunc(debugger_arg, PythonString(args), exe_ctx_arg, cmd_retobj_arg);
754
755    return true;
756}
757
758SWIGEXPORT void*
759LLDBSWIGPythonCreateOSPlugin
760(
761    const char *python_class_name,
762    const char *session_dictionary_name,
763    const lldb::ProcessSP& process_sp
764)
765{
766    if (python_class_name == NULL || python_class_name[0] == '\0' || !session_dictionary_name)
767        Py_RETURN_NONE;
768
769    PyErr_Cleaner py_err_cleaner(true);
770
771    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
772    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_class_name, dict);
773
774    if (!pfunc.IsAllocated())
775        Py_RETURN_NONE;
776
777    // I do not want the SBProcess to be deallocated when going out of scope because python
778    // has ownership of it and will manage memory for this object by itself
779    lldb::SBProcess *process_sb = new lldb::SBProcess(process_sp);
780    PythonObject process_arg(PyRefType::Owned, SBTypeToSWIGWrapper(process_sb));
781    if (!process_arg.IsAllocated())
782        Py_RETURN_NONE;
783
784    auto result = pfunc(process_arg);
785
786    if (result.IsAllocated())
787        return result.release();
788
789    Py_RETURN_NONE;
790}
791
792SWIGEXPORT void*
793LLDBSWIGPython_CreateFrameRecognizer
794(
795    const char *python_class_name,
796    const char *session_dictionary_name
797)
798{
799    if (python_class_name == NULL || python_class_name[0] == '\0' || !session_dictionary_name)
800        Py_RETURN_NONE;
801
802    PyErr_Cleaner py_err_cleaner(true);
803
804    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
805    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_class_name, dict);
806
807    if (!pfunc.IsAllocated())
808        Py_RETURN_NONE;
809
810    auto result = pfunc();
811
812    if (result.IsAllocated())
813        return result.release();
814
815    Py_RETURN_NONE;
816}
817
818SWIGEXPORT PyObject*
819LLDBSwigPython_GetRecognizedArguments
820(
821    PyObject *implementor,
822    const lldb::StackFrameSP& frame_sp
823)
824{
825    static char callee_name[] = "get_recognized_arguments";
826
827    lldb::SBFrame frame_sb(frame_sp);
828    PyObject *arg = SBTypeToSWIGWrapper(frame_sb);
829
830    PythonString str(callee_name);
831    PyObject* result = PyObject_CallMethodObjArgs(implementor, str.get(), arg,
832                                                  NULL);
833    return result;
834}
835
836SWIGEXPORT void*
837LLDBSWIGPython_GetDynamicSetting (void* module, const char* setting, const lldb::TargetSP& target_sp)
838{
839    if (!module || !setting)
840        Py_RETURN_NONE;
841
842    PyErr_Cleaner py_err_cleaner(true);
843    PythonObject py_module(PyRefType::Borrowed, (PyObject *)module);
844    auto pfunc = py_module.ResolveName<PythonCallable>("get_dynamic_setting");
845
846    if (!pfunc.IsAllocated())
847        Py_RETURN_NONE;
848
849    lldb::SBTarget target_sb(target_sp);
850    PythonObject target_arg(PyRefType::Owned, SBTypeToSWIGWrapper(target_sb));
851    auto result = pfunc(target_arg, PythonString(setting));
852
853    return result.release();
854}
855
856SWIGEXPORT bool
857LLDBSWIGPythonRunScriptKeywordProcess
858(const char* python_function_name,
859const char* session_dictionary_name,
860lldb::ProcessSP& process,
861std::string& output)
862
863{
864    if (python_function_name == NULL || python_function_name[0] == '\0' || !session_dictionary_name)
865        return false;
866
867    PyErr_Cleaner py_err_cleaner(true);
868
869    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
870    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name, dict);
871
872    if (!pfunc.IsAllocated())
873        return false;
874
875    lldb::SBProcess process_sb(process);
876    PythonObject process_arg(PyRefType::Owned, SBTypeToSWIGWrapper(process_sb));
877    auto result = pfunc(process_arg, dict);
878
879    output = result.Str().GetString().str();
880
881    return true;
882}
883
884SWIGEXPORT bool
885LLDBSWIGPythonRunScriptKeywordThread
886(const char* python_function_name,
887const char* session_dictionary_name,
888lldb::ThreadSP& thread,
889std::string& output)
890
891{
892    if (python_function_name == NULL || python_function_name[0] == '\0' || !session_dictionary_name)
893        return false;
894
895    PyErr_Cleaner py_err_cleaner(true);
896
897    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
898    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name, dict);
899
900    if (!pfunc.IsAllocated())
901        return false;
902
903    lldb::SBThread thread_sb(thread);
904    PythonObject thread_arg(PyRefType::Owned, SBTypeToSWIGWrapper(thread_sb));
905    auto result = pfunc(thread_arg, dict);
906
907    output = result.Str().GetString().str();
908
909    return true;
910}
911
912SWIGEXPORT bool
913LLDBSWIGPythonRunScriptKeywordTarget
914(const char* python_function_name,
915const char* session_dictionary_name,
916lldb::TargetSP& target,
917std::string& output)
918
919{
920    if (python_function_name == NULL || python_function_name[0] == '\0' || !session_dictionary_name)
921        return false;
922
923    PyErr_Cleaner py_err_cleaner(true);
924
925    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
926    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name,dict);
927
928    if (!pfunc.IsAllocated())
929        return false;
930
931    lldb::SBTarget target_sb(target);
932    PythonObject target_arg(PyRefType::Owned, SBTypeToSWIGWrapper(target_sb));
933    auto result = pfunc(target_arg, dict);
934
935    output = result.Str().GetString().str();
936
937    return true;
938}
939
940SWIGEXPORT bool
941LLDBSWIGPythonRunScriptKeywordFrame
942(const char* python_function_name,
943const char* session_dictionary_name,
944lldb::StackFrameSP& frame,
945std::string& output)
946
947{
948    if (python_function_name == NULL || python_function_name[0] == '\0' || !session_dictionary_name)
949        return false;
950
951    PyErr_Cleaner py_err_cleaner(true);
952
953    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
954    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name,dict);
955
956    if (!pfunc.IsAllocated())
957        return false;
958
959    lldb::SBFrame frame_sb(frame);
960    PythonObject frame_arg(PyRefType::Owned, SBTypeToSWIGWrapper(frame_sb));
961    auto result = pfunc(frame_arg, dict);
962
963    output = result.Str().GetString().str();
964
965    return true;
966}
967
968SWIGEXPORT bool
969LLDBSWIGPythonRunScriptKeywordValue
970(const char* python_function_name,
971const char* session_dictionary_name,
972lldb::ValueObjectSP& value,
973std::string& output)
974
975{
976    if (python_function_name == NULL || python_function_name[0] == '\0' || !session_dictionary_name)
977        return false;
978
979    PyErr_Cleaner py_err_cleaner(true);
980
981    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
982    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name, dict);
983
984    if (!pfunc.IsAllocated())
985        return false;
986
987    lldb::SBValue value_sb(value);
988    PythonObject value_arg(PyRefType::Owned, SBTypeToSWIGWrapper(value_sb));
989    auto result = pfunc(value_arg, dict);
990
991    output = result.Str().GetString().str();
992
993    return true;
994}
995
996SWIGEXPORT bool
997LLDBSwigPythonCallModuleInit
998(
999    const char *python_module_name,
1000    const char *session_dictionary_name,
1001    lldb::DebuggerSP& debugger
1002)
1003{
1004    std::string python_function_name_string = python_module_name;
1005    python_function_name_string += ".__lldb_init_module";
1006    const char* python_function_name = python_function_name_string.c_str();
1007
1008    PyErr_Cleaner py_err_cleaner(true);
1009
1010    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
1011    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_function_name, dict);
1012
1013    // This method is optional and need not exist.  So if we don't find it,
1014    // it's actually a success, not a failure.
1015    if (!pfunc.IsAllocated())
1016        return true;
1017
1018    lldb::SBDebugger debugger_sb(debugger);
1019    PythonObject debugger_arg(PyRefType::Owned, SBTypeToSWIGWrapper(debugger_sb));
1020    pfunc(debugger_arg, dict);
1021
1022    return true;
1023}
1024%}
1025
1026
1027%runtime %{
1028// Forward declaration to be inserted at the start of LLDBWrapPython.h
1029#include "lldb/API/SBDebugger.h"
1030#include "lldb/API/SBValue.h"
1031
1032SWIGEXPORT lldb::ValueObjectSP
1033LLDBSWIGPython_GetValueObjectSPFromSBValue (void* data)
1034{
1035    lldb::ValueObjectSP valobj_sp;
1036    if (data)
1037    {
1038        lldb::SBValue* sb_ptr = (lldb::SBValue *)data;
1039        valobj_sp = sb_ptr->GetSP();
1040    }
1041    return valobj_sp;
1042}
1043
1044#ifdef __cplusplus
1045extern "C" {
1046#endif
1047
1048void LLDBSwigPythonCallPythonLogOutputCallback(const char *str, void *baton);
1049
1050#ifdef __cplusplus
1051}
1052#endif
1053%}
1054
1055%wrapper %{
1056
1057
1058// For the LogOutputCallback functions
1059void LLDBSwigPythonCallPythonLogOutputCallback(const char *str, void *baton) {
1060    if (baton != Py_None) {
1061      SWIG_PYTHON_THREAD_BEGIN_BLOCK;
1062      PyObject *result = PyObject_CallFunction(reinterpret_cast<PyObject*>(baton), const_cast<char*>("s"), str);
1063	  Py_XDECREF(result);
1064      SWIG_PYTHON_THREAD_END_BLOCK;
1065    }
1066}
1067%}
1068