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 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 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", "
141     Get const accessor for the module file specification.
142 
143     This function returns the file for the module on the host system
144     that is running LLDB. This can differ from the path on the
145     platform since we might be doing remote debugging.
146 
147     @return
148         A const reference to the file specification object.") GetFileSpec;
149     lldb::SBFileSpec
150     GetFileSpec () const;
151 
152     %feature("docstring", "
153     Get accessor for the module platform file specification.
154 
155     Platform file refers to the path of the module as it is known on
156     the remote system on which it is being debugged. For local
157     debugging this is always the same as Module::GetFileSpec(). But
158     remote debugging might mention a file '/usr/lib/liba.dylib'
159     which might be locally downloaded and cached. In this case the
160     platform file could be something like:
161     '/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib'
162     The file could also be cached in a local developer kit directory.
163 
164     @return
165         A const reference to the file specification object.") GetPlatformFileSpec;
166     lldb::SBFileSpec
167     GetPlatformFileSpec () const;
168 
169     bool
170     SetPlatformFileSpec (const lldb::SBFileSpec &platform_file);
171 
172     lldb::SBFileSpec
173     GetRemoteInstallFileSpec ();
174 
175     bool
176     SetRemoteInstallFileSpec (lldb::SBFileSpec &file);
177 
178     %feature("docstring", "Returns the UUID of the module as a Python string."
179     ) GetUUIDString;
180     const char *
181     GetUUIDString () const;
182 
183     bool operator==(const lldb::SBModule &rhs) const;
184 
185     bool operator!=(const lldb::SBModule &rhs) const;
186 
187     lldb::SBSection
188     FindSection (const char *sect_name);
189 
190     lldb::SBAddress
191     ResolveFileAddress (lldb::addr_t vm_addr);
192 
193     lldb::SBSymbolContext
194     ResolveSymbolContextForAddress (const lldb::SBAddress& addr,
195                                     uint32_t resolve_scope);
196 
197     bool
198     GetDescription (lldb::SBStream &description);
199 
200     uint32_t
201     GetNumCompileUnits();
202 
203     lldb::SBCompileUnit
204     GetCompileUnitAtIndex (uint32_t);
205 
206     %feature("docstring", "
207     Find compile units related to *this module and passed source
208     file.
209 
210     @param[in] sb_file_spec
211         A lldb::SBFileSpec object that contains source file
212         specification.
213 
214     @return
215         A lldb::SBSymbolContextList that gets filled in with all of
216         the symbol contexts for all the matches.") FindCompileUnits;
217     lldb::SBSymbolContextList
218     FindCompileUnits (const lldb::SBFileSpec &sb_file_spec);
219 
220     size_t
221     GetNumSymbols ();
222 
223     lldb::SBSymbol
224     GetSymbolAtIndex (size_t idx);
225 
226     lldb::SBSymbol
227     FindSymbol (const char *name,
228                 lldb::SymbolType type = eSymbolTypeAny);
229 
230     lldb::SBSymbolContextList
231     FindSymbols (const char *name,
232                  lldb::SymbolType type = eSymbolTypeAny);
233 
234 
235     size_t
236     GetNumSections ();
237 
238     lldb::SBSection
239     GetSectionAtIndex (size_t idx);
240 
241 
242     %feature("docstring", "
243     Find functions by name.
244 
245     @param[in] name
246         The name of the function we are looking for.
247 
248     @param[in] name_type_mask
249         A logical OR of one or more FunctionNameType enum bits that
250         indicate what kind of names should be used when doing the
251         lookup. Bits include fully qualified names, base names,
252         C++ methods, or ObjC selectors.
253         See FunctionNameType for more details.
254 
255     @return
256         A symbol context list that gets filled in with all of the
257         matches.") FindFunctions;
258     lldb::SBSymbolContextList
259     FindFunctions (const char *name,
260                    uint32_t name_type_mask = lldb::eFunctionNameTypeAny);
261 
262     lldb::SBType
263     FindFirstType (const char* name);
264 
265     lldb::SBTypeList
266     FindTypes (const char* type);
267 
268     lldb::SBType
269     GetTypeByID (lldb::user_id_t uid);
270 
271     lldb::SBType
272     GetBasicType(lldb::BasicType type);
273 
274     %feature("docstring", "
275     Get all types matching type_mask from debug info in this
276     module.
277 
278     @param[in] type_mask
279         A bitfield that consists of one or more bits logically OR'ed
280         together from the lldb::TypeClass enumeration. This allows
281         you to request only structure types, or only class, struct
282         and union types. Passing in lldb::eTypeClassAny will return
283         all types found in the debug information for this module.
284 
285     @return
286         A list of types in this module that match type_mask") GetTypes;
287     lldb::SBTypeList
288     GetTypes (uint32_t type_mask = lldb::eTypeClassAny);
289 
290     %feature("docstring", "
291     Find global and static variables by name.
292 
293     @param[in] target
294         A valid SBTarget instance representing the debuggee.
295 
296     @param[in] name
297         The name of the global or static variable we are looking
298         for.
299 
300     @param[in] max_matches
301         Allow the number of matches to be limited to max_matches.
302 
303     @return
304         A list of matched variables in an SBValueList.") FindGlobalVariables;
305     lldb::SBValueList
306     FindGlobalVariables (lldb::SBTarget &target,
307                          const char *name,
308                          uint32_t max_matches);
309 
310     %feature("docstring", "
311     Find the first global (or static) variable by name.
312 
313     @param[in] target
314         A valid SBTarget instance representing the debuggee.
315 
316     @param[in] name
317         The name of the global or static variable we are looking
318         for.
319 
320     @return
321         An SBValue that gets filled in with the found variable (if any).") FindFirstGlobalVariable;
322     lldb::SBValue
323     FindFirstGlobalVariable (lldb::SBTarget &target, const char *name);
324 
325     lldb::ByteOrder
326     GetByteOrder ();
327 
328     uint32_t
329     GetAddressByteSize();
330 
331     const char *
332     GetTriple ();
333 
334     uint32_t
335     GetVersion (uint32_t *versions,
336                 uint32_t num_versions);
337 
338     lldb::SBFileSpec
339     GetSymbolFileSpec() const;
340 
341     lldb::SBAddress
342     GetObjectFileHeaderAddress() const;
343 
344     lldb::SBAddress
345     GetObjectFileEntryPointAddress() const;
346 
347     %feature("docstring", "
348     Returns the number of modules in the module cache. This is an
349     implementation detail exposed for testing and should not be relied upon.
350 
351     @return
352         The number of modules in the module cache.") GetNumberAllocatedModules;
353     static uint32_t
354     GetNumberAllocatedModules();
355 
356     %feature("docstring", "
357     Removes all modules which are no longer needed by any part of LLDB from
358     the module cache.
359 
360     This is an implementation detail exposed for testing and should not be
361     relied upon. Use SBDebugger::MemoryPressureDetected instead to reduce
362     LLDB's memory consumption during execution.
363     ") GarbageCollectAllocatedModules;
364     static void
365     GarbageCollectAllocatedModules();
366 
367     STRING_EXTENSION(SBModule)
368 
369 #ifdef SWIGPYTHON
370     %pythoncode %{
371         def __len__(self):
372             '''Return the number of symbols in a lldb.SBModule object.'''
373             return self.GetNumSymbols()
374 
375         def __iter__(self):
376             '''Iterate over all symbols in a lldb.SBModule object.'''
377             return lldb_iter(self, 'GetNumSymbols', 'GetSymbolAtIndex')
378 
379         def section_iter(self):
380             '''Iterate over all sections in a lldb.SBModule object.'''
381             return lldb_iter(self, 'GetNumSections', 'GetSectionAtIndex')
382 
383         def compile_unit_iter(self):
384             '''Iterate over all compile units in a lldb.SBModule object.'''
385             return lldb_iter(self, 'GetNumCompileUnits', 'GetCompileUnitAtIndex')
386 
387         def symbol_in_section_iter(self, section):
388             '''Given a module and its contained section, returns an iterator on the
389             symbols within the section.'''
390             for sym in self:
391                 if in_range(sym, section):
392                     yield sym
393 
394         class symbols_access(object):
395             re_compile_type = type(re.compile('.'))
396             '''A helper object that will lazily hand out lldb.SBSymbol objects for a module when supplied an index, name, or regular expression.'''
397             def __init__(self, sbmodule):
398                 self.sbmodule = sbmodule
399 
400             def __len__(self):
401                 if self.sbmodule:
402                     return int(self.sbmodule.GetNumSymbols())
403                 return 0
404 
405             def __getitem__(self, key):
406                 count = len(self)
407                 if type(key) is int:
408                     if key < count:
409                         return self.sbmodule.GetSymbolAtIndex(key)
410                 elif type(key) is str:
411                     matches = []
412                     sc_list = self.sbmodule.FindSymbols(key)
413                     for sc in sc_list:
414                         symbol = sc.symbol
415                         if symbol:
416                             matches.append(symbol)
417                     return matches
418                 elif isinstance(key, self.re_compile_type):
419                     matches = []
420                     for idx in range(count):
421                         symbol = self.sbmodule.GetSymbolAtIndex(idx)
422                         added = False
423                         name = symbol.name
424                         if name:
425                             re_match = key.search(name)
426                             if re_match:
427                                 matches.append(symbol)
428                                 added = True
429                         if not added:
430                             mangled = symbol.mangled
431                             if mangled:
432                                 re_match = key.search(mangled)
433                                 if re_match:
434                                     matches.append(symbol)
435                     return matches
436                 else:
437                     print("error: unsupported item type: %s" % type(key))
438                 return None
439 
440         def get_symbols_access_object(self):
441             '''An accessor function that returns a symbols_access() object which allows lazy symbol access from a lldb.SBModule object.'''
442             return self.symbols_access (self)
443 
444         def get_compile_units_access_object (self):
445             '''An accessor function that returns a compile_units_access() object which allows lazy compile unit access from a lldb.SBModule object.'''
446             return self.compile_units_access (self)
447 
448         def get_symbols_array(self):
449             '''An accessor function that returns a list() that contains all symbols in a lldb.SBModule object.'''
450             symbols = []
451             for idx in range(self.num_symbols):
452                 symbols.append(self.GetSymbolAtIndex(idx))
453             return symbols
454 
455         class sections_access(object):
456             re_compile_type = type(re.compile('.'))
457             '''A helper object that will lazily hand out lldb.SBSection objects for a module when supplied an index, name, or regular expression.'''
458             def __init__(self, sbmodule):
459                 self.sbmodule = sbmodule
460 
461             def __len__(self):
462                 if self.sbmodule:
463                     return int(self.sbmodule.GetNumSections())
464                 return 0
465 
466             def __getitem__(self, key):
467                 count = len(self)
468                 if type(key) is int:
469                     if key < count:
470                         return self.sbmodule.GetSectionAtIndex(key)
471                 elif type(key) is str:
472                     for idx in range(count):
473                         section = self.sbmodule.GetSectionAtIndex(idx)
474                         if section.name == key:
475                             return section
476                 elif isinstance(key, self.re_compile_type):
477                     matches = []
478                     for idx in range(count):
479                         section = self.sbmodule.GetSectionAtIndex(idx)
480                         name = section.name
481                         if name:
482                             re_match = key.search(name)
483                             if re_match:
484                                 matches.append(section)
485                     return matches
486                 else:
487                     print("error: unsupported item type: %s" % type(key))
488                 return None
489 
490         class compile_units_access(object):
491             re_compile_type = type(re.compile('.'))
492             '''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.'''
493             def __init__(self, sbmodule):
494                 self.sbmodule = sbmodule
495 
496             def __len__(self):
497                 if self.sbmodule:
498                     return int(self.sbmodule.GetNumCompileUnits())
499                 return 0
500 
501             def __getitem__(self, key):
502                 count = len(self)
503                 if type(key) is int:
504                     if key < count:
505                         return self.sbmodule.GetCompileUnitAtIndex(key)
506                 elif type(key) is str:
507                     is_full_path = key[0] == '/'
508                     for idx in range(count):
509                         comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
510                         if is_full_path:
511                             if comp_unit.file.fullpath == key:
512                                 return comp_unit
513                         else:
514                             if comp_unit.file.basename == key:
515                                 return comp_unit
516                 elif isinstance(key, self.re_compile_type):
517                     matches = []
518                     for idx in range(count):
519                         comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
520                         fullpath = comp_unit.file.fullpath
521                         if fullpath:
522                             re_match = key.search(fullpath)
523                             if re_match:
524                                 matches.append(comp_unit)
525                     return matches
526                 else:
527                     print("error: unsupported item type: %s" % type(key))
528                 return None
529 
530         def get_sections_access_object(self):
531             '''An accessor function that returns a sections_access() object which allows lazy section array access.'''
532             return self.sections_access (self)
533 
534         def get_sections_array(self):
535             '''An accessor function that returns an array object that contains all sections in this module object.'''
536             if not hasattr(self, 'sections_array'):
537                 self.sections_array = []
538                 for idx in range(self.num_sections):
539                     self.sections_array.append(self.GetSectionAtIndex(idx))
540             return self.sections_array
541 
542         def get_compile_units_array(self):
543             '''An accessor function that returns an array object that contains all compile_units in this module object.'''
544             if not hasattr(self, 'compile_units_array'):
545                 self.compile_units_array = []
546                 for idx in range(self.GetNumCompileUnits()):
547                     self.compile_units_array.append(self.GetCompileUnitAtIndex(idx))
548             return self.compile_units_array
549 
550         symbols = property(get_symbols_array, None, doc='''A read only property that returns a list() of lldb.SBSymbol objects contained in this module.''')
551         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''')
552         sections = property(get_sections_array, None, doc='''A read only property that returns a list() of lldb.SBSection objects contained in this module.''')
553         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.''')
554         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''')
555         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.''')
556 
557         def get_uuid(self):
558             return uuid.UUID (self.GetUUIDString())
559 
560         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.''')
561         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.''')
562         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.''')
563         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.''')
564         addr_size = property(GetAddressByteSize, None, doc='''A read only property that returns the size in bytes of an address for this module.''')
565         triple = property(GetTriple, None, doc='''A read only property that returns the target triple (arch-vendor-os) for this module.''')
566         num_symbols = property(GetNumSymbols, None, doc='''A read only property that returns number of symbols in the module symbol table as an integer.''')
567         num_sections = property(GetNumSections, None, doc='''A read only property that returns number of sections in the module as an integer.''')
568 
569     %}
570 #endif
571 
572 };
573 
574 } // namespace lldb
575