198576Sobrien//===-- SBCommandInterpreter.cpp --------------------------------*- C++ -*-===//
298576Sobrien//
3113959Smtm//                     The LLVM Compiler Infrastructure
498576Sobrien//
598576Sobrien// This file is distributed under the University of Illinois Open Source
698576Sobrien// License. See LICENSE.TXT for details.
7113959Smtm//
8136224Smtm//===----------------------------------------------------------------------===//
998576Sobrien
1098576Sobrien#include "lldb/lldb-python.h"
1198576Sobrien
1298576Sobrien#include "lldb/lldb-types.h"
13230099Sdougb#include "lldb/Core/SourceManager.h"
1498576Sobrien#include "lldb/Core/Listener.h"
1598576Sobrien#include "lldb/Interpreter/CommandInterpreter.h"
16124618Smtm#include "lldb/Interpreter/CommandObjectMultiword.h"
1798576Sobrien#include "lldb/Interpreter/CommandReturnObject.h"
18113959Smtm#include "lldb/Target/Target.h"
19113959Smtm
20113959Smtm#include "lldb/API/SBBroadcaster.h"
21113959Smtm#include "lldb/API/SBCommandReturnObject.h"
22113959Smtm#include "lldb/API/SBCommandInterpreter.h"
23113959Smtm#include "lldb/API/SBProcess.h"
24113959Smtm#include "lldb/API/SBTarget.h"
25113959Smtm#include "lldb/API/SBListener.h"
26255450Scy#include "lldb/API/SBStream.h"
27113959Smtm#include "lldb/API/SBStringList.h"
28113959Smtm
29113959Smtmusing namespace lldb;
30113959Smtmusing namespace lldb_private;
31113959Smtm
3298576Sobrienclass CommandPluginInterfaceImplementation : public CommandObjectParsed
3398576Sobrien{
3498576Sobrienpublic:
35113959Smtm    CommandPluginInterfaceImplementation (CommandInterpreter &interpreter,
3698576Sobrien                                          const char *name,
3798576Sobrien                                          lldb::SBCommandPluginInterface* backend,
3898576Sobrien                                          const char *help = NULL,
3998576Sobrien                                          const char *syntax = NULL,
4098576Sobrien                                          uint32_t flags = 0) :
4198576Sobrien    CommandObjectParsed (interpreter, name, help, syntax, flags),
4298576Sobrien    m_backend(backend) {}
4398576Sobrien
4498576Sobrien    virtual bool
4598576Sobrien    IsRemovable() const { return true; }
4698576Sobrien
47113959Smtmprotected:
4898576Sobrien    virtual bool
4998576Sobrien    DoExecute (Args& command, CommandReturnObject &result)
5098576Sobrien    {
5198576Sobrien        SBCommandReturnObject sb_return(&result);
52        SBCommandInterpreter sb_interpreter(&m_interpreter);
53        SBDebugger debugger_sb(m_interpreter.GetDebugger().shared_from_this());
54        bool ret = m_backend->DoExecute (debugger_sb,(char**)command.GetArgumentVector(), sb_return);
55        sb_return.Release();
56        return ret;
57    }
58    lldb::SBCommandPluginInterface* m_backend;
59};
60
61SBCommandInterpreter::SBCommandInterpreter (CommandInterpreter *interpreter) :
62    m_opaque_ptr (interpreter)
63{
64    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
65
66    if (log)
67        log->Printf ("SBCommandInterpreter::SBCommandInterpreter (interpreter=%p)"
68                     " => SBCommandInterpreter(%p)", interpreter, m_opaque_ptr);
69}
70
71SBCommandInterpreter::SBCommandInterpreter(const SBCommandInterpreter &rhs) :
72    m_opaque_ptr (rhs.m_opaque_ptr)
73{
74}
75
76const SBCommandInterpreter &
77SBCommandInterpreter::operator = (const SBCommandInterpreter &rhs)
78{
79    m_opaque_ptr = rhs.m_opaque_ptr;
80    return *this;
81}
82
83SBCommandInterpreter::~SBCommandInterpreter ()
84{
85}
86
87bool
88SBCommandInterpreter::IsValid() const
89{
90    return m_opaque_ptr != NULL;
91}
92
93
94bool
95SBCommandInterpreter::CommandExists (const char *cmd)
96{
97    if (cmd && m_opaque_ptr)
98        return m_opaque_ptr->CommandExists (cmd);
99    return false;
100}
101
102bool
103SBCommandInterpreter::AliasExists (const char *cmd)
104{
105    if (cmd && m_opaque_ptr)
106        return m_opaque_ptr->AliasExists (cmd);
107    return false;
108}
109
110bool
111SBCommandInterpreter::IsActive ()
112{
113    if (m_opaque_ptr)
114        return m_opaque_ptr->IsActive ();
115    return false;
116}
117
118const char *
119SBCommandInterpreter::GetIOHandlerControlSequence(char ch)
120{
121    if (m_opaque_ptr)
122        return m_opaque_ptr->GetDebugger().GetTopIOHandlerControlSequence (ch).GetCString();
123    return NULL;
124}
125
126lldb::ReturnStatus
127SBCommandInterpreter::HandleCommand (const char *command_line, SBCommandReturnObject &result, bool add_to_history)
128{
129    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
130
131    if (log)
132        log->Printf ("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", SBCommandReturnObject(%p), add_to_history=%i)",
133                     m_opaque_ptr, command_line, result.get(), add_to_history);
134
135    result.Clear();
136    if (command_line && m_opaque_ptr)
137    {
138        m_opaque_ptr->HandleCommand (command_line, add_to_history ? eLazyBoolYes : eLazyBoolNo, result.ref());
139    }
140    else
141    {
142        result->AppendError ("SBCommandInterpreter or the command line is not valid");
143        result->SetStatus (eReturnStatusFailed);
144    }
145
146    // We need to get the value again, in case the command disabled the log!
147    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API);
148    if (log)
149    {
150        SBStream sstr;
151        result.GetDescription (sstr);
152        log->Printf ("SBCommandInterpreter(%p)::HandleCommand (command=\"%s\", SBCommandReturnObject(%p): %s, add_to_history=%i) => %i",
153                     m_opaque_ptr, command_line, result.get(), sstr.GetData(), add_to_history, result.GetStatus());
154    }
155
156    return result.GetStatus();
157}
158
159int
160SBCommandInterpreter::HandleCompletion (const char *current_line,
161                                        const char *cursor,
162                                        const char *last_char,
163                                        int match_start_point,
164                                        int max_return_elements,
165                                        SBStringList &matches)
166{
167    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
168    int num_completions = 0;
169
170    // Sanity check the arguments that are passed in:
171    // cursor & last_char have to be within the current_line.
172    if (current_line == NULL || cursor == NULL || last_char == NULL)
173        return 0;
174
175    if (cursor < current_line || last_char < current_line)
176        return 0;
177
178    size_t current_line_size = strlen (current_line);
179    if (cursor - current_line > current_line_size || last_char - current_line > current_line_size)
180        return 0;
181
182    if (log)
183        log->Printf ("SBCommandInterpreter(%p)::HandleCompletion (current_line=\"%s\", cursor at: %" PRId64 ", last char at: %" PRId64 ", match_start_point: %d, max_return_elements: %d)",
184                     m_opaque_ptr, current_line, (uint64_t) (cursor - current_line), (uint64_t) (last_char - current_line), match_start_point, max_return_elements);
185
186    if (m_opaque_ptr)
187    {
188        lldb_private::StringList lldb_matches;
189        num_completions =  m_opaque_ptr->HandleCompletion (current_line, cursor, last_char, match_start_point,
190                                                           max_return_elements, lldb_matches);
191
192        SBStringList temp_list (&lldb_matches);
193        matches.AppendList (temp_list);
194    }
195    if (log)
196        log->Printf ("SBCommandInterpreter(%p)::HandleCompletion - Found %d completions.", m_opaque_ptr, num_completions);
197
198    return num_completions;
199}
200
201int
202SBCommandInterpreter::HandleCompletion (const char *current_line,
203                  uint32_t cursor_pos,
204                  int match_start_point,
205                  int max_return_elements,
206                  lldb::SBStringList &matches)
207{
208    const char *cursor = current_line + cursor_pos;
209    const char *last_char = current_line + strlen (current_line);
210    return HandleCompletion (current_line, cursor, last_char, match_start_point, max_return_elements, matches);
211}
212
213bool
214SBCommandInterpreter::HasCommands ()
215{
216    if (m_opaque_ptr)
217        return m_opaque_ptr->HasCommands();
218    return false;
219}
220
221bool
222SBCommandInterpreter::HasAliases ()
223{
224    if (m_opaque_ptr)
225        return m_opaque_ptr->HasAliases();
226    return false;
227}
228
229bool
230SBCommandInterpreter::HasAliasOptions ()
231{
232    if (m_opaque_ptr)
233        return m_opaque_ptr->HasAliasOptions ();
234    return false;
235}
236
237SBProcess
238SBCommandInterpreter::GetProcess ()
239{
240    SBProcess sb_process;
241    ProcessSP process_sp;
242    if (m_opaque_ptr)
243    {
244        TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget());
245        if (target_sp)
246        {
247            Mutex::Locker api_locker(target_sp->GetAPIMutex());
248            process_sp = target_sp->GetProcessSP();
249            sb_process.SetSP(process_sp);
250        }
251    }
252    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
253
254    if (log)
255        log->Printf ("SBCommandInterpreter(%p)::GetProcess () => SBProcess(%p)",
256                     m_opaque_ptr, process_sp.get());
257
258
259    return sb_process;
260}
261
262SBDebugger
263SBCommandInterpreter::GetDebugger ()
264{
265    SBDebugger sb_debugger;
266    if (m_opaque_ptr)
267        sb_debugger.reset(m_opaque_ptr->GetDebugger().shared_from_this());
268    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
269
270    if (log)
271        log->Printf ("SBCommandInterpreter(%p)::GetDebugger () => SBDebugger(%p)",
272                     m_opaque_ptr, sb_debugger.get());
273
274
275    return sb_debugger;
276}
277
278CommandInterpreter *
279SBCommandInterpreter::get ()
280{
281    return m_opaque_ptr;
282}
283
284CommandInterpreter &
285SBCommandInterpreter::ref ()
286{
287    assert (m_opaque_ptr);
288    return *m_opaque_ptr;
289}
290
291void
292SBCommandInterpreter::reset (lldb_private::CommandInterpreter *interpreter)
293{
294    m_opaque_ptr = interpreter;
295}
296
297void
298SBCommandInterpreter::SourceInitFileInHomeDirectory (SBCommandReturnObject &result)
299{
300    result.Clear();
301    if (m_opaque_ptr)
302    {
303        TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget());
304        Mutex::Locker api_locker;
305        if (target_sp)
306            api_locker.Lock(target_sp->GetAPIMutex());
307        m_opaque_ptr->SourceInitFile (false, result.ref());
308    }
309    else
310    {
311        result->AppendError ("SBCommandInterpreter is not valid");
312        result->SetStatus (eReturnStatusFailed);
313    }
314    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
315
316    if (log)
317        log->Printf ("SBCommandInterpreter(%p)::SourceInitFileInHomeDirectory (&SBCommandReturnObject(%p))",
318                     m_opaque_ptr, result.get());
319
320}
321
322void
323SBCommandInterpreter::SourceInitFileInCurrentWorkingDirectory (SBCommandReturnObject &result)
324{
325    result.Clear();
326    if (m_opaque_ptr)
327    {
328        TargetSP target_sp(m_opaque_ptr->GetDebugger().GetSelectedTarget());
329        Mutex::Locker api_locker;
330        if (target_sp)
331            api_locker.Lock(target_sp->GetAPIMutex());
332        m_opaque_ptr->SourceInitFile (true, result.ref());
333    }
334    else
335    {
336        result->AppendError ("SBCommandInterpreter is not valid");
337        result->SetStatus (eReturnStatusFailed);
338    }
339    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
340
341    if (log)
342        log->Printf ("SBCommandInterpreter(%p)::SourceInitFileInCurrentWorkingDirectory (&SBCommandReturnObject(%p))",
343                     m_opaque_ptr, result.get());
344}
345
346SBBroadcaster
347SBCommandInterpreter::GetBroadcaster ()
348{
349    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
350
351    SBBroadcaster broadcaster (m_opaque_ptr, false);
352
353    if (log)
354        log->Printf ("SBCommandInterpreter(%p)::GetBroadcaster() => SBBroadcaster(%p)",
355                     m_opaque_ptr, broadcaster.get());
356
357    return broadcaster;
358}
359
360const char *
361SBCommandInterpreter::GetBroadcasterClass ()
362{
363    return Communication::GetStaticBroadcasterClass().AsCString();
364}
365
366const char *
367SBCommandInterpreter::GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type)
368{
369    return CommandObject::GetArgumentTypeAsCString (arg_type);
370}
371
372const char *
373SBCommandInterpreter::GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type)
374{
375    return CommandObject::GetArgumentDescriptionAsCString (arg_type);
376}
377
378bool
379SBCommandInterpreter::SetCommandOverrideCallback (const char *command_name,
380                                                  lldb::CommandOverrideCallback callback,
381                                                  void *baton)
382{
383    if (command_name && command_name[0] && m_opaque_ptr)
384    {
385        std::string command_name_str (command_name);
386        CommandObject *cmd_obj = m_opaque_ptr->GetCommandObjectForCommand(command_name_str);
387        if (cmd_obj)
388        {
389            assert(command_name_str.empty());
390            cmd_obj->SetOverrideCallback (callback, baton);
391            return true;
392        }
393    }
394    return false;
395}
396
397#ifndef LLDB_DISABLE_PYTHON
398
399// Defined in the SWIG source file
400extern "C" void
401init_lldb(void);
402
403// these are the Pythonic implementations of the required callbacks
404// these are scripting-language specific, which is why they belong here
405// we still need to use function pointers to them instead of relying
406// on linkage-time resolution because the SWIG stuff and this file
407// get built at different times
408extern "C" bool
409LLDBSwigPythonBreakpointCallbackFunction (const char *python_function_name,
410                                          const char *session_dictionary_name,
411                                          const lldb::StackFrameSP& sb_frame,
412                                          const lldb::BreakpointLocationSP& sb_bp_loc);
413
414extern "C" bool
415LLDBSwigPythonWatchpointCallbackFunction (const char *python_function_name,
416                                          const char *session_dictionary_name,
417                                          const lldb::StackFrameSP& sb_frame,
418                                          const lldb::WatchpointSP& sb_wp);
419
420extern "C" bool
421LLDBSwigPythonCallTypeScript (const char *python_function_name,
422                              void *session_dictionary,
423                              const lldb::ValueObjectSP& valobj_sp,
424                              void** pyfunct_wrapper,
425                              std::string& retval);
426
427extern "C" void*
428LLDBSwigPythonCreateSyntheticProvider (const char *python_class_name,
429                                       const char *session_dictionary_name,
430                                       const lldb::ValueObjectSP& valobj_sp);
431
432
433extern "C" uint32_t
434LLDBSwigPython_CalculateNumChildren (void *implementor);
435
436extern "C" void *
437LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
438
439extern "C" int
440LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
441
442extern "C" void *
443LLDBSWIGPython_CastPyObjectToSBValue (void* data);
444
445extern lldb::ValueObjectSP
446LLDBSWIGPython_GetValueObjectSPFromSBValue (void* data);
447
448extern "C" bool
449LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
450
451extern "C" bool
452LLDBSwigPython_MightHaveChildrenSynthProviderInstance (void* implementor);
453
454extern "C" bool
455LLDBSwigPythonCallCommand (const char *python_function_name,
456                           const char *session_dictionary_name,
457                           lldb::DebuggerSP& debugger,
458                           const char* args,
459                           lldb_private::CommandReturnObject &cmd_retobj);
460
461extern "C" bool
462LLDBSwigPythonCallModuleInit (const char *python_module_name,
463                              const char *session_dictionary_name,
464                              lldb::DebuggerSP& debugger);
465
466extern "C" void*
467LLDBSWIGPythonCreateOSPlugin (const char *python_class_name,
468                              const char *session_dictionary_name,
469                              const lldb::ProcessSP& process_sp);
470
471extern "C" bool
472LLDBSWIGPythonRunScriptKeywordProcess (const char* python_function_name,
473                                       const char* session_dictionary_name,
474                                       lldb::ProcessSP& process,
475                                       std::string& output);
476
477extern "C" bool
478LLDBSWIGPythonRunScriptKeywordThread (const char* python_function_name,
479                                      const char* session_dictionary_name,
480                                      lldb::ThreadSP& thread,
481                                      std::string& output);
482
483extern "C" bool
484LLDBSWIGPythonRunScriptKeywordTarget (const char* python_function_name,
485                                      const char* session_dictionary_name,
486                                      lldb::TargetSP& target,
487                                      std::string& output);
488
489extern "C" bool
490LLDBSWIGPythonRunScriptKeywordFrame (const char* python_function_name,
491                                     const char* session_dictionary_name,
492                                     lldb::StackFrameSP& frame,
493                                     std::string& output);
494
495extern "C" void*
496LLDBSWIGPython_GetDynamicSetting (void* module,
497                                  const char* setting,
498                                  const lldb::TargetSP& target_sp);
499
500
501#endif
502
503void
504SBCommandInterpreter::InitializeSWIG ()
505{
506    static bool g_initialized = false;
507    if (!g_initialized)
508    {
509        g_initialized = true;
510#ifndef LLDB_DISABLE_PYTHON
511        ScriptInterpreter::InitializeInterpreter (init_lldb,
512                                                  LLDBSwigPythonBreakpointCallbackFunction,
513                                                  LLDBSwigPythonWatchpointCallbackFunction,
514                                                  LLDBSwigPythonCallTypeScript,
515                                                  LLDBSwigPythonCreateSyntheticProvider,
516                                                  LLDBSwigPython_CalculateNumChildren,
517                                                  LLDBSwigPython_GetChildAtIndex,
518                                                  LLDBSwigPython_GetIndexOfChildWithName,
519                                                  LLDBSWIGPython_CastPyObjectToSBValue,
520                                                  LLDBSWIGPython_GetValueObjectSPFromSBValue,
521                                                  LLDBSwigPython_UpdateSynthProviderInstance,
522                                                  LLDBSwigPython_MightHaveChildrenSynthProviderInstance,
523                                                  LLDBSwigPythonCallCommand,
524                                                  LLDBSwigPythonCallModuleInit,
525                                                  LLDBSWIGPythonCreateOSPlugin,
526                                                  LLDBSWIGPythonRunScriptKeywordProcess,
527                                                  LLDBSWIGPythonRunScriptKeywordThread,
528                                                  LLDBSWIGPythonRunScriptKeywordTarget,
529                                                  LLDBSWIGPythonRunScriptKeywordFrame,
530                                                  LLDBSWIGPython_GetDynamicSetting);
531#endif
532    }
533}
534
535lldb::SBCommand
536SBCommandInterpreter::AddMultiwordCommand (const char* name, const char* help)
537{
538    CommandObjectMultiword *new_command = new CommandObjectMultiword(*m_opaque_ptr,name,help);
539    new_command->SetRemovable (true);
540    lldb::CommandObjectSP new_command_sp(new_command);
541    if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true))
542        return lldb::SBCommand(new_command_sp);
543    return lldb::SBCommand();
544}
545
546lldb::SBCommand
547SBCommandInterpreter::AddCommand (const char* name, lldb::SBCommandPluginInterface* impl, const char* help)
548{
549    lldb::CommandObjectSP new_command_sp;
550    new_command_sp.reset(new CommandPluginInterfaceImplementation(*m_opaque_ptr,name,impl,help));
551
552    if (new_command_sp && m_opaque_ptr->AddUserCommand(name, new_command_sp, true))
553        return lldb::SBCommand(new_command_sp);
554    return lldb::SBCommand();
555}
556
557SBCommand::SBCommand ()
558{}
559
560SBCommand::SBCommand (lldb::CommandObjectSP cmd_sp) : m_opaque_sp (cmd_sp)
561{}
562
563bool
564SBCommand::IsValid ()
565{
566    return (bool)m_opaque_sp;
567}
568
569const char*
570SBCommand::GetName ()
571{
572    if (IsValid ())
573        return m_opaque_sp->GetCommandName ();
574    return NULL;
575}
576
577const char*
578SBCommand::GetHelp ()
579{
580    if (IsValid ())
581        return m_opaque_sp->GetHelp ();
582    return NULL;
583}
584
585lldb::SBCommand
586SBCommand::AddMultiwordCommand (const char* name, const char* help)
587{
588    if (!IsValid ())
589        return lldb::SBCommand();
590    if (m_opaque_sp->IsMultiwordObject() == false)
591        return lldb::SBCommand();
592    CommandObjectMultiword *new_command = new CommandObjectMultiword(m_opaque_sp->GetCommandInterpreter(),name,help);
593    new_command->SetRemovable (true);
594    lldb::CommandObjectSP new_command_sp(new_command);
595    if (new_command_sp && m_opaque_sp->LoadSubCommand(name,new_command_sp))
596        return lldb::SBCommand(new_command_sp);
597    return lldb::SBCommand();
598}
599
600lldb::SBCommand
601SBCommand::AddCommand (const char* name, lldb::SBCommandPluginInterface *impl, const char* help)
602{
603    if (!IsValid ())
604        return lldb::SBCommand();
605    if (m_opaque_sp->IsMultiwordObject() == false)
606        return lldb::SBCommand();
607    lldb::CommandObjectSP new_command_sp;
608    new_command_sp.reset(new CommandPluginInterfaceImplementation(m_opaque_sp->GetCommandInterpreter(),name,impl,help));
609    if (new_command_sp && m_opaque_sp->LoadSubCommand(name,new_command_sp))
610        return lldb::SBCommand(new_command_sp);
611    return lldb::SBCommand();
612}
613
614