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