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