1 //===-- SWIG Interface for SBDebugger ---------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 namespace lldb {
10 
11 %feature("docstring",
12 "SBDebugger is the primordial object that creates SBTargets and provides
13 access to them.  It also manages the overall debugging experiences.
14 
15 For example (from example/disasm.py),::
16 
17     import lldb
18     import os
19     import sys
20 
21     def disassemble_instructions (insts):
22         for i in insts:
23             print i
24 
25     ...
26 
27     # Create a new debugger instance
28     debugger = lldb.SBDebugger.Create()
29 
30     # When we step or continue, don't return from the function until the process
31     # stops. We do this by setting the async mode to false.
32     debugger.SetAsync (False)
33 
34     # Create a target from a file and arch
35     print('Creating a target for \'%s\'' % exe)
36 
37     target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
38 
39     if target:
40         # If the target is valid set a breakpoint at main
41         main_bp = target.BreakpointCreateByName (fname, target.GetExecutable().GetFilename());
42 
43         print main_bp
44 
45         # Launch the process. Since we specified synchronous mode, we won't return
46         # from this function until we hit the breakpoint at main
47         process = target.LaunchSimple (None, None, os.getcwd())
48 
49         # Make sure the launch went ok
50         if process:
51             # Print some simple process info
52             state = process.GetState ()
53             print process
54             if state == lldb.eStateStopped:
55                 # Get the first thread
56                 thread = process.GetThreadAtIndex (0)
57                 if thread:
58                     # Print some simple thread info
59                     print thread
60                     # Get the first frame
61                     frame = thread.GetFrameAtIndex (0)
62                     if frame:
63                         # Print some simple frame info
64                         print frame
65                         function = frame.GetFunction()
66                         # See if we have debug info (a function)
67                         if function:
68                             # We do have a function, print some info for the function
69                             print function
70                             # Now get all instructions for this function and print them
71                             insts = function.GetInstructions(target)
72                             disassemble_instructions (insts)
73                         else:
74                             # See if we have a symbol in the symbol table for where we stopped
75                             symbol = frame.GetSymbol();
76                             if symbol:
77                                 # We do have a symbol, print some info for the symbol
78                                 print symbol
79                                 # Now get all instructions for this symbol and print them
80                                 insts = symbol.GetInstructions(target)
81                                 disassemble_instructions (insts)
82 
83                         registerList = frame.GetRegisters()
84                         print('Frame registers (size of register set = %d):' % registerList.GetSize())
85                         for value in registerList:
86                             #print value
87                             print('%s (number of children = %d):' % (value.GetName(), value.GetNumChildren()))
88                             for child in value:
89                                 print('Name: ', child.GetName(), ' Value: ', child.GetValue())
90 
91                 print('Hit the breakpoint at main, enter to continue and wait for program to exit or \'Ctrl-D\'/\'quit\' to terminate the program')
92                 next = sys.stdin.readline()
93                 if not next or next.rstrip('\\n') == 'quit':
94                     print('Terminating the inferior process...')
95                     process.Kill()
96                 else:
97                     # Now continue to the program exit
98                     process.Continue()
99                     # When we return from the above function we will hopefully be at the
100                     # program exit. Print out some process info
101                     print process
102             elif state == lldb.eStateExited:
103                 print('Didn\'t hit the breakpoint at main, program has exited...')
104             else:
105                 print('Unexpected process state: %s, killing process...' % debugger.StateAsCString (state))
106                 process.Kill()
107 
108 Sometimes you need to create an empty target that will get filled in later.  The most common use for this
109 is to attach to a process by name or pid where you don't know the executable up front.  The most convenient way
110 to do this is: ::
111 
112     target = debugger.CreateTarget('')
113     error = lldb.SBError()
114     process = target.AttachToProcessWithName(debugger.GetListener(), 'PROCESS_NAME', False, error)
115 
116 or the equivalent arguments for :py:class:`SBTarget.AttachToProcessWithID` .") SBDebugger;
117 class SBDebugger
118 {
119 public:
120     enum
121     {
122         eBroadcastBitProgress = (1 << 0),
123         eBroadcastBitWarning = (1 << 1),
124         eBroadcastBitError = (1 << 2),
125     };
126 
127 
128     static const char *GetProgressFromEvent(const lldb::SBEvent &event,
129                                         uint64_t &OUTPUT,
130                                         uint64_t &OUTPUT,
131                                         uint64_t &OUTPUT,
132                                         bool &OUTPUT);
133 
134     static lldb::SBStructuredData GetDiagnosticFromEvent(const lldb::SBEvent &event);
135 
136     SBBroadcaster GetBroadcaster();
137 
138     static void
139     Initialize();
140 
141     static SBError
142     InitializeWithErrorHandling();
143 
144     static void PrintStackTraceOnError();
145 
146     static void
147     Terminate();
148 
149     static lldb::SBDebugger
150     Create();
151 
152     static lldb::SBDebugger
153     Create(bool source_init_files);
154 
155     static lldb::SBDebugger
156     Create(bool source_init_files, lldb::LogOutputCallback log_callback, void *baton);
157 
158     static void
159     Destroy (lldb::SBDebugger &debugger);
160 
161     static void
162     MemoryPressureDetected();
163 
164     SBDebugger();
165 
166     SBDebugger(const lldb::SBDebugger &rhs);
167 
168     ~SBDebugger();
169 
170     bool
171     IsValid() const;
172 
173     explicit operator bool() const;
174 
175     void
176     Clear ();
177 
178     void
179     SetAsync (bool b);
180 
181     bool
182     GetAsync ();
183 
184     void
185     SkipLLDBInitFiles (bool b);
186 
187 #ifdef SWIGPYTHON
188     %pythoncode %{
189         def SetOutputFileHandle(self, file, transfer_ownership):
190             "DEPRECATED, use SetOutputFile"
191             if file is None:
192                 import sys
193                 file = sys.stdout
194             self.SetOutputFile(SBFile.Create(file, borrow=True))
195 
196         def SetInputFileHandle(self, file, transfer_ownership):
197             "DEPRECATED, use SetInputFile"
198             if file is None:
199                 import sys
200                 file = sys.stdin
201             self.SetInputFile(SBFile.Create(file, borrow=True))
202 
203         def SetErrorFileHandle(self, file, transfer_ownership):
204             "DEPRECATED, use SetErrorFile"
205             if file is None:
206                 import sys
207                 file = sys.stderr
208             self.SetErrorFile(SBFile.Create(file, borrow=True))
209     %}
210 #endif
211 
212 
213     %extend {
214 
GetInputFileHandle()215         lldb::FileSP GetInputFileHandle() {
216             return self->GetInputFile().GetFile();
217         }
218 
GetOutputFileHandle()219         lldb::FileSP GetOutputFileHandle() {
220             return self->GetOutputFile().GetFile();
221         }
222 
GetErrorFileHandle()223         lldb::FileSP GetErrorFileHandle() {
224             return self->GetErrorFile().GetFile();
225         }
226     }
227 
228     SBError
229     SetInputString (const char* data);
230 
231     SBError
232     SetInputFile (SBFile file);
233 
234     SBError
235     SetOutputFile (SBFile file);
236 
237     SBError
238     SetErrorFile (SBFile file);
239 
240     SBError
241     SetInputFile (FileSP file);
242 
243     SBError
244     SetOutputFile (FileSP file);
245 
246     SBError
247     SetErrorFile (FileSP file);
248 
249     SBFile
250     GetInputFile ();
251 
252     SBFile
253     GetOutputFile ();
254 
255     SBFile
256     GetErrorFile ();
257 
258     lldb::SBCommandInterpreter
259     GetCommandInterpreter ();
260 
261     void
262     HandleCommand (const char *command);
263 
264     lldb::SBListener
265     GetListener ();
266 
267     void
268     HandleProcessEvent (const lldb::SBProcess &process,
269                         const lldb::SBEvent &event,
270                         SBFile out,
271                         SBFile err);
272 
273     void
274     HandleProcessEvent (const lldb::SBProcess &process,
275                         const lldb::SBEvent &event,
276                         FileSP BORROWED,
277                         FileSP BORROWED);
278 
279     lldb::SBTarget
280     CreateTarget (const char *filename,
281                   const char *target_triple,
282                   const char *platform_name,
283                   bool add_dependent_modules,
284                   lldb::SBError& sb_error);
285 
286     lldb::SBTarget
287     CreateTargetWithFileAndTargetTriple (const char *filename,
288                                          const char *target_triple);
289 
290     lldb::SBTarget
291     CreateTargetWithFileAndArch (const char *filename,
292                                  const char *archname);
293 
294     lldb::SBTarget
295     CreateTarget (const char *filename);
296 
297     %feature("docstring",
298     "The dummy target holds breakpoints and breakpoint names that will prime newly created targets."
299     ) GetDummyTarget;
300     lldb::SBTarget GetDummyTarget();
301 
302     %feature("docstring",
303     "Return true if target is deleted from the target list of the debugger."
304     ) DeleteTarget;
305     bool
306     DeleteTarget (lldb::SBTarget &target);
307 
308     lldb::SBTarget
309     GetTargetAtIndex (uint32_t idx);
310 
311     uint32_t
312     GetIndexOfTarget (lldb::SBTarget target);
313 
314     lldb::SBTarget
315     FindTargetWithProcessID (pid_t pid);
316 
317     lldb::SBTarget
318     FindTargetWithFileAndArch (const char *filename,
319                                const char *arch);
320 
321     uint32_t
322     GetNumTargets ();
323 
324     lldb::SBTarget
325     GetSelectedTarget ();
326 
327     void
328     SetSelectedTarget (lldb::SBTarget &target);
329 
330     lldb::SBPlatform
331     GetSelectedPlatform();
332 
333     void
334     SetSelectedPlatform(lldb::SBPlatform &platform);
335 
336     %feature("docstring",
337     "Get the number of currently active platforms."
338     ) GetNumPlatforms;
339     uint32_t
340     GetNumPlatforms ();
341 
342     %feature("docstring",
343     "Get one of the currently active platforms."
344     ) GetPlatformAtIndex;
345     lldb::SBPlatform
346     GetPlatformAtIndex (uint32_t idx);
347 
348     %feature("docstring",
349     "Get the number of available platforms."
350     ) GetNumAvailablePlatforms;
351     uint32_t
352     GetNumAvailablePlatforms ();
353 
354     %feature("docstring", "
355     Get the name and description of one of the available platforms.
356 
357     @param idx Zero-based index of the platform for which info should be
358                retrieved, must be less than the value returned by
359                GetNumAvailablePlatforms().") GetAvailablePlatformInfoAtIndex;
360     lldb::SBStructuredData
361     GetAvailablePlatformInfoAtIndex (uint32_t idx);
362 
363     lldb::SBSourceManager
364     GetSourceManager ();
365 
366     // REMOVE: just for a quick fix, need to expose platforms through
367     // SBPlatform from this class.
368     lldb::SBError
369     SetCurrentPlatform (const char *platform_name);
370 
371     bool
372     SetCurrentPlatformSDKRoot (const char *sysroot);
373 
374     // FIXME: Once we get the set show stuff in place, the driver won't need
375     // an interface to the Set/Get UseExternalEditor.
376     bool
377     SetUseExternalEditor (bool input);
378 
379     bool
380     GetUseExternalEditor ();
381 
382     bool
383     SetUseColor (bool use_color);
384 
385     bool
386     GetUseColor () const;
387 
388     static bool
389     GetDefaultArchitecture (char *arch_name, size_t arch_name_len);
390 
391     static bool
392     SetDefaultArchitecture (const char *arch_name);
393 
394     lldb::ScriptLanguage
395     GetScriptingLanguage (const char *script_language_name);
396 
397     static const char *
398     GetVersionString ();
399 
400     static const char *
401     StateAsCString (lldb::StateType state);
402 
403     static SBStructuredData GetBuildConfiguration();
404 
405     static bool
406     StateIsRunningState (lldb::StateType state);
407 
408     static bool
409     StateIsStoppedState (lldb::StateType state);
410 
411     bool
412     EnableLog (const char *channel, const char ** types);
413 
414     void
415     SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton);
416 
417     void
418     DispatchInput (const void *data, size_t data_len);
419 
420     void
421     DispatchInputInterrupt ();
422 
423     void
424     DispatchInputEndOfFile ();
425 
426     const char *
427     GetInstanceName  ();
428 
429     static SBDebugger
430     FindDebuggerWithID (int id);
431 
432     static lldb::SBError
433     SetInternalVariable (const char *var_name, const char *value, const char *debugger_instance_name);
434 
435     static lldb::SBStringList
436     GetInternalVariableValue (const char *var_name, const char *debugger_instance_name);
437 
438     bool
439     GetDescription (lldb::SBStream &description);
440 
441     uint32_t
442     GetTerminalWidth () const;
443 
444     void
445     SetTerminalWidth (uint32_t term_width);
446 
447     lldb::user_id_t
448     GetID ();
449 
450     const char *
451     GetPrompt() const;
452 
453     void
454     SetPrompt (const char *prompt);
455 
456     const char *
457     GetReproducerPath() const;
458 
459     lldb::ScriptLanguage
460     GetScriptLanguage() const;
461 
462     void
463     SetScriptLanguage (lldb::ScriptLanguage script_lang);
464 
465     bool
466     GetCloseInputOnEOF () const;
467 
468     void
469     SetCloseInputOnEOF (bool b);
470 
471     lldb::SBTypeCategory
472     GetCategory (const char* category_name);
473 
474     SBTypeCategory
475     GetCategory (lldb::LanguageType lang_type);
476 
477     lldb::SBTypeCategory
478     CreateCategory (const char* category_name);
479 
480     bool
481     DeleteCategory (const char* category_name);
482 
483     uint32_t
484     GetNumCategories ();
485 
486     lldb::SBTypeCategory
487     GetCategoryAtIndex (uint32_t);
488 
489     lldb::SBTypeCategory
490     GetDefaultCategory();
491 
492     lldb::SBTypeFormat
493     GetFormatForType (lldb::SBTypeNameSpecifier);
494 
495     lldb::SBTypeSummary
496     GetSummaryForType (lldb::SBTypeNameSpecifier);
497 
498     lldb::SBTypeFilter
499     GetFilterForType (lldb::SBTypeNameSpecifier);
500 
501     lldb::SBTypeSynthetic
502     GetSyntheticForType (lldb::SBTypeNameSpecifier);
503 
504     SBStructuredData GetScriptInterpreterInfo(ScriptLanguage);
505 
506     STRING_EXTENSION(SBDebugger)
507 
508     %feature("docstring",
509 "Launch a command interpreter session. Commands are read from standard input or
510 from the input handle specified for the debugger object. Output/errors are
511 similarly redirected to standard output/error or the configured handles.
512 
513 @param[in] auto_handle_events If true, automatically handle resulting events.
514 @param[in] spawn_thread If true, start a new thread for IO handling.
515 @param[in] options Parameter collection of type SBCommandInterpreterRunOptions.
516 @param[in] num_errors Initial error counter.
517 @param[in] quit_requested Initial quit request flag.
518 @param[in] stopped_for_crash Initial crash flag.
519 
520 @return
521 A tuple with the number of errors encountered by the interpreter, a boolean
522 indicating whether quitting the interpreter was requested and another boolean
523 set to True in case of a crash.
524 
525 Example: ::
526 
527     # Start an interactive lldb session from a script (with a valid debugger object
528     # created beforehand):
529     n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True,
530         False, lldb.SBCommandInterpreterRunOptions(), 0, False, False)") RunCommandInterpreter;
531     %apply int& INOUT { int& num_errors };
532     %apply bool& INOUT { bool& quit_requested };
533     %apply bool& INOUT { bool& stopped_for_crash };
534     void
535     RunCommandInterpreter (bool auto_handle_events,
536                            bool spawn_thread,
537                            SBCommandInterpreterRunOptions &options,
538                            int  &num_errors,
539                            bool &quit_requested,
540                            bool &stopped_for_crash);
541 
542     lldb::SBError
543     RunREPL (lldb::LanguageType language, const char *repl_options);
544 
545     SBTrace LoadTraceFromFile(SBError &error, const SBFileSpec &trace_description_file);
546 
547 #ifdef SWIGPYTHON
548     %pythoncode%{
549     def __iter__(self):
550         '''Iterate over all targets in a lldb.SBDebugger object.'''
551         return lldb_iter(self, 'GetNumTargets', 'GetTargetAtIndex')
552 
553     def __len__(self):
554         '''Return the number of targets in a lldb.SBDebugger object.'''
555         return self.GetNumTargets()
556     %}
557 #endif
558 
559 }; // class SBDebugger
560 
561 } // namespace lldb
562