1 //===-- SWIG Interface for SBThread -----------------------------*- 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 "Represents a thread of execution. :py:class:`SBProcess` contains SBThread(s).
13 
14 SBThreads can be referred to by their ID, which maps to the system specific thread
15 identifier, or by IndexID.  The ID may or may not be unique depending on whether the
16 system reuses its thread identifiers.  The IndexID is a monotonically increasing identifier
17 that will always uniquely reference a particular thread, and when that thread goes
18 away it will not be reused.
19 
20 SBThread supports frame iteration. For example (from test/python_api/
21 lldbutil/iter/TestLLDBIterator.py), ::
22 
23         from lldbutil import print_stacktrace
24         stopped_due_to_breakpoint = False
25         for thread in process:
26             if self.TraceOn():
27                 print_stacktrace(thread)
28             ID = thread.GetThreadID()
29             if thread.GetStopReason() == lldb.eStopReasonBreakpoint:
30                 stopped_due_to_breakpoint = True
31             for frame in thread:
32                 self.assertTrue(frame.GetThread().GetThreadID() == ID)
33                 if self.TraceOn():
34                     print frame
35 
36         self.assertTrue(stopped_due_to_breakpoint)
37 
38 See also :py:class:`SBFrame` ."
39 ) SBThread;
40 class SBThread
41 {
42 public:
43     //------------------------------------------------------------------
44     // Broadcaster bits.
45     //------------------------------------------------------------------
46     enum
47     {
48         eBroadcastBitStackChanged           = (1 << 0),
49         eBroadcastBitThreadSuspended        = (1 << 1),
50         eBroadcastBitThreadResumed          = (1 << 2),
51         eBroadcastBitSelectedFrameChanged   = (1 << 3),
52         eBroadcastBitThreadSelected         = (1 << 4)
53     };
54 
55 
56     SBThread ();
57 
58     SBThread (const lldb::SBThread &thread);
59 
60    ~SBThread();
61 
62     static const char *
63     GetBroadcasterClassName ();
64 
65     static bool
66     EventIsThreadEvent (const SBEvent &event);
67 
68     static SBFrame
69     GetStackFrameFromEvent (const SBEvent &event);
70 
71     static SBThread
72     GetThreadFromEvent (const SBEvent &event);
73 
74     bool
75     IsValid() const;
76 
77     explicit operator bool() const;
78 
79     void
80     Clear ();
81 
82     lldb::StopReason
83     GetStopReason();
84 
85     %feature("docstring", "
86     Get the number of words associated with the stop reason.
87     See also GetStopReasonDataAtIndex().") GetStopReasonDataCount;
88     size_t
89     GetStopReasonDataCount();
90 
91     %feature("docstring", "
92     Get information associated with a stop reason.
93 
94     Breakpoint stop reasons will have data that consists of pairs of
95     breakpoint IDs followed by the breakpoint location IDs (they always come
96     in pairs).
97 
98     Stop Reason              Count Data Type
99     ======================== ===== =========================================
100     eStopReasonNone          0
101     eStopReasonTrace         0
102     eStopReasonBreakpoint    N     duple: {breakpoint id, location id}
103     eStopReasonWatchpoint    1     watchpoint id
104     eStopReasonSignal        1     unix signal number
105     eStopReasonException     N     exception data
106     eStopReasonExec          0
107     eStopReasonFork          1     pid of the child process
108     eStopReasonVFork         1     pid of the child process
109     eStopReasonVForkDone     0
110     eStopReasonPlanComplete  0") GetStopReasonDataAtIndex;
111     uint64_t
112     GetStopReasonDataAtIndex(uint32_t idx);
113 
114     %feature("autodoc", "
115     Collects a thread's stop reason extended information dictionary and prints it
116     into the SBStream in a JSON format. The format of this JSON dictionary depends
117     on the stop reason and is currently used only for instrumentation plugins.") GetStopReasonExtendedInfoAsJSON;
118     bool
119     GetStopReasonExtendedInfoAsJSON (lldb::SBStream &stream);
120 
121     %feature("autodoc", "
122     Returns a collection of historical stack traces that are significant to the
123     current stop reason. Used by ThreadSanitizer, where we provide various stack
124     traces that were involved in a data race or other type of detected issue.") GetStopReasonExtendedBacktraces;
125     SBThreadCollection
126     GetStopReasonExtendedBacktraces (InstrumentationRuntimeType type);
127 
128 
129     %feature("autodoc", "
130     Pass only an (int)length and expect to get a Python string describing the
131     stop reason.") GetStopDescription;
132     size_t
133     GetStopDescription (char *dst_or_null, size_t dst_len);
134 
135     SBValue
136     GetStopReturnValue ();
137 
138     %feature("autodoc", "
139     Returns a unique thread identifier (type lldb::tid_t, typically a 64-bit type)
140     for the current SBThread that will remain constant throughout the thread's
141     lifetime in this process and will not be reused by another thread during this
142     process lifetime.  On Mac OS X systems, this is a system-wide unique thread
143     identifier; this identifier is also used by other tools like sample which helps
144     to associate data from those tools with lldb.  See related GetIndexID.")
145     GetThreadID;
146     lldb::tid_t
147     GetThreadID () const;
148 
149     %feature("autodoc", "
150     Return the index number for this SBThread.  The index number is the same thing
151     that a user gives as an argument to 'thread select' in the command line lldb.
152     These numbers start at 1 (for the first thread lldb sees in a debug session)
153     and increments up throughout the process lifetime.  An index number will not be
154     reused for a different thread later in a process - thread 1 will always be
155     associated with the same thread.  See related GetThreadID.
156     This method returns a uint32_t index number, takes no arguments.")
157     GetIndexID;
158     uint32_t
159     GetIndexID () const;
160 
161     const char *
162     GetName () const;
163 
164     %feature("autodoc", "
165     Return the queue name associated with this thread, if any, as a str.
166     For example, with a libdispatch (aka Grand Central Dispatch) queue.") GetQueueName;
167 
168     const char *
169     GetQueueName() const;
170 
171     %feature("autodoc", "
172     Return the dispatch_queue_id for this thread, if any, as a lldb::queue_id_t.
173     For example, with a libdispatch (aka Grand Central Dispatch) queue.") GetQueueID;
174 
175     lldb::queue_id_t
176     GetQueueID() const;
177 
178     %feature("docstring", "
179     Takes a path string and a SBStream reference as parameters, returns a bool.
180     Collects the thread's 'info' dictionary from the remote system, uses the path
181     argument to descend into the dictionary to an item of interest, and prints
182     it into the SBStream in a natural format.  Return bool is to indicate if
183     anything was printed into the stream (true) or not (false).") GetInfoItemByPathAsString;
184 
185     bool
186     GetInfoItemByPathAsString (const char *path, lldb::SBStream &strm);
187 
188     %feature("autodoc", "
189     Return the SBQueue for this thread.  If this thread is not currently associated
190     with a libdispatch queue, the SBQueue object's IsValid() method will return false.
191     If this SBThread is actually a HistoryThread, we may be able to provide QueueID
192     and QueueName, but not provide an SBQueue.  Those individual attributes may have
193     been saved for the HistoryThread without enough information to reconstitute the
194     entire SBQueue at that time.
195     This method takes no arguments, returns an SBQueue.") GetQueue;
196 
197     lldb::SBQueue
198     GetQueue () const;
199 
200     void
201     StepOver (lldb::RunMode stop_other_threads = lldb::eOnlyDuringStepping);
202 
203     %feature("autodoc",
204     "Do a source level single step over in the currently selected thread.") StepOver;
205     void
206     StepOver (lldb::RunMode stop_other_threads, SBError &error);
207 
208     void
209     StepInto (lldb::RunMode stop_other_threads = lldb::eOnlyDuringStepping);
210 
211     void
212     StepInto (const char *target_name, lldb::RunMode stop_other_threads = lldb::eOnlyDuringStepping);
213 
214     %feature("autodoc", "
215     Step the current thread from the current source line to the line given by end_line, stopping if
216     the thread steps into the function given by target_name.  If target_name is None, then stepping will stop
217     in any of the places we would normally stop.") StepInto;
218     void
219     StepInto (const char *target_name,
220               uint32_t end_line,
221               SBError &error,
222               lldb::RunMode stop_other_threads = lldb::eOnlyDuringStepping);
223 
224     void
225     StepOut ();
226 
227     %feature("autodoc",
228     "Step out of the currently selected thread.") StepOut;
229     void
230     StepOut (SBError &error);
231 
232     void
233     StepOutOfFrame (SBFrame &frame);
234 
235     %feature("autodoc",
236     "Step out of the specified frame.") StepOutOfFrame;
237     void
238     StepOutOfFrame (SBFrame &frame, SBError &error);
239 
240     void
241     StepInstruction(bool step_over);
242 
243     %feature("autodoc",
244     "Do an instruction level single step in the currently selected thread.") StepInstruction;
245     void
246     StepInstruction(bool step_over, SBError &error);
247 
248     SBError
249     StepOverUntil (lldb::SBFrame &frame,
250                    lldb::SBFileSpec &file_spec,
251                    uint32_t line);
252 
253     SBError
254     StepUsingScriptedThreadPlan (const char *script_class_name);
255 
256     SBError
257     StepUsingScriptedThreadPlan (const char *script_class_name, bool resume_immediately);
258 
259     SBError
260     StepUsingScriptedThreadPlan(const char *script_class_name,
261                                 lldb::SBStructuredData &args_data,
262                                 bool resume_immediately);
263 
264     SBError
265     JumpToLine (lldb::SBFileSpec &file_spec, uint32_t line);
266 
267     void
268     RunToAddress (lldb::addr_t addr);
269 
270     void
271     RunToAddress (lldb::addr_t addr, SBError &error);
272 
273     %feature("autodoc", "
274     Force a return from the frame passed in (and any frames younger than it)
275     without executing any more code in those frames.  If return_value contains
276     a valid SBValue, that will be set as the return value from frame.  Note, at
277     present only scalar return values are supported.") ReturnFromFrame;
278 
279     SBError
280     ReturnFromFrame (SBFrame &frame, SBValue &return_value);
281 
282     %feature("autodoc", "
283     Unwind the stack frames from the innermost expression evaluation.
284     This API is equivalent to 'thread return -x'.") UnwindInnermostExpression;
285 
286     SBError
287     UnwindInnermostExpression();
288 
289     %feature("docstring", "
290     LLDB currently supports process centric debugging which means when any
291     thread in a process stops, all other threads are stopped. The Suspend()
292     call here tells our process to suspend a thread and not let it run when
293     the other threads in a process are allowed to run. So when
294     SBProcess::Continue() is called, any threads that aren't suspended will
295     be allowed to run. If any of the SBThread functions for stepping are
296     called (StepOver, StepInto, StepOut, StepInstruction, RunToAddres), the
297     thread will now be allowed to run and these functions will simply return.
298 
299     Eventually we plan to add support for thread centric debugging where
300     each thread is controlled individually and each thread would broadcast
301     its state, but we haven't implemented this yet.
302 
303     Likewise the SBThread::Resume() call will again allow the thread to run
304     when the process is continued.
305 
306     Suspend() and Resume() functions are not currently reference counted, if
307     anyone has the need for them to be reference counted, please let us
308     know.") Suspend;
309     bool
310     Suspend();
311 
312     bool
313     Suspend(SBError &error);
314 
315     bool
316     Resume ();
317 
318     bool
319     Resume (SBError &error);
320 
321     bool
322     IsSuspended();
323 
324     bool
325     IsStopped();
326 
327     uint32_t
328     GetNumFrames ();
329 
330     lldb::SBFrame
331     GetFrameAtIndex (uint32_t idx);
332 
333     lldb::SBFrame
334     GetSelectedFrame ();
335 
336     lldb::SBFrame
337     SetSelectedFrame (uint32_t frame_idx);
338 
339     lldb::SBProcess
340     GetProcess ();
341 
342     bool
343     GetDescription (lldb::SBStream &description) const;
344 
345     %feature("docstring", "
346     Get the description strings for this thread that match what the
347     lldb driver will present, using the thread-format (stop_format==false)
348     or thread-stop-format (stop_format = true).") GetDescription;
349     bool GetDescription(lldb::SBStream &description, bool stop_format) const;
350 
351     bool
352     GetStatus (lldb::SBStream &status) const;
353 
354     bool
355     operator == (const lldb::SBThread &rhs) const;
356 
357     bool
358     operator != (const lldb::SBThread &rhs) const;
359 
360     %feature("autodoc","
361     Given an argument of str to specify the type of thread-origin extended
362     backtrace to retrieve, query whether the origin of this thread is
363     available.  An SBThread is retured; SBThread.IsValid will return true
364     if an extended backtrace was available.  The returned SBThread is not
365     a part of the SBProcess' thread list and it cannot be manipulated like
366     normal threads -- you cannot step or resume it, for instance -- it is
367     intended to used primarily for generating a backtrace.  You may request
368     the returned thread's own thread origin in turn.") GetExtendedBacktraceThread;
369     lldb::SBThread
370     GetExtendedBacktraceThread (const char *type);
371 
372     %feature("autodoc","
373     Takes no arguments, returns a uint32_t.
374     If this SBThread is an ExtendedBacktrace thread, get the IndexID of the
375     original thread that this ExtendedBacktrace thread represents, if
376     available.  The thread that was running this backtrace in the past may
377     not have been registered with lldb's thread index (if it was created,
378     did its work, and was destroyed without lldb ever stopping execution).
379     In that case, this ExtendedBacktrace thread's IndexID will be returned.") GetExtendedBacktraceOriginatingIndexID;
380     uint32_t
381     GetExtendedBacktraceOriginatingIndexID();
382 
383     %feature("autodoc","
384     Returns an SBValue object represeting the current exception for the thread,
385     if there is any. Currently, this works for Obj-C code and returns an SBValue
386     representing the NSException object at the throw site or that's currently
387     being processes.") GetCurrentException;
388     lldb::SBValue
389     GetCurrentException();
390 
391     %feature("autodoc","
392     Returns a historical (fake) SBThread representing the stack trace of an
393     exception, if there is one for the thread. Currently, this works for Obj-C
394     code, and can retrieve the throw-site backtrace of an NSException object
395     even when the program is no longer at the throw site.") GetCurrentExceptionBacktrace;
396     lldb::SBThread
397     GetCurrentExceptionBacktrace();
398 
399     %feature("autodoc","
400     Takes no arguments, returns a bool.
401     lldb may be able to detect that function calls should not be executed
402     on a given thread at a particular point in time.  It is recommended that
403     this is checked before performing an inferior function call on a given
404     thread.") SafeToCallFunctions;
405     bool
406     SafeToCallFunctions ();
407 
408     STRING_EXTENSION(SBThread)
409 
410 #ifdef SWIGPYTHON
411     %pythoncode %{
412         def __iter__(self):
413             '''Iterate over all frames in a lldb.SBThread object.'''
414             return lldb_iter(self, 'GetNumFrames', 'GetFrameAtIndex')
415 
416         def __len__(self):
417             '''Return the number of frames in a lldb.SBThread object.'''
418             return self.GetNumFrames()
419 
420         class frames_access(object):
421             '''A helper object that will lazily hand out frames for a thread when supplied an index.'''
422             def __init__(self, sbthread):
423                 self.sbthread = sbthread
424 
425             def __len__(self):
426                 if self.sbthread:
427                     return int(self.sbthread.GetNumFrames())
428                 return 0
429 
430             def __getitem__(self, key):
431                 if type(key) is int and key < self.sbthread.GetNumFrames():
432                     return self.sbthread.GetFrameAtIndex(key)
433                 return None
434 
435         def get_frames_access_object(self):
436             '''An accessor function that returns a frames_access() object which allows lazy frame access from a lldb.SBThread object.'''
437             return self.frames_access (self)
438 
439         def get_thread_frames(self):
440             '''An accessor function that returns a list() that contains all frames in a lldb.SBThread object.'''
441             frames = []
442             for frame in self:
443                 frames.append(frame)
444             return frames
445 
446         id = property(GetThreadID, None, doc='''A read only property that returns the thread ID as an integer.''')
447         idx = property(GetIndexID, None, doc='''A read only property that returns the thread index ID as an integer. Thread index ID values start at 1 and increment as threads come and go and can be used to uniquely identify threads.''')
448         return_value = property(GetStopReturnValue, None, doc='''A read only property that returns an lldb object that represents the return value from the last stop (lldb.SBValue) if we just stopped due to stepping out of a function.''')
449         process = property(GetProcess, None, doc='''A read only property that returns an lldb object that represents the process (lldb.SBProcess) that owns this thread.''')
450         num_frames = property(GetNumFrames, None, doc='''A read only property that returns the number of stack frames in this thread as an integer.''')
451         frames = property(get_thread_frames, None, doc='''A read only property that returns a list() of lldb.SBFrame objects for all frames in this thread.''')
452         frame = property(get_frames_access_object, None, doc='''A read only property that returns an object that can be used to access frames as an array ("frame_12 = lldb.thread.frame[12]").''')
453         name = property(GetName, None, doc='''A read only property that returns the name of this thread as a string.''')
454         queue = property(GetQueueName, None, doc='''A read only property that returns the dispatch queue name of this thread as a string.''')
455         queue_id = property(GetQueueID, None, doc='''A read only property that returns the dispatch queue id of this thread as an integer.''')
456         stop_reason = property(GetStopReason, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eStopReason") that represents the reason this thread stopped.''')
457         is_suspended = property(IsSuspended, None, doc='''A read only property that returns a boolean value that indicates if this thread is suspended.''')
458         is_stopped = property(IsStopped, None, doc='''A read only property that returns a boolean value that indicates if this thread is stopped but not exited.''')
459     %}
460 #endif
461 
462 };
463 
464 } // namespace lldb
465