Debian Codegraph @

Tools/build/smelly.py

raw
1 #!/usr/bin/env python
2 # Script checking that all symbols exported by libpython start with Py or _Py
3
4 import os.path
5 import subprocess
6 import sys
7 import sysconfig
8
9
10 ALLOWED_PREFIXES = ('Py', '_Py')
11 if sys.platform == 'darwin':
12 ALLOWED_PREFIXES += ('__Py',)
13
14 # mimalloc doesn't use static, but it's symbols are not exported
15 # from the shared library. They do show up in the static library
16 # before its linked into an executable.
17 ALLOWED_STATIC_PREFIXES = ('mi_', '_mi_')
18
19 # "Legacy": some old symbols are prefixed by "PY_".
20 EXCEPTIONS = frozenset({
21 'PY_TIMEOUT_MAX',
22 })
23
24 IGNORED_EXTENSION = "_ctypes_test"
25 # Ignore constructor and destructor functions
26 IGNORED_SYMBOLS = {'_init', '_fini'}
27
28
29 def is_local_symbol_type(symtype):
30 # Ignore local symbols.
31
32 # If lowercase, the symbol is usually local; if uppercase, the symbol
33 # is global (external). There are however a few lowercase symbols that
34 # are shown for special global symbols ("u", "v" and "w").
35 if symtype.islower() and symtype not in "uvw":
36 return True
37
38 # Ignore the initialized data section (d and D) and the BSS data
39 # section. For example, ignore "__bss_start (type: B)"
40 # and "_edata (type: D)".
41 if symtype in "bBdD":
42 return True
43
44 return False
45
46
47 def get_exported_symbols(library, dynamic=False):
48 print(f"Check that {library} only exports symbols starting with Py or _Py")
49
50 # Only look at dynamic symbols
51 args = ['nm', '--no-sort']
52 if dynamic:
53 args.append('--dynamic')
54 args.append(library)
55 print("+ %s" % ' '.join(args))
56 proc = subprocess.run(args, stdout=subprocess.PIPE, universal_newlines=True)
57 if proc.returncode:
58 sys.stdout.write(proc.stdout)
59 sys.exit(proc.returncode)
60
61 stdout = proc.stdout.rstrip()
62 if not stdout:
63 raise Exception("command output is empty")
64 return stdout
65
66
67 def get_smelly_symbols(stdout, dynamic=False):
68 smelly_symbols = []
69 python_symbols = []
70 local_symbols = []
71
72 for line in stdout.splitlines():
73 # Split line '0000000000001b80 D PyTextIOWrapper_Type'
74 if not line:
75 continue
76
77 parts = line.split(maxsplit=2)
78 if len(parts) < 3:
79 continue
80
81 symtype = parts[1].strip()
82 symbol = parts[-1]
83 result = '%s (type: %s)' % (symbol, symtype)
84
85 if (symbol.startswith(ALLOWED_PREFIXES) or
86 symbol in EXCEPTIONS or
87 (not dynamic and symbol.startswith(ALLOWED_STATIC_PREFIXES))):
88 python_symbols.append(result)
89 continue
90
91 if is_local_symbol_type(symtype):
92 local_symbols.append(result)
93 elif symbol in IGNORED_SYMBOLS:
94 local_symbols.append(result)
95 else:
96 smelly_symbols.append(result)
97
98 if local_symbols:
99 print(f"Ignore {len(local_symbols)} local symbols")
100 return smelly_symbols, python_symbols
101
102
103 def check_library(library, dynamic=False):
104 nm_output = get_exported_symbols(library, dynamic)
105 smelly_symbols, python_symbols = get_smelly_symbols(nm_output, dynamic)
106
107 if not smelly_symbols:
108 print(f"OK: no smelly symbol found ({len(python_symbols)} Python symbols)")
109 return 0
110
111 print()
112 smelly_symbols.sort()
113 for symbol in smelly_symbols:
114 print("Smelly symbol: %s" % symbol)
115
116 print()
117 print("ERROR: Found %s smelly symbols!" % len(smelly_symbols))
118 return len(smelly_symbols)
119
120
121 def check_extensions():
122 print(__file__)
123 # This assumes pybuilddir.txt is in same directory as pyconfig.h.
124 # In the case of out-of-tree builds, we can't assume pybuilddir.txt is
125 # in the source folder.
126 config_dir = os.path.dirname(sysconfig.get_config_h_filename())
127 filename = os.path.join(config_dir, "pybuilddir.txt")
128 try:
129 with open(filename, encoding="utf-8") as fp:
130 pybuilddir = fp.readline()
131 except FileNotFoundError:
132 print(f"Cannot check extensions because {filename} does not exist")
133 return True
134
135 print(f"Check extension modules from {pybuilddir} directory")
136 builddir = os.path.join(config_dir, pybuilddir)
137 nsymbol = 0
138 for name in os.listdir(builddir):
139 if not name.endswith(".so"):
140 continue
141 if IGNORED_EXTENSION in name:
142 print()
143 print(f"Ignore extension: {name}")
144 continue
145
146 print()
147 filename = os.path.join(builddir, name)
148 nsymbol += check_library(filename, dynamic=True)
149
150 return nsymbol
151
152
153 def main():
154 nsymbol = 0
155
156 # static library
157 LIBRARY = sysconfig.get_config_var('LIBRARY')
158 if not LIBRARY:
159 raise Exception("failed to get LIBRARY variable from sysconfig")
160 if os.path.exists(LIBRARY):
161 nsymbol += check_library(LIBRARY)
162
163 # dynamic library
164 LDLIBRARY = sysconfig.get_config_var('LDLIBRARY')
165 if not LDLIBRARY:
166 raise Exception("failed to get LDLIBRARY variable from sysconfig")
167 if LDLIBRARY != LIBRARY:
168 print()
169 nsymbol += check_library(LDLIBRARY, dynamic=True)
170
171 # Check extension modules like _ssl.cpython-310d-x86_64-linux-gnu.so
172 nsymbol += check_extensions()
173
174 if nsymbol:
175 print()
176 print(f"ERROR: Found {nsymbol} smelly symbols in total!")
177 sys.exit(1)
178
179 print()
180 print(f"OK: all exported symbols of all libraries "
181 f"are prefixed with {' or '.join(map(repr, ALLOWED_PREFIXES))}")
182
183
184 if __name__ == "__main__":
185 main()