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
9namespace lldb {
10
11#ifdef SWIGPYTHON
12%pythoncode%{
13# ==================================
14# Helper function for SBModule class
15# ==================================
16def 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
39The module is designed to be able to select a single slice of an
40executable image as it would appear on disk and during program
41execution.
42
43You can retrieve SBModule from SBSymbolContext, which in turn is available
44from SBFrame.
45
46SBModule supports symbol iteration, for example,
47
48    for symbol in module:
49        name = symbol.GetName()
50        saddr = symbol.GetStartAddress()
51        eaddr = symbol.GetEndAddress()
52
53and 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
58to test module equality.  A module also contains object file sections, namely
59SBSection.  SBModule supports section iteration through section_iter(), for
60example,
61
62    print('Number of sections: %d' % module.GetNumSections())
63    for sec in module.section_iter():
64        print(sec)
65
66And 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
75produces 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;
117class SBModule
118{
119public:
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    STRING_EXTENSION(SBModule)
348
349#ifdef SWIGPYTHON
350    %pythoncode %{
351        def __len__(self):
352            '''Return the number of symbols in a lldb.SBModule object.'''
353            return self.GetNumSymbols()
354
355        def __iter__(self):
356            '''Iterate over all symbols in a lldb.SBModule object.'''
357            return lldb_iter(self, 'GetNumSymbols', 'GetSymbolAtIndex')
358
359        def section_iter(self):
360            '''Iterate over all sections in a lldb.SBModule object.'''
361            return lldb_iter(self, 'GetNumSections', 'GetSectionAtIndex')
362
363        def compile_unit_iter(self):
364            '''Iterate over all compile units in a lldb.SBModule object.'''
365            return lldb_iter(self, 'GetNumCompileUnits', 'GetCompileUnitAtIndex')
366
367        def symbol_in_section_iter(self, section):
368            '''Given a module and its contained section, returns an iterator on the
369            symbols within the section.'''
370            for sym in self:
371                if in_range(sym, section):
372                    yield sym
373
374        class symbols_access(object):
375            re_compile_type = type(re.compile('.'))
376            '''A helper object that will lazily hand out lldb.SBSymbol objects for a module when supplied an index, name, or regular expression.'''
377            def __init__(self, sbmodule):
378                self.sbmodule = sbmodule
379
380            def __len__(self):
381                if self.sbmodule:
382                    return int(self.sbmodule.GetNumSymbols())
383                return 0
384
385            def __getitem__(self, key):
386                count = len(self)
387                if type(key) is int:
388                    if key < count:
389                        return self.sbmodule.GetSymbolAtIndex(key)
390                elif type(key) is str:
391                    matches = []
392                    sc_list = self.sbmodule.FindSymbols(key)
393                    for sc in sc_list:
394                        symbol = sc.symbol
395                        if symbol:
396                            matches.append(symbol)
397                    return matches
398                elif isinstance(key, self.re_compile_type):
399                    matches = []
400                    for idx in range(count):
401                        symbol = self.sbmodule.GetSymbolAtIndex(idx)
402                        added = False
403                        name = symbol.name
404                        if name:
405                            re_match = key.search(name)
406                            if re_match:
407                                matches.append(symbol)
408                                added = True
409                        if not added:
410                            mangled = symbol.mangled
411                            if mangled:
412                                re_match = key.search(mangled)
413                                if re_match:
414                                    matches.append(symbol)
415                    return matches
416                else:
417                    print("error: unsupported item type: %s" % type(key))
418                return None
419
420        def get_symbols_access_object(self):
421            '''An accessor function that returns a symbols_access() object which allows lazy symbol access from a lldb.SBModule object.'''
422            return self.symbols_access (self)
423
424        def get_compile_units_access_object (self):
425            '''An accessor function that returns a compile_units_access() object which allows lazy compile unit access from a lldb.SBModule object.'''
426            return self.compile_units_access (self)
427
428        def get_symbols_array(self):
429            '''An accessor function that returns a list() that contains all symbols in a lldb.SBModule object.'''
430            symbols = []
431            for idx in range(self.num_symbols):
432                symbols.append(self.GetSymbolAtIndex(idx))
433            return symbols
434
435        class sections_access(object):
436            re_compile_type = type(re.compile('.'))
437            '''A helper object that will lazily hand out lldb.SBSection objects for a module when supplied an index, name, or regular expression.'''
438            def __init__(self, sbmodule):
439                self.sbmodule = sbmodule
440
441            def __len__(self):
442                if self.sbmodule:
443                    return int(self.sbmodule.GetNumSections())
444                return 0
445
446            def __getitem__(self, key):
447                count = len(self)
448                if type(key) is int:
449                    if key < count:
450                        return self.sbmodule.GetSectionAtIndex(key)
451                elif type(key) is str:
452                    for idx in range(count):
453                        section = self.sbmodule.GetSectionAtIndex(idx)
454                        if section.name == key:
455                            return section
456                elif isinstance(key, self.re_compile_type):
457                    matches = []
458                    for idx in range(count):
459                        section = self.sbmodule.GetSectionAtIndex(idx)
460                        name = section.name
461                        if name:
462                            re_match = key.search(name)
463                            if re_match:
464                                matches.append(section)
465                    return matches
466                else:
467                    print("error: unsupported item type: %s" % type(key))
468                return None
469
470        class compile_units_access(object):
471            re_compile_type = type(re.compile('.'))
472            '''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.'''
473            def __init__(self, sbmodule):
474                self.sbmodule = sbmodule
475
476            def __len__(self):
477                if self.sbmodule:
478                    return int(self.sbmodule.GetNumCompileUnits())
479                return 0
480
481            def __getitem__(self, key):
482                count = len(self)
483                if type(key) is int:
484                    if key < count:
485                        return self.sbmodule.GetCompileUnitAtIndex(key)
486                elif type(key) is str:
487                    is_full_path = key[0] == '/'
488                    for idx in range(count):
489                        comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
490                        if is_full_path:
491                            if comp_unit.file.fullpath == key:
492                                return comp_unit
493                        else:
494                            if comp_unit.file.basename == key:
495                                return comp_unit
496                elif isinstance(key, self.re_compile_type):
497                    matches = []
498                    for idx in range(count):
499                        comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx)
500                        fullpath = comp_unit.file.fullpath
501                        if fullpath:
502                            re_match = key.search(fullpath)
503                            if re_match:
504                                matches.append(comp_unit)
505                    return matches
506                else:
507                    print("error: unsupported item type: %s" % type(key))
508                return None
509
510        def get_sections_access_object(self):
511            '''An accessor function that returns a sections_access() object which allows lazy section array access.'''
512            return self.sections_access (self)
513
514        def get_sections_array(self):
515            '''An accessor function that returns an array object that contains all sections in this module object.'''
516            if not hasattr(self, 'sections_array'):
517                self.sections_array = []
518                for idx in range(self.num_sections):
519                    self.sections_array.append(self.GetSectionAtIndex(idx))
520            return self.sections_array
521
522        def get_compile_units_array(self):
523            '''An accessor function that returns an array object that contains all compile_units in this module object.'''
524            if not hasattr(self, 'compile_units_array'):
525                self.compile_units_array = []
526                for idx in range(self.GetNumCompileUnits()):
527                    self.compile_units_array.append(self.GetCompileUnitAtIndex(idx))
528            return self.compile_units_array
529
530        symbols = property(get_symbols_array, None, doc='''A read only property that returns a list() of lldb.SBSymbol objects contained in this module.''')
531        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''')
532        sections = property(get_sections_array, None, doc='''A read only property that returns a list() of lldb.SBSection objects contained in this module.''')
533        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.''')
534        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''')
535        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.''')
536
537        def get_uuid(self):
538            return uuid.UUID (self.GetUUIDString())
539
540        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.''')
541        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.''')
542        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.''')
543        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.''')
544        addr_size = property(GetAddressByteSize, None, doc='''A read only property that returns the size in bytes of an address for this module.''')
545        triple = property(GetTriple, None, doc='''A read only property that returns the target triple (arch-vendor-os) for this module.''')
546        num_symbols = property(GetNumSymbols, None, doc='''A read only property that returns number of symbols in the module symbol table as an integer.''')
547        num_sections = property(GetNumSections, None, doc='''A read only property that returns number of sections in the module as an integer.''')
548
549    %}
550#endif
551
552};
553
554} // namespace lldb
555