| 1 |
"""Check the stable ABI manifest or generate files from it |
| 2 |
|
| 3 |
By default, the tool only checks existing files/libraries. |
| 4 |
Pass --generate to recreate auto-generated files instead. |
| 5 |
|
| 6 |
For actions that take a FILENAME, the filename can be left out to use a default |
| 7 |
(relative to the manifest file, as they appear in the CPython codebase). |
| 8 |
""" |
| 9 |
|
| 10 |
import argparse |
| 11 |
import csv |
| 12 |
import dataclasses |
| 13 |
import difflib |
| 14 |
import io |
| 15 |
import os |
| 16 |
import os.path |
| 17 |
import pprint |
| 18 |
import re |
| 19 |
import subprocess |
| 20 |
import sys |
| 21 |
import sysconfig |
| 22 |
import textwrap |
| 23 |
import tomllib |
| 24 |
from functools import partial |
| 25 |
from pathlib import Path |
| 26 |
|
| 27 |
SCRIPT_NAME = 'Tools/build/stable_abi.py' |
| 28 |
DEFAULT_MANIFEST_PATH = ( |
| 29 |
Path(__file__).parent / '../../Misc/stable_abi.toml').resolve() |
| 30 |
MISSING = object() |
| 31 |
|
| 32 |
EXCLUDED_HEADERS = { |
| 33 |
"bytes_methods.h", |
| 34 |
"cellobject.h", |
| 35 |
"classobject.h", |
| 36 |
"code.h", |
| 37 |
"compile.h", |
| 38 |
"datetime.h", |
| 39 |
"dtoa.h", |
| 40 |
"frameobject.h", |
| 41 |
"genobject.h", |
| 42 |
"longintrepr.h", |
| 43 |
"parsetok.h", |
| 44 |
"pyatomic.h", |
| 45 |
"token.h", |
| 46 |
"ucnhash.h", |
| 47 |
} |
| 48 |
MACOS = (sys.platform == "darwin") |
| 49 |
UNIXY = MACOS or (sys.platform == "linux") # XXX should this be "not Windows"? |
| 50 |
|
| 51 |
|
| 52 |
# The stable ABI manifest (Misc/stable_abi.toml) exists only to fill the |
| 53 |
# following dataclasses. |
| 54 |
# Feel free to change its syntax (and the `parse_manifest` function) |
| 55 |
# to better serve that purpose (while keeping it human-readable). |
| 56 |
|
| 57 |
class Manifest: |
| 58 |
"""Collection of `ABIItem`s forming the stable ABI/limited API.""" |
| 59 |
def __init__(self): |
| 60 |
self.contents = {} |
| 61 |
|
| 62 |
def add(self, item): |
| 63 |
if item.name in self.contents: |
| 64 |
# We assume that stable ABI items do not share names, |
| 65 |
# even if they're different kinds (e.g. function vs. macro). |
| 66 |
raise ValueError(f'duplicate ABI item {item.name}') |
| 67 |
self.contents[item.name] = item |
| 68 |
|
| 69 |
def select(self, kinds, *, include_abi_only=True, ifdef=None): |
| 70 |
"""Yield selected items of the manifest |
| 71 |
|
| 72 |
kinds: set of requested kinds, e.g. {'function', 'macro'} |
| 73 |
include_abi_only: if True (default), include all items of the |
| 74 |
stable ABI. |
| 75 |
If False, include only items from the limited API |
| 76 |
(i.e. items people should use today) |
| 77 |
ifdef: set of feature macros (e.g. {'HAVE_FORK', 'MS_WINDOWS'}). |
| 78 |
If None (default), items are not filtered by this. (This is |
| 79 |
different from the empty set, which filters out all such |
| 80 |
conditional items.) |
| 81 |
""" |
| 82 |
for name, item in sorted(self.contents.items()): |
| 83 |
if item.kind not in kinds: |
| 84 |
continue |
| 85 |
if item.abi_only and not include_abi_only: |
| 86 |
continue |
| 87 |
if (ifdef is not None |
| 88 |
and item.ifdef is not None |
| 89 |
and item.ifdef not in ifdef): |
| 90 |
continue |
| 91 |
yield item |
| 92 |
|
| 93 |
def dump(self): |
| 94 |
"""Yield lines to recreate the manifest file (sans comments/newlines)""" |
| 95 |
for item in self.contents.values(): |
| 96 |
fields = dataclasses.fields(item) |
| 97 |
yield f"[{item.kind}.{item.name}]" |
| 98 |
for field in fields: |
| 99 |
if field.name in {'name', 'value', 'kind'}: |
| 100 |
continue |
| 101 |
value = getattr(item, field.name) |
| 102 |
if value == field.default: |
| 103 |
pass |
| 104 |
elif value is True: |
| 105 |
yield f" {field.name} = true" |
| 106 |
elif value: |
| 107 |
yield f" {field.name} = {value!r}" |
| 108 |
|
| 109 |
|
| 110 |
itemclasses = {} |
| 111 |
def itemclass(kind): |
| 112 |
"""Register the decorated class in `itemclasses`""" |
| 113 |
def decorator(cls): |
| 114 |
itemclasses[kind] = cls |
| 115 |
return cls |
| 116 |
return decorator |
| 117 |
|
| 118 |
@itemclass('function') |
| 119 |
@itemclass('macro') |
| 120 |
@itemclass('data') |
| 121 |
@itemclass('const') |
| 122 |
@itemclass('typedef') |
| 123 |
@dataclasses.dataclass |
| 124 |
class ABIItem: |
| 125 |
"""Information on one item (function, macro, struct, etc.)""" |
| 126 |
|
| 127 |
name: str |
| 128 |
kind: str |
| 129 |
added: str = None |
| 130 |
abi_only: bool = False |
| 131 |
ifdef: str = None |
| 132 |
|
| 133 |
@itemclass('feature_macro') |
| 134 |
@dataclasses.dataclass(kw_only=True) |
| 135 |
class FeatureMacro(ABIItem): |
| 136 |
name: str |
| 137 |
doc: str |
| 138 |
windows: bool = False |
| 139 |
abi_only: bool = True |
| 140 |
|
| 141 |
@itemclass('struct') |
| 142 |
@dataclasses.dataclass(kw_only=True) |
| 143 |
class Struct(ABIItem): |
| 144 |
struct_abi_kind: str |
| 145 |
members: list = None |
| 146 |
|
| 147 |
|
| 148 |
def parse_manifest(file): |
| 149 |
"""Parse the given file (iterable of lines) to a Manifest""" |
| 150 |
|
| 151 |
manifest = Manifest() |
| 152 |
|
| 153 |
data = tomllib.load(file) |
| 154 |
|
| 155 |
for kind, itemclass in itemclasses.items(): |
| 156 |
for name, item_data in data[kind].items(): |
| 157 |
try: |
| 158 |
item = itemclass(name=name, kind=kind, **item_data) |
| 159 |
manifest.add(item) |
| 160 |
except BaseException as exc: |
| 161 |
exc.add_note(f'in {kind} {name}') |
| 162 |
raise |
| 163 |
|
| 164 |
return manifest |
| 165 |
|
| 166 |
# The tool can run individual "actions". |
| 167 |
# Most actions are "generators", which generate a single file from the |
| 168 |
# manifest. (Checking works by generating a temp file & comparing.) |
| 169 |
# Other actions, like "--unixy-check", don't work on a single file. |
| 170 |
|
| 171 |
generators = [] |
| 172 |
def generator(var_name, default_path): |
| 173 |
"""Decorates a file generator: function that writes to a file""" |
| 174 |
def _decorator(func): |
| 175 |
func.var_name = var_name |
| 176 |
func.arg_name = '--' + var_name.replace('_', '-') |
| 177 |
func.default_path = default_path |
| 178 |
generators.append(func) |
| 179 |
return func |
| 180 |
return _decorator |
| 181 |
|
| 182 |
|
| 183 |
@generator("python3dll", 'PC/python3dll.c') |
| 184 |
def gen_python3dll(manifest, args, outfile): |
| 185 |
"""Generate/check the source for the Windows stable ABI library""" |
| 186 |
write = partial(print, file=outfile) |
| 187 |
content = f"""\ |
| 188 |
/* Re-export stable Python ABI */ |
| 189 |
|
| 190 |
/* Generated by {SCRIPT_NAME} */ |
| 191 |
""" |
| 192 |
content += r""" |
| 193 |
#ifdef _M_IX86 |
| 194 |
#define DECORATE "_" |
| 195 |
#else |
| 196 |
#define DECORATE |
| 197 |
#endif |
| 198 |
|
| 199 |
#define EXPORT_FUNC(name) \ |
| 200 |
__pragma(comment(linker, "/EXPORT:" DECORATE #name "=" PYTHON_DLL_NAME "." #name)) |
| 201 |
#define EXPORT_DATA(name) \ |
| 202 |
__pragma(comment(linker, "/EXPORT:" DECORATE #name "=" PYTHON_DLL_NAME "." #name ",DATA")) |
| 203 |
""" |
| 204 |
write(textwrap.dedent(content)) |
| 205 |
|
| 206 |
def sort_key(item): |
| 207 |
return item.name.lower() |
| 208 |
|
| 209 |
windows_feature_macros = { |
| 210 |
item.name for item in manifest.select({'feature_macro'}) if item.windows |
| 211 |
} |
| 212 |
for item in sorted( |
| 213 |
manifest.select( |
| 214 |
{'function'}, |
| 215 |
include_abi_only=True, |
| 216 |
ifdef=windows_feature_macros), |
| 217 |
key=sort_key): |
| 218 |
write(f'EXPORT_FUNC({item.name})') |
| 219 |
|
| 220 |
write() |
| 221 |
|
| 222 |
for item in sorted( |
| 223 |
manifest.select( |
| 224 |
{'data'}, |
| 225 |
include_abi_only=True, |
| 226 |
ifdef=windows_feature_macros), |
| 227 |
key=sort_key): |
| 228 |
write(f'EXPORT_DATA({item.name})') |
| 229 |
|
| 230 |
ITEM_KIND_TO_DOC_ROLE = { |
| 231 |
'function': 'func', |
| 232 |
'data': 'data', |
| 233 |
'struct': 'type', |
| 234 |
'macro': 'macro', |
| 235 |
'const': 'macro', |
| 236 |
'typedef': 'type', |
| 237 |
} |
| 238 |
|
| 239 |
@generator("doc_list", 'Doc/data/stable_abi.dat') |
| 240 |
def gen_doc_annotations(manifest, args, outfile): |
| 241 |
"""Generate/check the stable ABI list for documentation annotations |
| 242 |
|
| 243 |
See ``StableABIEntry`` in ``Doc/tools/extensions/c_annotations.py`` |
| 244 |
for a description of each field. |
| 245 |
""" |
| 246 |
writer = csv.DictWriter( |
| 247 |
outfile, |
| 248 |
['role', 'name', 'added', 'ifdef_note', 'struct_abi_kind'], |
| 249 |
lineterminator='\n') |
| 250 |
writer.writeheader() |
| 251 |
kinds = set(ITEM_KIND_TO_DOC_ROLE) |
| 252 |
for item in manifest.select(kinds, include_abi_only=False): |
| 253 |
if item.ifdef: |
| 254 |
ifdef_note = manifest.contents[item.ifdef].doc |
| 255 |
else: |
| 256 |
ifdef_note = None |
| 257 |
row = { |
| 258 |
'role': ITEM_KIND_TO_DOC_ROLE[item.kind], |
| 259 |
'name': item.name, |
| 260 |
'added': item.added, |
| 261 |
'ifdef_note': ifdef_note, |
| 262 |
} |
| 263 |
rows = [row] |
| 264 |
if item.kind == 'struct': |
| 265 |
row['struct_abi_kind'] = item.struct_abi_kind |
| 266 |
for member_name in item.members or (): |
| 267 |
rows.append({ |
| 268 |
'role': 'member', |
| 269 |
'name': f'{item.name}.{member_name}', |
| 270 |
'added': item.added, |
| 271 |
}) |
| 272 |
writer.writerows(rows) |
| 273 |
|
| 274 |
@generator("ctypes_test", 'Lib/test/test_stable_abi_ctypes.py') |
| 275 |
def gen_ctypes_test(manifest, args, outfile): |
| 276 |
"""Generate/check the ctypes-based test for exported symbols""" |
| 277 |
write = partial(print, file=outfile) |
| 278 |
write(textwrap.dedent(f'''\ |
| 279 |
# Generated by {SCRIPT_NAME} |
| 280 |
|
| 281 |
"""Test that all symbols of the Stable ABI are accessible using ctypes |
| 282 |
""" |
| 283 |
|
| 284 |
import sys |
| 285 |
import unittest |
| 286 |
from test.support.import_helper import import_module |
| 287 |
try: |
| 288 |
from _testcapi import get_feature_macros |
| 289 |
except ImportError: |
| 290 |
raise unittest.SkipTest("requires _testcapi") |
| 291 |
|
| 292 |
feature_macros = get_feature_macros() |
| 293 |
|
| 294 |
# Stable ABI is incompatible with Py_TRACE_REFS builds due to PyObject |
| 295 |
# layout differences. |
| 296 |
# See https://github.com/python/cpython/issues/88299#issuecomment-1113366226 |
| 297 |
if feature_macros['Py_TRACE_REFS']: |
| 298 |
raise unittest.SkipTest("incompatible with Py_TRACE_REFS.") |
| 299 |
|
| 300 |
ctypes_test = import_module('ctypes') |
| 301 |
|
| 302 |
class TestStableABIAvailability(unittest.TestCase): |
| 303 |
def test_available_symbols(self): |
| 304 |
|
| 305 |
for symbol_name in SYMBOL_NAMES: |
| 306 |
with self.subTest(symbol_name): |
| 307 |
ctypes_test.pythonapi[symbol_name] |
| 308 |
|
| 309 |
def test_feature_macros(self): |
| 310 |
self.assertEqual( |
| 311 |
set(get_feature_macros()), EXPECTED_FEATURE_MACROS) |
| 312 |
|
| 313 |
# The feature macros for Windows are used in creating the DLL |
| 314 |
# definition, so they must be known on all platforms. |
| 315 |
# If we are on Windows, we check that the hardcoded data matches |
| 316 |
# the reality. |
| 317 |
@unittest.skipIf(sys.platform != "win32", "Windows specific test") |
| 318 |
def test_windows_feature_macros(self): |
| 319 |
for name, value in WINDOWS_FEATURE_MACROS.items(): |
| 320 |
if value != 'maybe': |
| 321 |
with self.subTest(name): |
| 322 |
self.assertEqual(feature_macros[name], value) |
| 323 |
|
| 324 |
SYMBOL_NAMES = ( |
| 325 |
''')) |
| 326 |
items = manifest.select( |
| 327 |
{'function', 'data'}, |
| 328 |
include_abi_only=True, |
| 329 |
) |
| 330 |
feature_macros = list(manifest.select({'feature_macro'})) |
| 331 |
optional_items = {m.name: [] for m in feature_macros} |
| 332 |
for item in items: |
| 333 |
if item.ifdef: |
| 334 |
optional_items[item.ifdef].append(item.name) |
| 335 |
else: |
| 336 |
write(f' "{item.name}",') |
| 337 |
write(")") |
| 338 |
for ifdef, names in optional_items.items(): |
| 339 |
write(f"if feature_macros[{ifdef!r}]:") |
| 340 |
write(f" SYMBOL_NAMES += (") |
| 341 |
for name in names: |
| 342 |
write(f" {name!r},") |
| 343 |
write(" )") |
| 344 |
write("") |
| 345 |
feature_names = sorted(m.name for m in feature_macros) |
| 346 |
write(f"EXPECTED_FEATURE_MACROS = set({pprint.pformat(feature_names)})") |
| 347 |
|
| 348 |
windows_feature_macros = {m.name: m.windows for m in feature_macros} |
| 349 |
write(f"WINDOWS_FEATURE_MACROS = {pprint.pformat(windows_feature_macros)}") |
| 350 |
|
| 351 |
|
| 352 |
@generator("testcapi_feature_macros", 'Modules/_testcapi_feature_macros.inc') |
| 353 |
def gen_testcapi_feature_macros(manifest, args, outfile): |
| 354 |
"""Generate/check the stable ABI list for documentation annotations""" |
| 355 |
write = partial(print, file=outfile) |
| 356 |
write(f'// Generated by {SCRIPT_NAME}') |
| 357 |
write() |
| 358 |
write('// Add an entry in dict `result` for each Stable ABI feature macro.') |
| 359 |
write() |
| 360 |
for macro in manifest.select({'feature_macro'}): |
| 361 |
name = macro.name |
| 362 |
write(f'#ifdef {name}') |
| 363 |
write(f' res = PyDict_SetItemString(result, "{name}", Py_True);') |
| 364 |
write('#else') |
| 365 |
write(f' res = PyDict_SetItemString(result, "{name}", Py_False);') |
| 366 |
write('#endif') |
| 367 |
write('if (res) {') |
| 368 |
write(' Py_DECREF(result); return NULL;') |
| 369 |
write('}') |
| 370 |
write() |
| 371 |
|
| 372 |
|
| 373 |
def generate_or_check(manifest, args, path, func): |
| 374 |
"""Generate/check a file with a single generator |
| 375 |
|
| 376 |
Return True if successful; False if a comparison failed. |
| 377 |
""" |
| 378 |
|
| 379 |
outfile = io.StringIO() |
| 380 |
func(manifest, args, outfile) |
| 381 |
generated = outfile.getvalue() |
| 382 |
existing = path.read_text() |
| 383 |
|
| 384 |
if generated != existing: |
| 385 |
if args.generate: |
| 386 |
path.write_text(generated) |
| 387 |
else: |
| 388 |
print(f'File {path} differs from expected!') |
| 389 |
diff = difflib.unified_diff( |
| 390 |
generated.splitlines(), existing.splitlines(), |
| 391 |
str(path), '<expected>', |
| 392 |
lineterm='', |
| 393 |
) |
| 394 |
for line in diff: |
| 395 |
print(line) |
| 396 |
return False |
| 397 |
return True |
| 398 |
|
| 399 |
|
| 400 |
def do_unixy_check(manifest, args): |
| 401 |
"""Check headers & library using "Unixy" tools (GCC/clang, binutils)""" |
| 402 |
okay = True |
| 403 |
|
| 404 |
# Get all macros first: we'll need feature macros like HAVE_FORK and |
| 405 |
# MS_WINDOWS for everything else |
| 406 |
present_macros = gcc_get_limited_api_macros(['Include/Python.h']) |
| 407 |
feature_macros = {m.name for m in manifest.select({'feature_macro'})} |
| 408 |
feature_macros &= present_macros |
| 409 |
|
| 410 |
# Check that we have all needed macros |
| 411 |
expected_macros = {item.name for item in manifest.select({'macro'})} |
| 412 |
missing_macros = expected_macros - present_macros |
| 413 |
okay &= _report_unexpected_items( |
| 414 |
missing_macros, |
| 415 |
'Some macros from are not defined from "Include/Python.h" ' |
| 416 |
'with Py_LIMITED_API:') |
| 417 |
|
| 418 |
expected_symbols = {item.name for item in manifest.select( |
| 419 |
{'function', 'data'}, include_abi_only=True, ifdef=feature_macros, |
| 420 |
)} |
| 421 |
|
| 422 |
# Check the static library (*.a) |
| 423 |
LIBRARY = sysconfig.get_config_var("LIBRARY") |
| 424 |
if not LIBRARY: |
| 425 |
raise Exception("failed to get LIBRARY variable from sysconfig") |
| 426 |
if os.path.exists(LIBRARY): |
| 427 |
okay &= binutils_check_library( |
| 428 |
manifest, LIBRARY, expected_symbols, dynamic=False) |
| 429 |
|
| 430 |
# Check the dynamic library (*.so) |
| 431 |
LDLIBRARY = sysconfig.get_config_var("LDLIBRARY") |
| 432 |
if not LDLIBRARY: |
| 433 |
raise Exception("failed to get LDLIBRARY variable from sysconfig") |
| 434 |
okay &= binutils_check_library( |
| 435 |
manifest, LDLIBRARY, expected_symbols, dynamic=False) |
| 436 |
|
| 437 |
# Check definitions in the header files |
| 438 |
expected_defs = {item.name for item in manifest.select( |
| 439 |
{'function', 'data'}, include_abi_only=False, ifdef=feature_macros, |
| 440 |
)} |
| 441 |
found_defs = gcc_get_limited_api_definitions(['Include/Python.h']) |
| 442 |
missing_defs = expected_defs - found_defs |
| 443 |
okay &= _report_unexpected_items( |
| 444 |
missing_defs, |
| 445 |
'Some expected declarations were not declared in ' |
| 446 |
'"Include/Python.h" with Py_LIMITED_API:') |
| 447 |
|
| 448 |
# Some Limited API macros are defined in terms of private symbols. |
| 449 |
# These are not part of Limited API (even though they're defined with |
| 450 |
# Py_LIMITED_API). They must be part of the Stable ABI, though. |
| 451 |
private_symbols = {n for n in expected_symbols if n.startswith('_')} |
| 452 |
extra_defs = found_defs - expected_defs - private_symbols |
| 453 |
okay &= _report_unexpected_items( |
| 454 |
extra_defs, |
| 455 |
'Some extra declarations were found in "Include/Python.h" ' |
| 456 |
'with Py_LIMITED_API:') |
| 457 |
|
| 458 |
return okay |
| 459 |
|
| 460 |
|
| 461 |
def _report_unexpected_items(items, msg): |
| 462 |
"""If there are any `items`, report them using "msg" and return false""" |
| 463 |
if items: |
| 464 |
print(msg, file=sys.stderr) |
| 465 |
for item in sorted(items): |
| 466 |
print(' -', item, file=sys.stderr) |
| 467 |
return False |
| 468 |
return True |
| 469 |
|
| 470 |
|
| 471 |
def binutils_get_exported_symbols(library, dynamic=False): |
| 472 |
"""Retrieve exported symbols using the nm(1) tool from binutils""" |
| 473 |
# Only look at dynamic symbols |
| 474 |
args = ["nm", "--no-sort"] |
| 475 |
if dynamic: |
| 476 |
args.append("--dynamic") |
| 477 |
args.append(library) |
| 478 |
proc = subprocess.run(args, stdout=subprocess.PIPE, encoding='utf-8') |
| 479 |
if proc.returncode: |
| 480 |
sys.stdout.write(proc.stdout) |
| 481 |
sys.exit(proc.returncode) |
| 482 |
|
| 483 |
stdout = proc.stdout.rstrip() |
| 484 |
if not stdout: |
| 485 |
raise Exception("command output is empty") |
| 486 |
|
| 487 |
for line in stdout.splitlines(): |
| 488 |
# Split line '0000000000001b80 D PyTextIOWrapper_Type' |
| 489 |
if not line: |
| 490 |
continue |
| 491 |
|
| 492 |
parts = line.split(maxsplit=2) |
| 493 |
if len(parts) < 3: |
| 494 |
continue |
| 495 |
|
| 496 |
symbol = parts[-1] |
| 497 |
if MACOS and symbol.startswith("_"): |
| 498 |
yield symbol[1:] |
| 499 |
else: |
| 500 |
yield symbol |
| 501 |
|
| 502 |
|
| 503 |
def binutils_check_library(manifest, library, expected_symbols, dynamic): |
| 504 |
"""Check that library exports all expected_symbols""" |
| 505 |
available_symbols = set(binutils_get_exported_symbols(library, dynamic)) |
| 506 |
missing_symbols = expected_symbols - available_symbols |
| 507 |
if missing_symbols: |
| 508 |
print(textwrap.dedent(f"""\ |
| 509 |
Some symbols from the limited API are missing from {library}: |
| 510 |
{', '.join(missing_symbols)} |
| 511 |
|
| 512 |
This error means that there are some missing symbols among the |
| 513 |
ones exported in the library. |
| 514 |
This normally means that some symbol, function implementation or |
| 515 |
a prototype belonging to a symbol in the limited API has been |
| 516 |
deleted or is missing. |
| 517 |
"""), file=sys.stderr) |
| 518 |
return False |
| 519 |
return True |
| 520 |
|
| 521 |
|
| 522 |
def gcc_get_limited_api_macros(headers): |
| 523 |
"""Get all limited API macros from headers. |
| 524 |
|
| 525 |
Runs the preprocessor over all the header files in "Include" setting |
| 526 |
"-DPy_LIMITED_API" to the correct value for the running version of the |
| 527 |
interpreter and extracting all macro definitions (via adding -dM to the |
| 528 |
compiler arguments). |
| 529 |
|
| 530 |
Requires Python built with a GCC-compatible compiler. (clang might work) |
| 531 |
""" |
| 532 |
|
| 533 |
api_hexversion = sys.version_info.major << 24 | sys.version_info.minor << 16 |
| 534 |
|
| 535 |
preprocessor_output_with_macros = subprocess.check_output( |
| 536 |
sysconfig.get_config_var("CC").split() |
| 537 |
+ [ |
| 538 |
# Prevent the expansion of the exported macros so we can |
| 539 |
# capture them later |
| 540 |
"-DSIZEOF_WCHAR_T=4", # The actual value is not important |
| 541 |
f"-DPy_LIMITED_API={api_hexversion}", |
| 542 |
"-I.", |
| 543 |
"-I./Include", |
| 544 |
"-dM", |
| 545 |
"-E", |
| 546 |
] |
| 547 |
+ [str(file) for file in headers], |
| 548 |
encoding='utf-8', |
| 549 |
) |
| 550 |
|
| 551 |
return set(re.findall(r"#define (\w+)", preprocessor_output_with_macros)) |
| 552 |
|
| 553 |
|
| 554 |
def gcc_get_limited_api_definitions(headers): |
| 555 |
"""Get all limited API definitions from headers. |
| 556 |
|
| 557 |
Run the preprocessor over all the header files in "Include" setting |
| 558 |
"-DPy_LIMITED_API" to the correct value for the running version of the |
| 559 |
interpreter. |
| 560 |
|
| 561 |
The limited API symbols will be extracted from the output of this command |
| 562 |
as it includes the prototypes and definitions of all the exported symbols |
| 563 |
that are in the limited api. |
| 564 |
|
| 565 |
This function does *NOT* extract the macros defined on the limited API |
| 566 |
|
| 567 |
Requires Python built with a GCC-compatible compiler. (clang might work) |
| 568 |
""" |
| 569 |
api_hexversion = sys.version_info.major << 24 | sys.version_info.minor << 16 |
| 570 |
preprocessor_output = subprocess.check_output( |
| 571 |
sysconfig.get_config_var("CC").split() |
| 572 |
+ [ |
| 573 |
# Prevent the expansion of the exported macros so we can capture |
| 574 |
# them later |
| 575 |
"-DPyAPI_FUNC=__PyAPI_FUNC", |
| 576 |
"-DPyAPI_DATA=__PyAPI_DATA", |
| 577 |
"-DEXPORT_DATA=__EXPORT_DATA", |
| 578 |
"-D_Py_NO_RETURN=", |
| 579 |
"-DSIZEOF_WCHAR_T=4", # The actual value is not important |
| 580 |
f"-DPy_LIMITED_API={api_hexversion}", |
| 581 |
"-I.", |
| 582 |
"-I./Include", |
| 583 |
"-E", |
| 584 |
] |
| 585 |
+ [str(file) for file in headers], |
| 586 |
encoding='utf-8', |
| 587 |
stderr=subprocess.DEVNULL, |
| 588 |
) |
| 589 |
stable_functions = set( |
| 590 |
re.findall(r"__PyAPI_FUNC\(.*?\)\s*(.*?)\s*\(", preprocessor_output) |
| 591 |
) |
| 592 |
stable_exported_data = set( |
| 593 |
re.findall(r"__EXPORT_DATA\((.*?)\)", preprocessor_output) |
| 594 |
) |
| 595 |
stable_data = set( |
| 596 |
re.findall(r"__PyAPI_DATA\(.*?\)[\s\*\(]*([^);]*)\)?.*;", preprocessor_output) |
| 597 |
) |
| 598 |
return stable_data | stable_exported_data | stable_functions |
| 599 |
|
| 600 |
def check_private_names(manifest): |
| 601 |
"""Ensure limited API doesn't contain private names |
| 602 |
|
| 603 |
Names prefixed by an underscore are private by definition. |
| 604 |
""" |
| 605 |
for name, item in manifest.contents.items(): |
| 606 |
if name.startswith('_') and not item.abi_only: |
| 607 |
raise ValueError( |
| 608 |
f'`{name}` is private (underscore-prefixed) and should be ' |
| 609 |
'removed from the stable ABI list or marked `abi_only`') |
| 610 |
|
| 611 |
def check_dump(manifest, filename): |
| 612 |
"""Check that manifest.dump() corresponds to the data. |
| 613 |
|
| 614 |
Mainly useful when debugging this script. |
| 615 |
""" |
| 616 |
dumped = tomllib.loads('\n'.join(manifest.dump())) |
| 617 |
with filename.open('rb') as file: |
| 618 |
from_file = tomllib.load(file) |
| 619 |
if dumped != from_file: |
| 620 |
print('Dump differs from loaded data!', file=sys.stderr) |
| 621 |
diff = difflib.unified_diff( |
| 622 |
pprint.pformat(dumped).splitlines(), |
| 623 |
pprint.pformat(from_file).splitlines(), |
| 624 |
'<dumped>', str(filename), |
| 625 |
lineterm='', |
| 626 |
) |
| 627 |
for line in diff: |
| 628 |
print(line, file=sys.stderr) |
| 629 |
return False |
| 630 |
else: |
| 631 |
return True |
| 632 |
|
| 633 |
def main(): |
| 634 |
parser = argparse.ArgumentParser( |
| 635 |
description=__doc__, |
| 636 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 637 |
) |
| 638 |
parser.add_argument( |
| 639 |
"file", type=Path, metavar='FILE', nargs='?', |
| 640 |
default=DEFAULT_MANIFEST_PATH, |
| 641 |
help=f"file with the stable abi manifest (default: {DEFAULT_MANIFEST_PATH})", |
| 642 |
) |
| 643 |
parser.add_argument( |
| 644 |
"--generate", action='store_true', |
| 645 |
help="generate file(s), rather than just checking them", |
| 646 |
) |
| 647 |
parser.add_argument( |
| 648 |
"--generate-all", action='store_true', |
| 649 |
help="as --generate, but generate all file(s) using default filenames." |
| 650 |
" (unlike --all, does not run any extra checks)", |
| 651 |
) |
| 652 |
parser.add_argument( |
| 653 |
"-a", "--all", action='store_true', |
| 654 |
help="run all available checks using default filenames", |
| 655 |
) |
| 656 |
parser.add_argument( |
| 657 |
"-l", "--list", action='store_true', |
| 658 |
help="list available generators and their default filenames; then exit", |
| 659 |
) |
| 660 |
parser.add_argument( |
| 661 |
"--dump", action='store_true', |
| 662 |
help="dump the manifest contents (used for debugging the parser)", |
| 663 |
) |
| 664 |
|
| 665 |
actions_group = parser.add_argument_group('actions') |
| 666 |
for gen in generators: |
| 667 |
actions_group.add_argument( |
| 668 |
gen.arg_name, dest=gen.var_name, |
| 669 |
type=str, nargs="?", default=MISSING, |
| 670 |
metavar='FILENAME', |
| 671 |
help=gen.__doc__, |
| 672 |
) |
| 673 |
actions_group.add_argument( |
| 674 |
'--unixy-check', action='store_true', |
| 675 |
help=do_unixy_check.__doc__, |
| 676 |
) |
| 677 |
args = parser.parse_args() |
| 678 |
|
| 679 |
base_path = args.file.parent.parent |
| 680 |
|
| 681 |
if args.list: |
| 682 |
for gen in generators: |
| 683 |
print(f'{gen.arg_name}: {(base_path / gen.default_path).resolve()}') |
| 684 |
sys.exit(0) |
| 685 |
|
| 686 |
run_all_generators = args.generate_all |
| 687 |
|
| 688 |
if args.generate_all: |
| 689 |
args.generate = True |
| 690 |
|
| 691 |
if args.all: |
| 692 |
run_all_generators = True |
| 693 |
if UNIXY: |
| 694 |
args.unixy_check = True |
| 695 |
|
| 696 |
try: |
| 697 |
file = args.file.open('rb') |
| 698 |
except FileNotFoundError as err: |
| 699 |
if args.file.suffix == '.txt': |
| 700 |
# Provide a better error message |
| 701 |
suggestion = args.file.with_suffix('.toml') |
| 702 |
raise FileNotFoundError( |
| 703 |
f'{args.file} not found. Did you mean {suggestion} ?') from err |
| 704 |
raise |
| 705 |
with file: |
| 706 |
manifest = parse_manifest(file) |
| 707 |
|
| 708 |
check_private_names(manifest) |
| 709 |
|
| 710 |
# Remember results of all actions (as booleans). |
| 711 |
# At the end we'll check that at least one action was run, |
| 712 |
# and also fail if any are false. |
| 713 |
results = {} |
| 714 |
|
| 715 |
if args.dump: |
| 716 |
for line in manifest.dump(): |
| 717 |
print(line) |
| 718 |
results['dump'] = check_dump(manifest, args.file) |
| 719 |
|
| 720 |
for gen in generators: |
| 721 |
filename = getattr(args, gen.var_name) |
| 722 |
if filename is None or (run_all_generators and filename is MISSING): |
| 723 |
filename = base_path / gen.default_path |
| 724 |
elif filename is MISSING: |
| 725 |
continue |
| 726 |
|
| 727 |
results[gen.var_name] = generate_or_check(manifest, args, filename, gen) |
| 728 |
|
| 729 |
if args.unixy_check: |
| 730 |
results['unixy_check'] = do_unixy_check(manifest, args) |
| 731 |
|
| 732 |
if not results: |
| 733 |
if args.generate: |
| 734 |
parser.error('No file specified. Use --generate-all to regenerate ' |
| 735 |
'all files, or --help for usage.') |
| 736 |
parser.error('No check specified. Use --all to check all files, ' |
| 737 |
'or --help for usage.') |
| 738 |
|
| 739 |
failed_results = [name for name, result in results.items() if not result] |
| 740 |
|
| 741 |
if failed_results: |
| 742 |
raise Exception(f""" |
| 743 |
These checks related to the stable ABI did not succeed: |
| 744 |
{', '.join(failed_results)} |
| 745 |
|
| 746 |
If you see diffs in the output, files derived from the stable |
| 747 |
ABI manifest the were not regenerated. |
| 748 |
Run `make regen-limited-abi` to fix this. |
| 749 |
|
| 750 |
Otherwise, see the error(s) above. |
| 751 |
|
| 752 |
The stable ABI manifest is at: {args.file} |
| 753 |
Note that there is a process to follow when modifying it. |
| 754 |
|
| 755 |
You can read more about the limited API and its contracts at: |
| 756 |
|
| 757 |
https://docs.python.org/3/c-api/stable.html |
| 758 |
|
| 759 |
And in PEP 384: |
| 760 |
|
| 761 |
https://peps.python.org/pep-0384/ |
| 762 |
""") |
| 763 |
|
| 764 |
|
| 765 |
if __name__ == "__main__": |
| 766 |
main() |