1 //===-- SWIG Interface for SBModule -----------------------------*- 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 #ifdef SWIGPYTHON
12 %pythoncode%{
13 # ==================================
14 # Helper function for SBModule class
15 # ==================================
16 def in_range(symbol, section):
17     """Test whether a symbol is within the range of a section."""
18     symSA = symbol.GetStartAddress().GetFileAddress()
19     symEA = symbol.GetEndAddress().GetFileAddress()
20     secSA = section.GetFileAddress()
21     secEA = secSA + section.GetByteSize()
22 
23     if symEA != LLDB_INVALID_ADDRESS:
24         if secSA <= symSA and symEA <= secEA:
25             return True
26         else:
27             return False
28     else:
29         if secSA <= symSA and symSA < secEA:
30             return True
31         else:
32             return False
33 %}
34 #endif
35 
36 %feature("docstring",
37 "Represents an executable image and its associated object and symbol files.
38 
39 The module is designed to be able to select a single slice of an
40 executable image as it would appear on disk and during program
41 execution.
42 
43 You can retrieve SBModule from :py:class:`SBSymbolContext` , which in turn is available
44 from SBFrame.
45 
46 SBModule supports symbol iteration, for example, ::
47 
48     for symbol in module:
49         name = symbol.GetName()
50         saddr = symbol.GetStartAddress()
51         eaddr = symbol.GetEndAddress()
52 
53 and rich comparison methods which allow the API program to use, ::
54 
55     if thisModule == thatModule:
56         print('This module is the same as that module')
57 
58 to test module equality.  A module also contains object file sections, namely
59 :py:class:`SBSection` .  SBModule supports section iteration through section_iter(), for
60 example, ::
61 
62     print('Number of sections: %d' % module.GetNumSections())
63     for sec in module.section_iter():
64         print(sec)
65 
66 And to iterate the symbols within a SBSection, use symbol_in_section_iter(), ::
67 
68     # Iterates the text section and prints each symbols within each sub-section.
69     for subsec in text_sec:
70         print(INDENT + repr(subsec))
71         for sym in exe_module.symbol_in_section_iter(subsec):
72             print(INDENT2 + repr(sym))
73             print(INDENT2 + 'symbol type: %s' % symbol_type_to_str(sym.GetType()))
74 
75 produces this following output: ::
76 
77     [0x0000000100001780-0x0000000100001d5c) a.out.__TEXT.__text
78         id = {0x00000004}, name = 'mask_access(MaskAction, unsigned int)', range = [0x00000001000017c0-0x0000000100001870)
79         symbol type: code
80         id = {0x00000008}, name = 'thread_func(void*)', range = [0x0000000100001870-0x00000001000019b0)
81         symbol type: code
82         id = {0x0000000c}, name = 'main', range = [0x00000001000019b0-0x0000000100001d5c)
83         symbol type: code
84         id = {0x00000023}, name = 'start', address = 0x0000000100001780
85         symbol type: code
86     [0x0000000100001d5c-0x0000000100001da4) a.out.__TEXT.__stubs
87         id = {0x00000024}, name = '__stack_chk_fail', range = [0x0000000100001d5c-0x0000000100001d62)
88         symbol type: trampoline
89         id = {0x00000028}, name = 'exit', range = [0x0000000100001d62-0x0000000100001d68)
90         symbol type: trampoline
91         id = {0x00000029}, name = 'fflush', range = [0x0000000100001d68-0x0000000100001d6e)
92         symbol type: trampoline
93         id = {0x0000002a}, name = 'fgets', range = [0x0000000100001d6e-0x0000000100001d74)
94         symbol type: trampoline
95         id = {0x0000002b}, name = 'printf', range = [0x0000000100001d74-0x0000000100001d7a)
96         symbol type: trampoline
97         id = {0x0000002c}, name = 'pthread_create', range = [0x0000000100001d7a-0x0000000100001d80)
98         symbol type: trampoline
99         id = {0x0000002d}, name = 'pthread_join', range = [0x0000000100001d80-0x0000000100001d86)
100         symbol type: trampoline
101         id = {0x0000002e}, name = 'pthread_mutex_lock', range = [0x0000000100001d86-0x0000000100001d8c)
102         symbol type: trampoline
103         id = {0x0000002f}, name = 'pthread_mutex_unlock', range = [0x0000000100001d8c-0x0000000100001d92)
104         symbol type: trampoline
105         id = {0x00000030}, name = 'rand', range = [0x0000000100001d92-0x0000000100001d98)
106         symbol type: trampoline
107         id = {0x00000031}, name = 'strtoul', range = [0x0000000100001d98-0x0000000100001d9e)
108         symbol type: trampoline
109         id = {0x00000032}, name = 'usleep', range = [0x0000000100001d9e-0x0000000100001da4)
110         symbol type: trampoline
111     [0x0000000100001da4-0x0000000100001e2c) a.out.__TEXT.__stub_helper
112     [0x0000000100001e2c-0x0000000100001f10) a.out.__TEXT.__cstring
113     [0x0000000100001f10-0x0000000100001f68) a.out.__TEXT.__unwind_info
114     [0x0000000100001f68-0x0000000100001ff8) a.out.__TEXT.__eh_frame
115 "
116 ) SBModule;
117 class SBModule
118 {
119 public:
120 
121     SBModule ();
122 
123     SBModule (const lldb::SBModule &rhs);
124 
125     SBModule (const lldb::SBModuleSpec &module_spec);
126 
127     SBModule (lldb::SBProcess &process,
128               lldb::addr_t header_addr);
129 
130     ~SBModule ();
131 
132     bool
133     IsValid () const;
134 
135     explicit operator bool() const;
136 
137     void
138     Clear();
139 
140     %feature("docstring", "Check if the module is file backed.
141     @return
142         True, if the module is backed by an object file on disk.
143         False, if the module is backed by an object file in memory.") IsFileBacked;
144     bool
145     IsFileBacked() const;
146 
147     %feature("docstring", "
148     Get const accessor for the module file specification.
149 
150     This function returns the file for the module on the host system
151     that is running LLDB. This can differ from the path on the
152     platform since we might be doing remote debugging.
153 
154     @return
155         A const reference to the file specification object.") GetFileSpec;
156     lldb::SBFileSpec
157     GetFileSpec () const;
158 
159     %feature("docstring", "
160     Get accessor for the module platform file specification.
161 
162     Platform file refers to the path of the module as it is known on
163     the remote system on which it is being debugged. For local
164     debugging this is always the same as Module::GetFileSpec(). But
165     remote debugging might mention a file '/usr/lib/liba.dylib'
166     which might be locally downloaded and cached. In this case the
167     platform file could be something like:
168     '/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib'
169     The file could also be cached in a local developer kit directory.
170 
171     @return
172         A const reference to the file specification object.") GetPlatformFileSpec;
173     lldb::SBFileSpec
174     GetPlatformFileSpec () const;
175 
176     bool
177     SetPlatformFileSpec (const lldb::SBFileSpec &platform_file);
178 
179     lldb::SBFileSpec
180     GetRemoteInstallFileSpec ();
181 
182     bool
183     SetRemoteInstallFileSpec (lldb::SBFileSpec &file);
184 
185     %feature("docstring", "Returns the UUID of the module as a Python string."
186     ) GetUUIDString;
187     const char *
188     GetUUIDString () const;
189 
190     bool operator==(const lldb::SBModule &rhs) const;
191 
192     bool operator!=(const lldb::SBModule &rhs) const;
193 
194     lldb::SBSection
195     FindSection (const char *sect_name);
196 
197     lldb::SBAddress
198     ResolveFileAddress (lldb::addr_t vm_addr);
199 
200     lldb::SBSymbolContext
201     ResolveSymbolContextForAddress (const lldb::SBAddress& addr,
202                                     uint32_t resolve_scope);
203 
204     bool
205     GetDescription (lldb::SBStream &description);
206 
207     uint32_t
208     GetNumCompileUnits();
209 
210     lldb::SBCompileUnit
211     GetCompileUnitAtIndex (uint32_t);
212 
213     %feature("docstring", "
214     Find compile units related to this module and passed source
215     file.
216 
217     @param[in] sb_file_spec
218         A :py:class:`SBFileSpec` object that contains source file
219         specification.
220 
221     @return
222         A :py:class:`SBSymbolContextList` that gets filled in with all of
223         the symbol contexts for all the matches.") FindCompileUnits;
224     lldb::SBSymbolContextList
225     FindCompileUnits (const lldb::SBFileSpec &sb_file_spec);
226 
227     size_t
228     GetNumSymbols ();
229 
230     lldb::SBSymbol
231     GetSymbolAtIndex (size_t idx);
232 
233     lldb::SBSymbol
234     FindSymbol (const char *name,
235                 lldb::SymbolType type = eSymbolTypeAny);
236 
237     lldb::SBSymbolContextList
238     FindSymbols (const char *name,
239                  lldb::SymbolType type = eSymbolTypeAny);
240 
241 
242     size_t
243     GetNumSections ();
244 
245     lldb::SBSection
246     GetSectionAtIndex (size_t idx);
247 
248 
249     %feature("docstring", "
250     Find functions by name.
251 
252     @param[in] name
253         The name of the function we are looking for.
254 
255     @param[in] name_type_mask
256         A logical OR of one or more FunctionNameType enum bits that
257         indicate what kind of names should be used when doing the
258         lookup. Bits include fully qualified names, base names,
259         C++ methods, or ObjC selectors.
260         See FunctionNameType for more details.
261 
262     @return
263         A symbol context list that gets filled in with all of the
264         matches.") FindFunctions;
265     lldb::SBSymbolContextList
266     FindFunctions (const char *name,
267                    uint32_t name_type_mask = lldb::eFunctionNameTypeAny);
268 
269     lldb::SBType
270     FindFirstType (const char* name);
271 
272     lldb::SBTypeList
273     FindTypes (const char* type);
274 
275     lldb::SBType
276     GetTypeByID (lldb::user_id_t uid);
277 
278     lldb::SBType
279     GetBasicType(lldb::BasicType type);
280 
281     %feature("docstring", "
282     Get all types matching type_mask from debug info in this
283     module.
284 
285     @param[in] type_mask
286         A bitfield that consists of one or more bits logically OR'ed
287         together from the lldb::TypeClass enumeration. This allows
288         you to request only structure types, or only class, struct
289         and union types. Passing in lldb::eTypeClassAny will return
290         all types found in the debug information for this module.
291 
292     @return
293         A list of types in this module that match type_mask") GetTypes;
294     lldb::SBTypeList
295     GetTypes (uint32_t type_mask = lldb::eTypeClassAny);
296 
297     %feature("docstring", "
298     Find global and static variables by name.
299 
300     @param[in] target
301         A valid SBTarget instance representing the debuggee.
302 
303     @param[in] name
304         The name of the global or static variable we are looking
305         for.
306 
307     @param[in] max_matches
308         Allow the number of matches to be limited to max_matches.
309 
310     @return
311         A list of matched variables in an SBValueList.") FindGlobalVariables;
312     lldb::SBValueList
313     FindGlobalVariables (lldb::SBTarget &target,
314                          const char *name,
315                          uint32_t max_matches);
316 
317     %feature("docstring", "
318     Find the first global (or static) variable by name.
319 
320     @param[in] target
321         A valid SBTarget instance representing the debuggee.
322 
323     @param[in] name
324         The name of the global or static variable we are looking
325         for.
326 
327     @return
328         An SBValue that gets filled in with the found variable (if any).") FindFirstGlobalVariable;
329     lldb::SBValue
330     FindFirstGlobalVariable (lldb::SBTarget &target, const char *name);
331 
332     lldb::ByteOrder
333     GetByteOrder ();
334 
335     uint32_t
336     GetAddressByteSize();
337 
338     const char *
339     GetTriple ();
340 
341     uint32_t
342     GetVersion (uint32_t *versions,
343                 uint32_t num_versions);
344 
345     lldb::SBFileSpec
346     GetSymbolFileSpec() const;
347 
348     lldb::SBAddress
349     GetObjectFileHeaderAddress() const;
350 
351     lldb::SBAddress
352     GetObjectFileEntryPointAddress() const;
353 
354     %feature("docstring", "
355     Returns the number of modules in the module cache. This is an
356     implementation detail exposed for testing and should not be relied upon.
357 
358     @return
359         The number of modules in the module cache.") GetNumberAllocatedModules;
360     static uint32_t
361     GetNumberAllocatedModules();
362 
363     %feature("docstring", "
364     Removes all modules which are no longer needed by any part of LLDB from
365     the module cache.
366 
367     This is an implementation detail exposed for testing and should not be
368     relied upon. Use SBDebugger::MemoryPressureDetected instead to reduce
369     LLDB's memory consumption during execution.
370     ") GarbageCollectAllocatedModules;
371     static void
372     GarbageCollectAllocatedModules();
373 
374     STRING_EXTENSION(SBModule)
375 
376 #ifdef SWIGPYTHON
377     %pythoncode %{
378         def __len__(self):
379             '''Return the number of symbols in a lldb.SBModule object.'''
380             return self.GetNumSymbols()
381 
382         def __iter__(self):
383             '''Iterate over all symbols in a lldb.SBModule object.'''
384             return lldb_iter(self, 'GetNumSymbols', 'GetSymbolAtIndex')
385 
386         def section_iter(self):
387             '''Iterate over all sections in a lldb.SBModule object.'''
388             return lldb_iter(self, 'GetNumSections', 'GetSectionAtIndex')
389 
390         def compile_unit_iter(self):
391             '''Iterate over all compile units in a lldb.SBModule object.'''
392             return lldb_iter(self, 'GetNumCompileUnits', 'GetCompileUnitAtIndex')
393 
394         def symbol_in_section_iter(self, section):
395             '''Given a module and its contained section, returns an iterator on the
396             symbols within the section.'''
397             for sym in self:
398                 if in_range(sym, section):
399                     yield sym
400 
401         class symbols_access(object):
402             re_compile_type = type(re.compile('.'))
403             '''A helper object that will lazily hand out lldb.SBSymbol objects for a module when supplied an index, name, or regular expression.'''
404             def __init__(self, sbmodule):
405                 self.sbmodule = sbmodule
406 
407             def __len__(self):
408                 if self.sbmodule:
409                     return int(self.sbmodule.GetNumSymbols())
410                 return 0
411 
412             def __getitem__(self, key):
413                 count = len(self)
414                 if type(key) is int:
415                     if key < count:
416                         return self.sbmodule.GetSymbolAtIndex(key)
417                 elif type(key) is str:
418                     matches = []
419                     sc_list = self.sbmodule.FindSymbols(key)
420                     for sc in sc_list:
421                         symbol = sc.symbol
422                         if symbol:
423                             matches.append(symbol)
424                     return matches
425                 elif isinstance(key, self.re_compile_type):
426                     matches = []
427                     for idx in range(count):
428                         symbol = self.sbmodule.GetSymbolAtIndex(idx)
429                         added = False
430                         name = symbol.name
431                         if name:
432                             re_match = key.search(name)
433                             if re_match:
434                                 matches.append(symbol)
435                                 added = True
436                         if not added:
437                             mangled = symbol.mangled
438                             if mangled:
439                                 re_match = key.search(mangled)
440                                 if re_match:
441                                     matches.append(symbol)
442                     return matches
443                 else:
444                     print("error: unsupported item type: %s" % type(key))
445                 return None
446 
447         def get_symbols_access_object(self):
448             '''An accessor function that returns a symbols_access() object which allows lazy symbol access from a lldb.SBModule object.'''
449             return self.symbols_access (self)
450 
451         def get_compile_units_access_object (self):
452             '''An accessor function that returns a compile_units_access() object which allows lazy compile unit access from a lldb.SBModule object.'''
453             return self.compile_units_access (self)
454 
455         def get_symbols_array(self):
456             '''An accessor function that returns a list() that contains all symbols in a lldb.SBModule object.'''
457             symbols = []
458             for idx in range(self.num_symbols):
459                 symbols.append(self.GetSymbolAtIndex(idx))
460             return symbols
461 
462         class sections_access(object):
463             re_compile_type = type(re.compile('.'))
464             '''A helper object that will lazily hand out lldb.SBSection objects for a module when supplied an index, name, or regular expression.'''
465             def __init__(self, sbmodule):
466                 self.sbmodule = sbmodule
467 
468             def __len__(self):
469                 if self.sbmodule:
470                     return int(self.sbmodule.GetNumSections())
471                 return 0
472 
473             def __getitem__(self, key):
474                 count = len(self)
475                 if type(key) is int:
476                     if key < count:
477                         return self.sbmodule.GetSectionAtIndex(key)
478                 elif type(key) is str:
479                     for idx in range(count):
480                         section = self.sbmodule.GetSectionAtIndex(idx)
481                         if section.name == key:
482                             return section
483                 elif isinstance(key, self.re_compile_type):
484                     matches = []
485                     for idx in range(count):
486                         section = self.sbmodule.GetSectionAtIndex(idx)
487                         name = section.name
488                         if name:
489                             re_match = key.search(name)
490                             if re_match:
491                                 matches.append(section)
492                     return matches
493                 else:
494                     print("error: unsupported item type: %s" % type(key))
495                 return None
496 
497         class compile_units_access(object):
498             re_compile_type = type(re.compile('.'))
499             '''A helper object that will lazily hand out lldb.SBCompileUnit objects for a module when supplied an index, full or partial path, or regular expression.'''
500             def __init__(self, sbmodule):
501                 self.sbmodule = sbmodule
502 
503             def __len__(self):
504                 if self.sbmodule:
505                     return int(self.sbmodule.GetNumCompileUnits())
506                 return 0
507 
508             def __getitem__(self, key):
509                 count = len(self)
510                 if type(key) is int:
511                     if key < count:
512                         return self.sbmodule.GetCompileUnitAtIndex(key)
513                 elif type(key) is str:
514                     is_full_path = key[0] == '/'
515                     for idx in range(count):
516                         comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
517                         if is_full_path:
518                             if comp_unit.file.fullpath == key:
519                                 return comp_unit
520                         else:
521                             if comp_unit.file.basename == key:
522                                 return comp_unit
523                 elif isinstance(key, self.re_compile_type):
524                     matches = []
525                     for idx in range(count):
526                         comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
527                         fullpath = comp_unit.file.fullpath
528                         if fullpath:
529                             re_match = key.search(fullpath)
530                             if re_match:
531                                 matches.append(comp_unit)
532                     return matches
533                 else:
534                     print("error: unsupported item type: %s" % type(key))
535                 return None
536 
537         def get_sections_access_object(self):
538             '''An accessor function that returns a sections_access() object which allows lazy section array access.'''
539             return self.sections_access (self)
540 
541         def get_sections_array(self):
542             '''An accessor function that returns an array object that contains all sections in this module object.'''
543             if not hasattr(self, 'sections_array'):
544                 self.sections_array = []
545                 for idx in range(self.num_sections):
546                     self.sections_array.append(self.GetSectionAtIndex(idx))
547             return self.sections_array
548 
549         def get_compile_units_array(self):
550             '''An accessor function that returns an array object that contains all compile_units in this module object.'''
551             if not hasattr(self, 'compile_units_array'):
552                 self.compile_units_array = []
553                 for idx in range(self.GetNumCompileUnits()):
554                     self.compile_units_array.append(self.GetCompileUnitAtIndex(idx))
555             return self.compile_units_array
556 
557         symbols = property(get_symbols_array, None, doc='''A read only property that returns a list() of lldb.SBSymbol objects contained in this module.''')
558         symbol = property(get_symbols_access_object, None, doc='''A read only property that can be used to access symbols by index ("symbol = module.symbol[0]"), name ("symbols = module.symbol['main']"), or using a regular expression ("symbols = module.symbol[re.compile(...)]"). The return value is a single lldb.SBSymbol object for array access, and a list() of lldb.SBSymbol objects for name and regular expression access''')
559         sections = property(get_sections_array, None, doc='''A read only property that returns a list() of lldb.SBSection objects contained in this module.''')
560         compile_units = property(get_compile_units_array, None, doc='''A read only property that returns a list() of lldb.SBCompileUnit objects contained in this module.''')
561         section = property(get_sections_access_object, None, doc='''A read only property that can be used to access symbols by index ("section = module.section[0]"), name ("sections = module.section[\'main\']"), or using a regular expression ("sections = module.section[re.compile(...)]"). The return value is a single lldb.SBSection object for array access, and a list() of lldb.SBSection objects for name and regular expression access''')
562         section = property(get_sections_access_object, None, doc='''A read only property that can be used to access compile units by index ("compile_unit = module.compile_unit[0]"), name ("compile_unit = module.compile_unit[\'main.cpp\']"), or using a regular expression ("compile_unit = module.compile_unit[re.compile(...)]"). The return value is a single lldb.SBCompileUnit object for array access or by full or partial path, and a list() of lldb.SBCompileUnit objects regular expressions.''')
563 
564         def get_uuid(self):
565             return uuid.UUID (self.GetUUIDString())
566 
567         uuid = property(get_uuid, None, doc='''A read only property that returns a standard python uuid.UUID object that represents the UUID of this module.''')
568         file = property(GetFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this object file for this module as it is represented where it is being debugged.''')
569         platform_file = property(GetPlatformFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this object file for this module as it is represented on the current host system.''')
570         byte_order = property(GetByteOrder, None, doc='''A read only property that returns an lldb enumeration value (lldb.eByteOrderLittle, lldb.eByteOrderBig, lldb.eByteOrderInvalid) that represents the byte order for this module.''')
571         addr_size = property(GetAddressByteSize, None, doc='''A read only property that returns the size in bytes of an address for this module.''')
572         triple = property(GetTriple, None, doc='''A read only property that returns the target triple (arch-vendor-os) for this module.''')
573         num_symbols = property(GetNumSymbols, None, doc='''A read only property that returns number of symbols in the module symbol table as an integer.''')
574         num_sections = property(GetNumSections, None, doc='''A read only property that returns number of sections in the module as an integer.''')
575 
576     %}
577 #endif
578 
579 };
580 
581 } // namespace lldb
582