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
9namespace lldb {
10
11%feature("docstring",
12"SBDebugger is the primordial object that creates SBTargets and provides
13access to them.  It also manages the overall debugging experiences.
14
15For example (from example/disasm.py),
16
17import lldb
18import os
19import sys
20
21def disassemble_instructions (insts):
22    for i in insts:
23        print i
24
25...
26
27# Create a new debugger instance
28debugger = 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.
32debugger.SetAsync (False)
33
34# Create a target from a file and arch
35print('Creating a target for \'%s\'' % exe)
36
37target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
38
39if 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
108Sometimes you need to create an empty target that will get filled in later.  The most common use for this
109is to attach to a process by name or pid where you don't know the executable up front.  The most convenient way
110to do this is:
111
112target = debugger.CreateTarget('')
113error = lldb.SBError()
114process = target.AttachToProcessWithName(debugger.GetListener(), 'PROCESS_NAME', False, error)
115
116or the equivalent arguments for AttachToProcessWithID.") SBDebugger;
117class SBDebugger
118{
119public:
120
121    static void
122    Initialize();
123
124    static SBError
125    InitializeWithErrorHandling();
126
127    static void
128    Terminate();
129
130    static lldb::SBDebugger
131    Create();
132
133    static lldb::SBDebugger
134    Create(bool source_init_files);
135
136    static lldb::SBDebugger
137    Create(bool source_init_files, lldb::LogOutputCallback log_callback, void *baton);
138
139    static void
140    Destroy (lldb::SBDebugger &debugger);
141
142    static void
143    MemoryPressureDetected();
144
145    SBDebugger();
146
147    SBDebugger(const lldb::SBDebugger &rhs);
148
149    ~SBDebugger();
150
151    bool
152    IsValid() const;
153
154    explicit operator bool() const;
155
156    void
157    Clear ();
158
159    void
160    SetAsync (bool b);
161
162    bool
163    GetAsync ();
164
165    void
166    SkipLLDBInitFiles (bool b);
167
168#ifdef SWIGPYTHON
169    %pythoncode %{
170        def SetOutputFileHandle(self, file, transfer_ownership):
171            "DEPRECATED, use SetOutputFile"
172            if file is None:
173                import sys
174                file = sys.stdout
175            self.SetOutputFile(SBFile.Create(file, borrow=True))
176
177        def SetInputFileHandle(self, file, transfer_ownership):
178            "DEPRECATED, use SetInputFile"
179            if file is None:
180                import sys
181                file = sys.stdin
182            self.SetInputFile(SBFile.Create(file, borrow=True))
183
184        def SetErrorFileHandle(self, file, transfer_ownership):
185            "DEPRECATED, use SetErrorFile"
186            if file is None:
187                import sys
188                file = sys.stderr
189            self.SetErrorFile(SBFile.Create(file, borrow=True))
190    %}
191#endif
192
193
194    %extend {
195
196        lldb::FileSP GetInputFileHandle() {
197            return self->GetInputFile().GetFile();
198        }
199
200        lldb::FileSP GetOutputFileHandle() {
201            return self->GetOutputFile().GetFile();
202        }
203
204        lldb::FileSP GetErrorFileHandle() {
205            return self->GetErrorFile().GetFile();
206        }
207    }
208
209    SBError
210    SetInputFile (SBFile file);
211
212    SBError
213    SetOutputFile (SBFile file);
214
215    SBError
216    SetErrorFile (SBFile file);
217
218    SBError
219    SetInputFile (FileSP file);
220
221    SBError
222    SetOutputFile (FileSP file);
223
224    SBError
225    SetErrorFile (FileSP file);
226
227    SBFile
228    GetInputFile ();
229
230    SBFile
231    GetOutputFile ();
232
233    SBFile
234    GetErrorFile ();
235
236    lldb::SBCommandInterpreter
237    GetCommandInterpreter ();
238
239    void
240    HandleCommand (const char *command);
241
242    lldb::SBListener
243    GetListener ();
244
245    void
246    HandleProcessEvent (const lldb::SBProcess &process,
247                        const lldb::SBEvent &event,
248                        SBFile out,
249                        SBFile err);
250
251    void
252    HandleProcessEvent (const lldb::SBProcess &process,
253                        const lldb::SBEvent &event,
254                        FileSP BORROWED,
255                        FileSP BORROWED);
256
257    lldb::SBTarget
258    CreateTarget (const char *filename,
259                  const char *target_triple,
260                  const char *platform_name,
261                  bool add_dependent_modules,
262                  lldb::SBError& sb_error);
263
264    lldb::SBTarget
265    CreateTargetWithFileAndTargetTriple (const char *filename,
266                                         const char *target_triple);
267
268    lldb::SBTarget
269    CreateTargetWithFileAndArch (const char *filename,
270                                 const char *archname);
271
272    lldb::SBTarget
273    CreateTarget (const char *filename);
274
275    %feature("docstring",
276    "The dummy target holds breakpoints and breakpoint names that will prime newly created targets."
277    ) GetDummyTarget;
278    lldb::SBTarget GetDummyTarget();
279
280    %feature("docstring",
281    "Return true if target is deleted from the target list of the debugger."
282    ) DeleteTarget;
283    bool
284    DeleteTarget (lldb::SBTarget &target);
285
286    lldb::SBTarget
287    GetTargetAtIndex (uint32_t idx);
288
289    uint32_t
290    GetIndexOfTarget (lldb::SBTarget target);
291
292    lldb::SBTarget
293    FindTargetWithProcessID (pid_t pid);
294
295    lldb::SBTarget
296    FindTargetWithFileAndArch (const char *filename,
297                               const char *arch);
298
299    uint32_t
300    GetNumTargets ();
301
302    lldb::SBTarget
303    GetSelectedTarget ();
304
305    void
306    SetSelectedTarget (lldb::SBTarget &target);
307
308    lldb::SBPlatform
309    GetSelectedPlatform();
310
311    void
312    SetSelectedPlatform(lldb::SBPlatform &platform);
313
314    %feature("docstring",
315    "Get the number of currently active platforms."
316    ) GetNumPlatforms;
317    uint32_t
318    GetNumPlatforms ();
319
320    %feature("docstring",
321    "Get one of the currently active platforms."
322    ) GetPlatformAtIndex;
323    lldb::SBPlatform
324    GetPlatformAtIndex (uint32_t idx);
325
326    %feature("docstring",
327    "Get the number of available platforms."
328    ) GetNumAvailablePlatforms;
329    uint32_t
330    GetNumAvailablePlatforms ();
331
332    %feature("docstring", "
333    Get the name and description of one of the available platforms.
334
335    @param idx Zero-based index of the platform for which info should be
336               retrieved, must be less than the value returned by
337               GetNumAvailablePlatforms().") GetAvailablePlatformInfoAtIndex;
338    lldb::SBStructuredData
339    GetAvailablePlatformInfoAtIndex (uint32_t idx);
340
341    lldb::SBSourceManager
342    GetSourceManager ();
343
344    // REMOVE: just for a quick fix, need to expose platforms through
345    // SBPlatform from this class.
346    lldb::SBError
347    SetCurrentPlatform (const char *platform_name);
348
349    bool
350    SetCurrentPlatformSDKRoot (const char *sysroot);
351
352    // FIXME: Once we get the set show stuff in place, the driver won't need
353    // an interface to the Set/Get UseExternalEditor.
354    bool
355    SetUseExternalEditor (bool input);
356
357    bool
358    GetUseExternalEditor ();
359
360    bool
361    SetUseColor (bool use_color);
362
363    bool
364    GetUseColor () const;
365
366    static bool
367    GetDefaultArchitecture (char *arch_name, size_t arch_name_len);
368
369    static bool
370    SetDefaultArchitecture (const char *arch_name);
371
372    lldb::ScriptLanguage
373    GetScriptingLanguage (const char *script_language_name);
374
375    static const char *
376    GetVersionString ();
377
378    static const char *
379    StateAsCString (lldb::StateType state);
380
381    static SBStructuredData GetBuildConfiguration();
382
383    static bool
384    StateIsRunningState (lldb::StateType state);
385
386    static bool
387    StateIsStoppedState (lldb::StateType state);
388
389    bool
390    EnableLog (const char *channel, const char ** types);
391
392    void
393    SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton);
394
395    void
396    DispatchInput (const void *data, size_t data_len);
397
398    void
399    DispatchInputInterrupt ();
400
401    void
402    DispatchInputEndOfFile ();
403
404    const char *
405    GetInstanceName  ();
406
407    static SBDebugger
408    FindDebuggerWithID (int id);
409
410    static lldb::SBError
411    SetInternalVariable (const char *var_name, const char *value, const char *debugger_instance_name);
412
413    static lldb::SBStringList
414    GetInternalVariableValue (const char *var_name, const char *debugger_instance_name);
415
416    bool
417    GetDescription (lldb::SBStream &description);
418
419    uint32_t
420    GetTerminalWidth () const;
421
422    void
423    SetTerminalWidth (uint32_t term_width);
424
425    lldb::user_id_t
426    GetID ();
427
428    const char *
429    GetPrompt() const;
430
431    void
432    SetPrompt (const char *prompt);
433
434    const char *
435    GetReproducerPath() const;
436
437    lldb::ScriptLanguage
438    GetScriptLanguage() const;
439
440    void
441    SetScriptLanguage (lldb::ScriptLanguage script_lang);
442
443    bool
444    GetCloseInputOnEOF () const;
445
446    void
447    SetCloseInputOnEOF (bool b);
448
449    lldb::SBTypeCategory
450    GetCategory (const char* category_name);
451
452    SBTypeCategory
453    GetCategory (lldb::LanguageType lang_type);
454
455    lldb::SBTypeCategory
456    CreateCategory (const char* category_name);
457
458    bool
459    DeleteCategory (const char* category_name);
460
461    uint32_t
462    GetNumCategories ();
463
464    lldb::SBTypeCategory
465    GetCategoryAtIndex (uint32_t);
466
467    lldb::SBTypeCategory
468    GetDefaultCategory();
469
470    lldb::SBTypeFormat
471    GetFormatForType (lldb::SBTypeNameSpecifier);
472
473    lldb::SBTypeSummary
474    GetSummaryForType (lldb::SBTypeNameSpecifier);
475
476    lldb::SBTypeFilter
477    GetFilterForType (lldb::SBTypeNameSpecifier);
478
479    lldb::SBTypeSynthetic
480    GetSyntheticForType (lldb::SBTypeNameSpecifier);
481
482    STRING_EXTENSION(SBDebugger)
483
484    %feature("docstring",
485"Launch a command interpreter session. Commands are read from standard input or
486from the input handle specified for the debugger object. Output/errors are
487similarly redirected to standard output/error or the configured handles.
488
489@param[in] auto_handle_events If true, automatically handle resulting events.
490@param[in] spawn_thread If true, start a new thread for IO handling.
491@param[in] options Parameter collection of type SBCommandInterpreterRunOptions.
492@param[in] num_errors Initial error counter.
493@param[in] quit_requested Initial quit request flag.
494@param[in] stopped_for_crash Initial crash flag.
495
496@return
497A tuple with the number of errors encountered by the interpreter, a boolean
498indicating whether quitting the interpreter was requested and another boolean
499set to True in case of a crash.
500
501Example:
502
503# Start an interactive lldb session from a script (with a valid debugger object
504# created beforehand):
505n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True,
506    False, lldb.SBCommandInterpreterRunOptions(), 0, False, False)") RunCommandInterpreter;
507    %apply int& INOUT { int& num_errors };
508    %apply bool& INOUT { bool& quit_requested };
509    %apply bool& INOUT { bool& stopped_for_crash };
510    void
511    RunCommandInterpreter (bool auto_handle_events,
512                           bool spawn_thread,
513                           SBCommandInterpreterRunOptions &options,
514                           int  &num_errors,
515                           bool &quit_requested,
516                           bool &stopped_for_crash);
517
518    lldb::SBError
519    RunREPL (lldb::LanguageType language, const char *repl_options);
520
521#ifdef SWIGPYTHON
522    %pythoncode%{
523    def __iter__(self):
524        '''Iterate over all targets in a lldb.SBDebugger object.'''
525        return lldb_iter(self, 'GetNumTargets', 'GetTargetAtIndex')
526
527    def __len__(self):
528        '''Return the number of targets in a lldb.SBDebugger object.'''
529        return self.GetNumTargets()
530    %}
531#endif
532
533}; // class SBDebugger
534
535} // namespace lldb
536