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 
215         lldb::FileSP GetInputFileHandle() {
216             return self->GetInputFile().GetFile();
217         }
218 
219         lldb::FileSP GetOutputFileHandle() {
220             return self->GetOutputFile().GetFile();
221         }
222 
223         lldb::FileSP GetErrorFileHandle() {
224             return self->GetErrorFile().GetFile();
225         }
226     }
227 
228     lldb::SBStructuredData GetSetting(const char *setting = nullptr);
229 
230     SBError
231     SetInputString (const char* data);
232 
233     SBError
234     SetInputFile (SBFile file);
235 
236     SBError
237     SetOutputFile (SBFile file);
238 
239     SBError
240     SetErrorFile (SBFile file);
241 
242     SBError
243     SetInputFile (FileSP file);
244 
245     SBError
246     SetOutputFile (FileSP file);
247 
248     SBError
249     SetErrorFile (FileSP file);
250 
251     SBFile
252     GetInputFile ();
253 
254     SBFile
255     GetOutputFile ();
256 
257     SBFile
258     GetErrorFile ();
259 
260     lldb::SBCommandInterpreter
261     GetCommandInterpreter ();
262 
263     void
264     HandleCommand (const char *command);
265 
266     lldb::SBListener
267     GetListener ();
268 
269     void
270     HandleProcessEvent (const lldb::SBProcess &process,
271                         const lldb::SBEvent &event,
272                         SBFile out,
273                         SBFile err);
274 
275     void
276     HandleProcessEvent (const lldb::SBProcess &process,
277                         const lldb::SBEvent &event,
278                         FileSP BORROWED,
279                         FileSP BORROWED);
280 
281     lldb::SBTarget
282     CreateTarget (const char *filename,
283                   const char *target_triple,
284                   const char *platform_name,
285                   bool add_dependent_modules,
286                   lldb::SBError& sb_error);
287 
288     lldb::SBTarget
289     CreateTargetWithFileAndTargetTriple (const char *filename,
290                                          const char *target_triple);
291 
292     lldb::SBTarget
293     CreateTargetWithFileAndArch (const char *filename,
294                                  const char *archname);
295 
296     lldb::SBTarget
297     CreateTarget (const char *filename);
298 
299     %feature("docstring",
300     "The dummy target holds breakpoints and breakpoint names that will prime newly created targets."
301     ) GetDummyTarget;
302     lldb::SBTarget GetDummyTarget();
303 
304     %feature("docstring",
305     "Return true if target is deleted from the target list of the debugger."
306     ) DeleteTarget;
307     bool
308     DeleteTarget (lldb::SBTarget &target);
309 
310     lldb::SBTarget
311     GetTargetAtIndex (uint32_t idx);
312 
313     uint32_t
314     GetIndexOfTarget (lldb::SBTarget target);
315 
316     lldb::SBTarget
317     FindTargetWithProcessID (pid_t pid);
318 
319     lldb::SBTarget
320     FindTargetWithFileAndArch (const char *filename,
321                                const char *arch);
322 
323     uint32_t
324     GetNumTargets ();
325 
326     lldb::SBTarget
327     GetSelectedTarget ();
328 
329     void
330     SetSelectedTarget (lldb::SBTarget &target);
331 
332     lldb::SBPlatform
333     GetSelectedPlatform();
334 
335     void
336     SetSelectedPlatform(lldb::SBPlatform &platform);
337 
338     %feature("docstring",
339     "Get the number of currently active platforms."
340     ) GetNumPlatforms;
341     uint32_t
342     GetNumPlatforms ();
343 
344     %feature("docstring",
345     "Get one of the currently active platforms."
346     ) GetPlatformAtIndex;
347     lldb::SBPlatform
348     GetPlatformAtIndex (uint32_t idx);
349 
350     %feature("docstring",
351     "Get the number of available platforms."
352     ) GetNumAvailablePlatforms;
353     uint32_t
354     GetNumAvailablePlatforms ();
355 
356     %feature("docstring", "
357     Get the name and description of one of the available platforms.
358 
359     @param idx Zero-based index of the platform for which info should be
360                retrieved, must be less than the value returned by
361                GetNumAvailablePlatforms().") GetAvailablePlatformInfoAtIndex;
362     lldb::SBStructuredData
363     GetAvailablePlatformInfoAtIndex (uint32_t idx);
364 
365     lldb::SBSourceManager
366     GetSourceManager ();
367 
368     // REMOVE: just for a quick fix, need to expose platforms through
369     // SBPlatform from this class.
370     lldb::SBError
371     SetCurrentPlatform (const char *platform_name);
372 
373     bool
374     SetCurrentPlatformSDKRoot (const char *sysroot);
375 
376     // FIXME: Once we get the set show stuff in place, the driver won't need
377     // an interface to the Set/Get UseExternalEditor.
378     bool
379     SetUseExternalEditor (bool input);
380 
381     bool
382     GetUseExternalEditor ();
383 
384     bool
385     SetUseColor (bool use_color);
386 
387     bool
388     GetUseColor () const;
389 
390     static bool
391     GetDefaultArchitecture (char *arch_name, size_t arch_name_len);
392 
393     static bool
394     SetDefaultArchitecture (const char *arch_name);
395 
396     lldb::ScriptLanguage
397     GetScriptingLanguage (const char *script_language_name);
398 
399     static const char *
400     GetVersionString ();
401 
402     static const char *
403     StateAsCString (lldb::StateType state);
404 
405     static SBStructuredData GetBuildConfiguration();
406 
407     static bool
408     StateIsRunningState (lldb::StateType state);
409 
410     static bool
411     StateIsStoppedState (lldb::StateType state);
412 
413     bool
414     EnableLog (const char *channel, const char ** types);
415 
416     void
417     SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton);
418 
419     void
420     DispatchInput (const void *data, size_t data_len);
421 
422     void
423     DispatchInputInterrupt ();
424 
425     void
426     DispatchInputEndOfFile ();
427 
428     const char *
429     GetInstanceName  ();
430 
431     static SBDebugger
432     FindDebuggerWithID (int id);
433 
434     static lldb::SBError
435     SetInternalVariable (const char *var_name, const char *value, const char *debugger_instance_name);
436 
437     static lldb::SBStringList
438     GetInternalVariableValue (const char *var_name, const char *debugger_instance_name);
439 
440     bool
441     GetDescription (lldb::SBStream &description);
442 
443     uint32_t
444     GetTerminalWidth () const;
445 
446     void
447     SetTerminalWidth (uint32_t term_width);
448 
449     lldb::user_id_t
450     GetID ();
451 
452     const char *
453     GetPrompt() const;
454 
455     void
456     SetPrompt (const char *prompt);
457 
458     const char *
459     GetReproducerPath() const;
460 
461     lldb::ScriptLanguage
462     GetScriptLanguage() const;
463 
464     void
465     SetScriptLanguage (lldb::ScriptLanguage script_lang);
466 
467     bool
468     GetCloseInputOnEOF () const;
469 
470     void
471     SetCloseInputOnEOF (bool b);
472 
473     lldb::SBTypeCategory
474     GetCategory (const char* category_name);
475 
476     SBTypeCategory
477     GetCategory (lldb::LanguageType lang_type);
478 
479     lldb::SBTypeCategory
480     CreateCategory (const char* category_name);
481 
482     bool
483     DeleteCategory (const char* category_name);
484 
485     uint32_t
486     GetNumCategories ();
487 
488     lldb::SBTypeCategory
489     GetCategoryAtIndex (uint32_t);
490 
491     lldb::SBTypeCategory
492     GetDefaultCategory();
493 
494     lldb::SBTypeFormat
495     GetFormatForType (lldb::SBTypeNameSpecifier);
496 
497     lldb::SBTypeSummary
498     GetSummaryForType (lldb::SBTypeNameSpecifier);
499 
500     lldb::SBTypeFilter
501     GetFilterForType (lldb::SBTypeNameSpecifier);
502 
503     lldb::SBTypeSynthetic
504     GetSyntheticForType (lldb::SBTypeNameSpecifier);
505 
506     SBStructuredData GetScriptInterpreterInfo(ScriptLanguage);
507 
508     STRING_EXTENSION(SBDebugger)
509 
510     %feature("docstring",
511 "Launch a command interpreter session. Commands are read from standard input or
512 from the input handle specified for the debugger object. Output/errors are
513 similarly redirected to standard output/error or the configured handles.
514 
515 @param[in] auto_handle_events If true, automatically handle resulting events.
516 @param[in] spawn_thread If true, start a new thread for IO handling.
517 @param[in] options Parameter collection of type SBCommandInterpreterRunOptions.
518 @param[in] num_errors Initial error counter.
519 @param[in] quit_requested Initial quit request flag.
520 @param[in] stopped_for_crash Initial crash flag.
521 
522 @return
523 A tuple with the number of errors encountered by the interpreter, a boolean
524 indicating whether quitting the interpreter was requested and another boolean
525 set to True in case of a crash.
526 
527 Example: ::
528 
529     # Start an interactive lldb session from a script (with a valid debugger object
530     # created beforehand):
531     n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True,
532         False, lldb.SBCommandInterpreterRunOptions(), 0, False, False)") RunCommandInterpreter;
533     %apply int& INOUT { int& num_errors };
534     %apply bool& INOUT { bool& quit_requested };
535     %apply bool& INOUT { bool& stopped_for_crash };
536     void
537     RunCommandInterpreter (bool auto_handle_events,
538                            bool spawn_thread,
539                            SBCommandInterpreterRunOptions &options,
540                            int  &num_errors,
541                            bool &quit_requested,
542                            bool &stopped_for_crash);
543 
544     lldb::SBError
545     RunREPL (lldb::LanguageType language, const char *repl_options);
546 
547     SBTrace LoadTraceFromFile(SBError &error, const SBFileSpec &trace_description_file);
548 
549 #ifdef SWIGPYTHON
550     %pythoncode%{
551     def __iter__(self):
552         '''Iterate over all targets in a lldb.SBDebugger object.'''
553         return lldb_iter(self, 'GetNumTargets', 'GetTargetAtIndex')
554 
555     def __len__(self):
556         '''Return the number of targets in a lldb.SBDebugger object.'''
557         return self.GetNumTargets()
558     %}
559 #endif
560 
561 }; // class SBDebugger
562 
563 } // namespace lldb
564