1 //===-- SWIG Interface for SBProcess ----------------------------*- 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 the process associated with the target program.
13 
14 SBProcess supports thread iteration. For example (from test/lldbutil.py),
15 
16 # ==================================================
17 # Utility functions related to Threads and Processes
18 # ==================================================
19 
20 def get_stopped_threads(process, reason):
21     '''Returns the thread(s) with the specified stop reason in a list.
22 
23     The list can be empty if no such thread exists.
24     '''
25     threads = []
26     for t in process:
27         if t.GetStopReason() == reason:
28             threads.append(t)
29     return threads
30 
31 ...
32 "
33 ) SBProcess;
34 class SBProcess
35 {
36 public:
37     enum
38     {
39         eBroadcastBitStateChanged   = (1 << 0),
40         eBroadcastBitInterrupt      = (1 << 1),
41         eBroadcastBitSTDOUT         = (1 << 2),
42         eBroadcastBitSTDERR         = (1 << 3),
43         eBroadcastBitProfileData    = (1 << 4),
44         eBroadcastBitStructuredData = (1 << 5)
45     };
46 
47     SBProcess ();
48 
49     SBProcess (const lldb::SBProcess& rhs);
50 
51     ~SBProcess();
52 
53     static const char *
54     GetBroadcasterClassName ();
55 
56     const char *
57     GetPluginName ();
58 
59     const char *
60     GetShortPluginName ();
61 
62     void
63     Clear ();
64 
65     bool
66     IsValid() const;
67 
68     explicit operator bool() const;
69 
70     lldb::SBTarget
71     GetTarget() const;
72 
73     lldb::ByteOrder
74     GetByteOrder() const;
75 
76     %feature("autodoc", "
77     Writes data into the current process's stdin. API client specifies a Python
78     string as the only argument.") PutSTDIN;
79     size_t
80     PutSTDIN (const char *src, size_t src_len);
81 
82     %feature("autodoc", "
83     Reads data from the current process's stdout stream. API client specifies
84     the size of the buffer to read data into. It returns the byte buffer in a
85     Python string.") GetSTDOUT;
86     size_t
87     GetSTDOUT (char *dst, size_t dst_len) const;
88 
89     %feature("autodoc", "
90     Reads data from the current process's stderr stream. API client specifies
91     the size of the buffer to read data into. It returns the byte buffer in a
92     Python string.") GetSTDERR;
93     size_t
94     GetSTDERR (char *dst, size_t dst_len) const;
95 
96     size_t
97     GetAsyncProfileData(char *dst, size_t dst_len) const;
98 
99     void
100     ReportEventState (const lldb::SBEvent &event, SBFile out) const;
101 
102     void
103     ReportEventState (const lldb::SBEvent &event, FileSP BORROWED) const;
104 
105     void
106     AppendEventStateReport (const lldb::SBEvent &event, lldb::SBCommandReturnObject &result);
107 
108     %feature("docstring", "
109     Remote connection related functions. These will fail if the
110     process is not in eStateConnected. They are intended for use
111     when connecting to an externally managed debugserver instance.") RemoteAttachToProcessWithID;
112     bool
113     RemoteAttachToProcessWithID (lldb::pid_t pid,
114                                  lldb::SBError& error);
115 
116     %feature("docstring",
117     "See SBTarget.Launch for argument description and usage."
118     ) RemoteLaunch;
119     bool
120     RemoteLaunch (char const **argv,
121                   char const **envp,
122                   const char *stdin_path,
123                   const char *stdout_path,
124                   const char *stderr_path,
125                   const char *working_directory,
126                   uint32_t launch_flags,
127                   bool stop_at_entry,
128                   lldb::SBError& error);
129 
130     //------------------------------------------------------------------
131     // Thread related functions
132     //------------------------------------------------------------------
133     uint32_t
134     GetNumThreads ();
135 
136     %feature("autodoc", "
137     Returns the INDEX'th thread from the list of current threads.  The index
138     of a thread is only valid for the current stop.  For a persistent thread
139     identifier use either the thread ID or the IndexID.  See help on SBThread
140     for more details.") GetThreadAtIndex;
141     lldb::SBThread
142     GetThreadAtIndex (size_t index);
143 
144     %feature("autodoc", "
145     Returns the thread with the given thread ID.") GetThreadByID;
146     lldb::SBThread
147     GetThreadByID (lldb::tid_t sb_thread_id);
148 
149     %feature("autodoc", "
150     Returns the thread with the given thread IndexID.") GetThreadByIndexID;
151     lldb::SBThread
152     GetThreadByIndexID (uint32_t index_id);
153 
154     %feature("autodoc", "
155     Returns the currently selected thread.") GetSelectedThread;
156     lldb::SBThread
157     GetSelectedThread () const;
158 
159     %feature("autodoc", "
160     Lazily create a thread on demand through the current OperatingSystem plug-in, if the current OperatingSystem plug-in supports it.") CreateOSPluginThread;
161     lldb::SBThread
162     CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context);
163 
164     bool
165     SetSelectedThread (const lldb::SBThread &thread);
166 
167     bool
168     SetSelectedThreadByID (lldb::tid_t tid);
169 
170     bool
171     SetSelectedThreadByIndexID (uint32_t index_id);
172 
173     //------------------------------------------------------------------
174     // Queue related functions
175     //------------------------------------------------------------------
176     uint32_t
177     GetNumQueues ();
178 
179     lldb::SBQueue
180     GetQueueAtIndex (uint32_t index);
181 
182     //------------------------------------------------------------------
183     // Stepping related functions
184     //------------------------------------------------------------------
185 
186     lldb::StateType
187     GetState ();
188 
189     int
190     GetExitStatus ();
191 
192     const char *
193     GetExitDescription ();
194 
195     %feature("autodoc", "
196     Returns the process ID of the process.") GetProcessID;
197     lldb::pid_t
198     GetProcessID ();
199 
200     %feature("autodoc", "
201     Returns an integer ID that is guaranteed to be unique across all process instances. This is not the process ID, just a unique integer for comparison and caching purposes.") GetUniqueID;
202     uint32_t
203     GetUniqueID();
204 
205     uint32_t
206     GetAddressByteSize() const;
207 
208     %feature("docstring", "
209     Kills the process and shuts down all threads that were spawned to
210     track and monitor process.") Destroy;
211     lldb::SBError
212     Destroy ();
213 
214     lldb::SBError
215     Continue ();
216 
217     lldb::SBError
218     Stop ();
219 
220     %feature("docstring", "Same as Destroy(self).") Destroy;
221     lldb::SBError
222     Kill ();
223 
224     lldb::SBError
225     Detach ();
226 
227     %feature("docstring", "Sends the process a unix signal.") Signal;
228     lldb::SBError
229     Signal (int signal);
230 
231     lldb::SBUnixSignals
232     GetUnixSignals();
233 
234     %feature("docstring", "
235     Returns a stop id that will increase every time the process executes.  If
236     include_expression_stops is true, then stops caused by expression evaluation
237     will cause the returned value to increase, otherwise the counter returned will
238     only increase when execution is continued explicitly by the user.  Note, the value
239     will always increase, but may increase by more than one per stop.") GetStopID;
240     uint32_t
241     GetStopID(bool include_expression_stops = false);
242 
243     void
244     SendAsyncInterrupt();
245 
246     %feature("autodoc", "
247     Reads memory from the current process's address space and removes any
248     traps that may have been inserted into the memory. It returns the byte
249     buffer in a Python string. Example:
250 
251     # Read 4 bytes from address 'addr' and assume error.Success() is True.
252     content = process.ReadMemory(addr, 4, error)
253     new_bytes = bytearray(content)") ReadMemory;
254     size_t
255     ReadMemory (addr_t addr, void *buf, size_t size, lldb::SBError &error);
256 
257     %feature("autodoc", "
258     Writes memory to the current process's address space and maintains any
259     traps that might be present due to software breakpoints. Example:
260 
261     # Create a Python string from the byte array.
262     new_value = str(bytes)
263     result = process.WriteMemory(addr, new_value, error)
264     if not error.Success() or result != len(bytes):
265         print('SBProcess.WriteMemory() failed!')") WriteMemory;
266     size_t
267     WriteMemory (addr_t addr, const void *buf, size_t size, lldb::SBError &error);
268 
269     %feature("autodoc", "
270     Reads a NULL terminated C string from the current process's address space.
271     It returns a python string of the exact length, or truncates the string if
272     the maximum character limit is reached. Example:
273 
274     # Read a C string of at most 256 bytes from address '0x1000'
275     error = lldb.SBError()
276     cstring = process.ReadCStringFromMemory(0x1000, 256, error)
277     if error.Success():
278         print('cstring: ', cstring)
279     else
280         print('error: ', error)") ReadCStringFromMemory;
281 
282     size_t
283     ReadCStringFromMemory (addr_t addr, void *char_buf, size_t size, lldb::SBError &error);
284 
285     %feature("autodoc", "
286     Reads an unsigned integer from memory given a byte size and an address.
287     Returns the unsigned integer that was read. Example:
288 
289     # Read a 4 byte unsigned integer from address 0x1000
290     error = lldb.SBError()
291     uint = ReadUnsignedFromMemory(0x1000, 4, error)
292     if error.Success():
293         print('integer: %u' % uint)
294     else
295         print('error: ', error)") ReadUnsignedFromMemory;
296 
297     uint64_t
298     ReadUnsignedFromMemory (addr_t addr, uint32_t byte_size, lldb::SBError &error);
299 
300     %feature("autodoc", "
301     Reads a pointer from memory from an address and returns the value. Example:
302 
303     # Read a pointer from address 0x1000
304     error = lldb.SBError()
305     ptr = ReadPointerFromMemory(0x1000, error)
306     if error.Success():
307         print('pointer: 0x%x' % ptr)
308     else
309         print('error: ', error)") ReadPointerFromMemory;
310 
311     lldb::addr_t
312     ReadPointerFromMemory (addr_t addr, lldb::SBError &error);
313 
314 
315     // Events
316     static lldb::StateType
317     GetStateFromEvent (const lldb::SBEvent &event);
318 
319     static bool
320     GetRestartedFromEvent (const lldb::SBEvent &event);
321 
322     static size_t
323     GetNumRestartedReasonsFromEvent (const lldb::SBEvent &event);
324 
325     static const char *
326     GetRestartedReasonAtIndexFromEvent (const lldb::SBEvent &event, size_t idx);
327 
328     static lldb::SBProcess
329     GetProcessFromEvent (const lldb::SBEvent &event);
330 
331     static bool
332     GetInterruptedFromEvent (const lldb::SBEvent &event);
333 
334     static lldb::SBStructuredData
335     GetStructuredDataFromEvent (const lldb::SBEvent &event);
336 
337     static bool
338     EventIsProcessEvent (const lldb::SBEvent &event);
339 
340     static bool
341     EventIsStructuredDataEvent (const lldb::SBEvent &event);
342 
343     lldb::SBBroadcaster
344     GetBroadcaster () const;
345 
346     bool
347     GetDescription (lldb::SBStream &description);
348 
349     %feature("autodoc", "
350     Returns the process' extended crash information.") GetExtendedCrashInformation;
351     lldb::SBStructuredData
352     GetExtendedCrashInformation ();
353 
354     uint32_t
355     GetNumSupportedHardwareWatchpoints (lldb::SBError &error) const;
356 
357     uint32_t
358     LoadImage (lldb::SBFileSpec &image_spec, lldb::SBError &error);
359 
360     %feature("autodoc", "
361     Load the library whose filename is given by image_spec looking in all the
362     paths supplied in the paths argument.  If successful, return a token that
363     can be passed to UnloadImage and fill loaded_path with the path that was
364     successfully loaded.  On failure, return
365     lldb.LLDB_INVALID_IMAGE_TOKEN.") LoadImageUsingPaths;
366     uint32_t
367     LoadImageUsingPaths(const lldb::SBFileSpec &image_spec,
368                         SBStringList &paths,
369                         lldb::SBFileSpec &loaded_path,
370                         SBError &error);
371 
372     lldb::SBError
373     UnloadImage (uint32_t image_token);
374 
375     lldb::SBError
376     SendEventData (const char *event_data);
377 
378     %feature("autodoc", "
379     Return the number of different thread-origin extended backtraces
380     this process can support as a uint32_t.
381     When the process is stopped and you have an SBThread, lldb may be
382     able to show a backtrace of when that thread was originally created,
383     or the work item was enqueued to it (in the case of a libdispatch
384     queue).") GetNumExtendedBacktraceTypes;
385 
386     uint32_t
387     GetNumExtendedBacktraceTypes ();
388 
389     %feature("autodoc", "
390     Takes an index argument, returns the name of one of the thread-origin
391     extended backtrace methods as a str.") GetExtendedBacktraceTypeAtIndex;
392 
393     const char *
394     GetExtendedBacktraceTypeAtIndex (uint32_t idx);
395 
396     lldb::SBThreadCollection
397     GetHistoryThreads (addr_t addr);
398 
399     bool
400     IsInstrumentationRuntimePresent(lldb::InstrumentationRuntimeType type);
401 
402     lldb::SBError
403     SaveCore(const char *file_name);
404 
405     lldb::SBTrace
406     StartTrace(SBTraceOptions &options, lldb::SBError &error);
407 
408     lldb::SBError
409     GetMemoryRegionInfo(lldb::addr_t load_addr, lldb::SBMemoryRegionInfo &region_info);
410 
411     lldb::SBMemoryRegionInfoList
412     GetMemoryRegions();
413 
414     %feature("autodoc", "
415     Get information about the process.
416     Valid process info will only be returned when the process is alive,
417     use IsValid() to check if the info returned is valid.
418 
419     process_info = process.GetProcessInfo()
420     if process_info.IsValid():
421         process_info.GetProcessID()") GetProcessInfo;
422     lldb::SBProcessInfo
423     GetProcessInfo();
424 
425     STRING_EXTENSION(SBProcess)
426 
427 #ifdef SWIGPYTHON
428     %pythoncode %{
429         def __get_is_alive__(self):
430             '''Returns "True" if the process is currently alive, "False" otherwise'''
431             s = self.GetState()
432             if (s == eStateAttaching or
433                 s == eStateLaunching or
434                 s == eStateStopped or
435                 s == eStateRunning or
436                 s == eStateStepping or
437                 s == eStateCrashed or
438                 s == eStateSuspended):
439                 return True
440             return False
441 
442         def __get_is_running__(self):
443             '''Returns "True" if the process is currently running, "False" otherwise'''
444             state = self.GetState()
445             if state == eStateRunning or state == eStateStepping:
446                 return True
447             return False
448 
449         def __get_is_stopped__(self):
450             '''Returns "True" if the process is currently stopped, "False" otherwise'''
451             state = self.GetState()
452             if state == eStateStopped or state == eStateCrashed or state == eStateSuspended:
453                 return True
454             return False
455 
456         class threads_access(object):
457             '''A helper object that will lazily hand out thread for a process when supplied an index.'''
458             def __init__(self, sbprocess):
459                 self.sbprocess = sbprocess
460 
461             def __len__(self):
462                 if self.sbprocess:
463                     return int(self.sbprocess.GetNumThreads())
464                 return 0
465 
466             def __getitem__(self, key):
467                 if type(key) is int and key < len(self):
468                     return self.sbprocess.GetThreadAtIndex(key)
469                 return None
470 
471         def get_threads_access_object(self):
472             '''An accessor function that returns a modules_access() object which allows lazy thread access from a lldb.SBProcess object.'''
473             return self.threads_access (self)
474 
475         def get_process_thread_list(self):
476             '''An accessor function that returns a list() that contains all threads in a lldb.SBProcess object.'''
477             threads = []
478             accessor = self.get_threads_access_object()
479             for idx in range(len(accessor)):
480                 threads.append(accessor[idx])
481             return threads
482 
483         def __iter__(self):
484             '''Iterate over all threads in a lldb.SBProcess object.'''
485             return lldb_iter(self, 'GetNumThreads', 'GetThreadAtIndex')
486 
487         def __len__(self):
488             '''Return the number of threads in a lldb.SBProcess object.'''
489             return self.GetNumThreads()
490 
491 
492         threads = property(get_process_thread_list, None, doc='''A read only property that returns a list() of lldb.SBThread objects for this process.''')
493         thread = property(get_threads_access_object, None, doc='''A read only property that returns an object that can access threads by thread index (thread = lldb.process.thread[12]).''')
494         is_alive = property(__get_is_alive__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently alive.''')
495         is_running = property(__get_is_running__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently running.''')
496         is_stopped = property(__get_is_stopped__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently stopped.''')
497         id = property(GetProcessID, None, doc='''A read only property that returns the process ID as an integer.''')
498         target = property(GetTarget, None, doc='''A read only property that an lldb object that represents the target (lldb.SBTarget) that owns this process.''')
499         num_threads = property(GetNumThreads, None, doc='''A read only property that returns the number of threads in this process as an integer.''')
500         selected_thread = property(GetSelectedThread, SetSelectedThread, doc='''A read/write property that gets/sets the currently selected thread in this process. The getter returns a lldb.SBThread object and the setter takes an lldb.SBThread object.''')
501         state = property(GetState, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eState") that represents the current state of this process (running, stopped, exited, etc.).''')
502         exit_state = property(GetExitStatus, None, doc='''A read only property that returns an exit status as an integer of this process when the process state is lldb.eStateExited.''')
503         exit_description = property(GetExitDescription, None, doc='''A read only property that returns an exit description as a string of this process when the process state is lldb.eStateExited.''')
504         broadcaster = property(GetBroadcaster, None, doc='''A read only property that an lldb object that represents the broadcaster (lldb.SBBroadcaster) for this process.''')
505     %}
506 #endif
507 
508 };
509 
510 }  // namespace lldb
511