From 8112006dfa44506c445ee4a76459c7deedb4c1cc Mon Sep 17 00:00:00 2001 From: DerThorsten Date: Fri, 27 Nov 2026 13:34:42 +0100 Subject: [PATCH] [6x] python: split the stdlib extension modules into side-module packages The interpreter is split at the builtin-module line (see the outputs comment in recipes/recipes_wasm/python/recipe.yaml): libpython-static is the slim core, openssl / sqlite / lzma / the CJK codecs / CPython's test modules are emscripten side modules in their own packages (python-ssl, python-sqlite3, python-lzma, python-cjkcodecs, python-test-modules); python-core is the stdlib, python a meta package with everything as before (but the test modules), python-dev adds libpython-static. - run_constraints pyjs >= 6 on python-core and python: pyjs < 6 (and xeus-python built on it) only unpacks the package named python and so gets the unsplit python (build 8) - libpython-static: openssl / lzma / uuid / sqlite no longer run deps - generic-testing 0.4.0: archives with LLVM bitcode members, ... - sqlite: built for the side module - python tests: core-only env (node) and full env (node + browser); playwright + playwright-python pinned to the same version (1.62.*): a driver / API mismatch failed the browser launch - regex: rebuilt against the split python, tested with pytester (Replaces the earlier branch: its temporary python pin in pytester-run is not needed since pyjs 6.0.1 + pytester 1.7.0 are on the channel.) Co-Authored-By: Claude Opus 5.5 --- .../generic_testing/__main__.py | 7 +- .../generic_testing/check_lib.py | 249 +++++++++++++--- .../generic-testing/recipe.yaml | 4 +- .../generic-testing/test_check_lib.py | 156 ++++++++-- recipes/recipes_wasm/python/HACL_LICENSE.txt | 26 ++ recipes/recipes_wasm/python/Setup.local | 22 +- recipes/recipes_wasm/python/browser_test.mjs | 6 +- recipes/recipes_wasm/python/build.sh | 121 +++++++- recipes/recipes_wasm/python/build_tests.sh | 43 ++- .../recipes_wasm/python/node_test_wrapper.js | 12 +- recipes/recipes_wasm/python/python_tests.mjs | 101 ++++++- recipes/recipes_wasm/python/recipe.yaml | 274 +++++++++++++++++- recipes/recipes_wasm/regex/recipe.yaml | 2 +- recipes/recipes_wasm/sqlite/LICENSE.md | 9 + recipes/recipes_wasm/sqlite/build.sh | 77 +++-- recipes/recipes_wasm/sqlite/recipe.yaml | 12 +- 16 files changed, 986 insertions(+), 135 deletions(-) create mode 100644 recipes/recipes_wasm/python/HACL_LICENSE.txt create mode 100644 recipes/recipes_wasm/sqlite/LICENSE.md diff --git a/recipes/recipes_native/generic-testing/generic_testing/__main__.py b/recipes/recipes_native/generic-testing/generic_testing/__main__.py index d525b0843bb..62f5dffc19d 100644 --- a/recipes/recipes_native/generic-testing/generic_testing/__main__.py +++ b/recipes/recipes_native/generic-testing/generic_testing/__main__.py @@ -8,7 +8,12 @@ def main(): parser = argparse.ArgumentParser(description="Run generic tests for a package") - parser.add_argument("--allow-pthread", action="store_true", help="Allow pthread symbols in the package") + parser.add_argument( + "--allow-pthread", + action="store_true", + help="Allow code compiled with thread support (-pthread: atomics / shared memory). " + "Calling pthread_* functions alone never needs this.", + ) args = parser.parse_args() diff --git a/recipes/recipes_native/generic-testing/generic_testing/check_lib.py b/recipes/recipes_native/generic-testing/generic_testing/check_lib.py index 4edc7ae6a56..cf8001eb8dd 100644 --- a/recipes/recipes_native/generic-testing/generic_testing/check_lib.py +++ b/recipes/recipes_native/generic-testing/generic_testing/check_lib.py @@ -6,18 +6,22 @@ import subprocess -def run_llvm_readobj(path, *options): - cmd = ["llvm-readobj", *options, str(path)] +def run_llvm_tool(tool, path, *options): + cmd = [tool, *options, str(path)] try: output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return output.decode("utf-8") except subprocess.CalledProcessError as e: - print(f"Error running llvm-readobj on {path}:") + print(f"Error running {tool} on {path}:") print(e.output.decode("utf-8")) sys.exit(1) +def run_llvm_readobj(path, *options): + return run_llvm_tool("llvm-readobj", path, *options) + + def is_memoryless_function_module(path): with open(path, "rb") as binary: if binary.read(8) != b"\0asm\x01\0\0\0": @@ -59,13 +63,68 @@ def read_uleb(): return False +# The two magic numbers of LLVM bitcode: plain, and the wrapper format. +BITCODE_MAGICS = (b"BC\xc0\xde", b"\xde\xc0\x17\x0b") + + +def members(path): + """The (name, bytes) of the objects in `path`: the members of a static + library (an `ar` archive), or the file itself for a single object.""" + data = Path(path).read_bytes() + if data[:8] != b"!\n": + return [(Path(path).name, data)] + result = [] + pos = 8 + while pos + 60 <= len(data): + header = data[pos:pos + 60] + size = int(header[48:58]) + name = header[:16].decode("latin-1").strip() + body = data[pos + 60:pos + 60 + size] + # (members start at even offsets) + pos += 60 + size + (size & 1) + # the symbol table and the long-name table are no objects + if name in ("/", "//", "/SYM64/"): + continue + result.append((name, body)) + return result + + +def bitcode_members(path): + """The members of `path` that are LLVM bitcode (link-time optimization: + compiled with -flto they contain LLVM IR, no WebAssembly yet).""" + return [(name, body) for name, body in members(path) if body[:4] in BITCODE_MAGICS] + + +def check_arch_of_bitcode(path, slim_arch): + """LLVM bitcode carries its target triple, e.g. + "wasm32-unknown-emscripten", in its string table as plain text. Every + bitcode member must name the expected architecture and not the other + one: the same mistake check_arch_of_lib catches for WebAssembly objects + (built for the wrong target).""" + other = {"wasm32": "wasm64", "wasm64": "wasm32"}[slim_arch] + for name, body in bitcode_members(path): + if f"{other}-".encode() in body or f"{slim_arch}-".encode() not in body: + print(f"Error: {path}: the LLVM bitcode of {name} is not built for {slim_arch}") + sys.exit(1) + + def check_arch_of_lib(path, arch): output = run_llvm_readobj(path, "-h") # arch is expected to be e.g. "emscripten-wasm32" or "emscripten-wasm64" slim_arch = arch.split("-")[-1] + # Static libraries / objects compiled with -flto (link-time optimization) + # contain LLVM bitcode instead of WebAssembly. That is fine (the linker + # compiles it), as long as it is bitcode for the right target. + has_bitcode = not str(path).endswith(".so") and bool(bitcode_members(path)) + if has_bitcode: + check_arch_of_bitcode(path, slim_arch) + # only bitcode: nothing left for the checks of WebAssembly below + if "Format: WASM" not in output: + return + if "Format: WASM" not in output: - print(f"Error: {path} is not a WebAssembly library") + print(f"Error: {path} is neither a WebAssembly library nor LLVM bitcode") sys.exit(1) # LLVM defaults to wasm32 for function-only wrappers with no memory width. @@ -90,42 +149,158 @@ def check_arch_of_lib(path, arch): sys.exit(1) -def check_no_pthread_symbols(path, allow_pthread): +# --------------------------------------------------------------------------- +# Thread support (-pthread) +# +# What the check is for: a package must not force its users to link with +# -pthread. That is the case when code was COMPILED with thread support: +# it then uses WebAssembly atomics and needs shared memory, and the linker +# refuses to mix it with code built without. Calling pthread_* functions +# alone is fine: emscripten's libc has them in non-threaded builds too +# (CPython calls pthread_mutex_lock & co. but is built without -pthread). +# +# What marks code compiled with -pthread (checked with emscripten 6.0.8): +# WebAssembly objects (.o, members of .a) "+atomics" in the custom +# section "target_features" +# LLVM bitcode (-flto) "+atomics" in the +# "target-features" attribute +# of its functions (llvm-dis) +# linked modules (.so) no target_features section +# any more; their memory +# (imported or own) is shared +# --------------------------------------------------------------------------- +def read_uleb(data, pos): + """an unsigned LEB128 integer at `pos` of `data`: (value, next position)""" + value = shift = 0 + while True: + byte = data[pos] + pos += 1 + value |= (byte & 0x7F) << shift + shift += 7 + if byte < 0x80: + return value, pos + + +def wasm_sections(data): + """(id, payload) of each section of a WebAssembly module / object""" + pos = 8 # magic number + version + while pos < len(data): + section_id = data[pos] + size, pos = read_uleb(data, pos + 1) + yield section_id, data[pos:pos + size] + pos += size + + +def wasm_target_features(data): + """the entries of the "target_features" custom section of a WebAssembly + object, e.g. {"+atomics", "+bulk-memory"} (empty if there is none)""" + features = set() + for section_id, payload in wasm_sections(data): + if section_id != 0: + continue + length, pos = read_uleb(payload, 0) + if payload[pos:pos + length] != b"target_features": + continue + count, pos = read_uleb(payload, pos + length) + for _ in range(count): + prefix = chr(payload[pos]) + length, pos = read_uleb(payload, pos + 1) + features.add(prefix + payload[pos:pos + length].decode()) + pos += length + return features + + +def wasm_has_shared_memory(data): + """does a linked WebAssembly module import or define shared memory? + (bit 0x02 of the limits flags of a memory)""" + for section_id, payload in wasm_sections(data): + if section_id == 2: # imports + count, pos = read_uleb(payload, 0) + for _ in range(count): + for _ in range(2): # module and field name + length, pos = read_uleb(payload, pos) + pos += length + kind = payload[pos] + pos += 1 + if kind == 0: # function: type index + _, pos = read_uleb(payload, pos) + elif kind in (1, 2): # table (+ element type) / memory: limits + if kind == 1: + pos += 1 + flags, pos = read_uleb(payload, pos) + if kind == 2 and flags & 0x02: + return True + _, pos = read_uleb(payload, pos) + if flags & 0x01: + _, pos = read_uleb(payload, pos) + elif kind == 3: # global: value type + mutability + pos += 2 + else: + # (tags, or something newer: memories come before, stop) + break + elif section_id == 5: # own memories + count, pos = read_uleb(payload, 0) + for _ in range(count): + flags, pos = read_uleb(payload, pos) + if flags & 0x02: + return True + _, pos = read_uleb(payload, pos) + if flags & 0x01: + _, pos = read_uleb(payload, pos) + return False + + +def bitcode_uses_atomics(body): + """is the LLVM bitcode `body` compiled with thread support? (its + functions' target features, as llvm-dis shows them, contain +atomics)""" + try: + text = subprocess.run( + ["llvm-dis", "-o", "-", "-"], input=body, capture_output=True, check=True + ).stdout + except subprocess.CalledProcessError as e: + print("Error running llvm-dis:") + print(e.stderr.decode("utf-8", "replace")) + sys.exit(1) + return re.search(rb'"target-features"="[^"]*\+atomics', text) is not None + + +def threaded_parts(path): + """the names of the objects in `path` that were compiled with thread + support (see above)""" + linked = str(path).endswith(".so") + result = [] + for name, body in members(path): + if body[:4] == b"\0asm": + if linked: + threaded = wasm_has_shared_memory(body) + else: + threaded = "+atomics" in wasm_target_features(body) + elif body[:4] in BITCODE_MAGICS: + threaded = bitcode_uses_atomics(body) + else: + threaded = False + if threaded: + result.append(name) + return result + + +def check_no_threads(path, allow_pthread): + """Fail if `path` contains code compiled with thread support (-pthread), + which would force every user to link with -pthread too; unless the + package says it is meant to be threaded (--allow-pthread).""" if allow_pthread: return - - output = run_llvm_readobj(path, "--symbols") - - # print(f"output for {path}") - # print(output) - - lines = output.splitlines() - context = 10 - - pthread_matches = [ - i for i, line in enumerate(lines) - if re.search(r"^\s*Name:\s+_*pthread_", line) - ] - - if pthread_matches: + threaded = threaded_parts(path) + if threaded: print( - f"Error: {path} contains pthread symbols " - "but --allow-pthread is not set" + f"Error: {path} contains code compiled with thread support (-pthread: " + "WebAssembly atomics / shared memory), which forces its users to link with " + "-pthread too; --allow-pthread is not set" ) - - print("\npthread-related symbols with context:") - - for index in pthread_matches: - start = max(0, index - context) - end = min(len(lines), index + context + 1) - - print("\n" + "=" * 80) - print(f"Match at line {index + 1}") - - for i in range(start, end): - prefix = ">>> " if i == index else " " - print(f"{prefix}{i + 1:5}: {lines[i]}") - + for name in threaded[:20]: + print(f" {name}") + if len(threaded) > 20: + print(f" ... and {len(threaded) - 20} more") sys.exit(1) def check_lib(path, arch, allow_pthread): @@ -144,5 +319,5 @@ def check_lib(path, arch, allow_pthread): sys.exit(1) check_arch_of_lib(path, arch) - check_no_pthread_symbols(path, allow_pthread) + check_no_threads(path, allow_pthread) diff --git a/recipes/recipes_native/generic-testing/recipe.yaml b/recipes/recipes_native/generic-testing/recipe.yaml index ae5c56f01f7..c2efd240379 100644 --- a/recipes/recipes_native/generic-testing/recipe.yaml +++ b/recipes/recipes_native/generic-testing/recipe.yaml @@ -1,5 +1,5 @@ context: - version: '0.3.3' + version: '0.4.0' name: generic-testing package: @@ -12,7 +12,7 @@ source: build: - number: 2 + number: 0 noarch: python script: build.sh python: diff --git a/recipes/recipes_native/generic-testing/test_check_lib.py b/recipes/recipes_native/generic-testing/test_check_lib.py index a175f5f570e..b2e5fb5bf34 100644 --- a/recipes/recipes_native/generic-testing/test_check_lib.py +++ b/recipes/recipes_native/generic-testing/test_check_lib.py @@ -7,7 +7,7 @@ from generic_testing.check_lib import ( check_arch_of_lib, - check_no_pthread_symbols, + check_no_threads, is_memoryless_function_module, run_llvm_readobj, ) @@ -68,25 +68,141 @@ def test_archives_objects_and_truncated_modules_are_not_exempt(self): self.assertEqual(error.code, 1) -class PthreadSymbolTests(unittest.TestCase): - def test_unrelated_symbol_names(self): - output = "\n".join([ - "File: /tmp/pthread/example.so", - "Name: FLAGS_pthreadpool_size", - "Name: _ZN4llvm15JumpThreadingPass3runEv", - "Name: pthreadpool_parallelize_1d", - ]) - with mock.patch("generic_testing.check_lib.run_llvm_readobj", return_value=output): - check_no_pthread_symbols(Path("example.so"), False) - - def test_actual_pthread_symbols_are_rejected(self): - for name in ("pthread_create", "_pthread_join", "__pthread_mutex_lock", - "pthread_create.llvm.123"): - with self.subTest(name=name), contextlib.redirect_stdout(io.StringIO()): - with mock.patch("generic_testing.check_lib.run_llvm_readobj", - return_value=f" Name: {name}\n"): - with self.assertRaises(SystemExit): - check_no_pthread_symbols(Path("example.so"), False) +def archive(*members): + """an `ar` archive (static library) with the given (name, bytes) members""" + data = b"!\n" + for name, body in members: + header = f"{name + '/':<16}{0:<12}{0:<6}{0:<6}{644:<8}{len(body):<10}`\n" + data += header.encode() + body + (b"\n" if len(body) % 2 else b"") + return data + + +def bitcode(triple): + """a stand-in for an LLVM bitcode object: the magic number and, as in + the string table of real bitcode, the target triple as plain text""" + return b"BC\xc0\xde" + b"\0" * 12 + triple + b"\0" * 7 + + +class BitcodeTests(unittest.TestCase): + """Static libraries compiled with -flto contain LLVM bitcode: accepted, + but only for the right architecture.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.path = Path(directory.name) / "libexample.a" + # (llvm-readobj sees no WebAssembly in bitcode) + patcher = mock.patch("generic_testing.check_lib.run_llvm_readobj", + return_value="File: libexample.a\n") + patcher.start() + self.addCleanup(patcher.stop) + + def check(self, data, arch): + self.path.write_bytes(data) + check_arch_of_lib(self.path, "emscripten-" + arch) + + def test_bitcode_of_the_right_arch(self): + for arch in ("wasm32", "wasm64"): + triple = f"{arch}-unknown-emscripten".encode() + self.check(archive(("a.o", bitcode(triple)), ("b.o", bitcode(triple))), arch) + + def test_bitcode_of_the_wrong_arch_or_without_wasm_triple(self): + for triple, arch in ((b"wasm64-unknown-emscripten", "wasm32"), + (b"wasm32-unknown-emscripten", "wasm64"), + (b"x86_64-apple-darwin", "wasm32")): + with self.subTest(triple=triple, arch=arch), contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit): + self.check(archive(("a.o", bitcode(triple))), arch) + + def test_one_wrong_member_is_enough(self): + good, bad = bitcode(b"wasm32-unknown-emscripten"), bitcode(b"wasm64-unknown-emscripten") + with contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + self.check(archive(("a.o", good), ("b.o", bad)), "wasm32") + + def test_neither_wasm_nor_bitcode(self): + with contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + self.check(archive(("a.o", b"\x7fELF" + b"\0" * 12)), "wasm32") + + +def section(section_id, payload): + """a WebAssembly section""" + return bytes((section_id, len(payload))) + payload + + +def custom_section(name, payload): + return section(0, bytes((len(name),)) + name + payload) + + +def target_features(*features): + """a "target_features" custom section, as in objects compiled by clang""" + entries = b"".join(f[:1].encode() + bytes((len(f) - 1,)) + f[1:].encode() for f in features) + return custom_section(b"target_features", bytes((len(features),)) + entries) + + +def wasm_object(*features, symbol=b"pthread_mutex_lock"): + """a WebAssembly object: a name in a custom section (stands for its + symbols, e.g. a call of pthread_mutex_lock) and its target features""" + return HEADER + custom_section(b"names", symbol) + target_features(*features) + + +def linked_module(memory_flags): + """a linked module (.so) importing env.memory with the given flags""" + entry = b"\x03env\x06memory\x02" + bytes((memory_flags, 1)) + if memory_flags & 1: + entry += b"\x02" + return HEADER + section(2, b"\x01" + entry) + + +class ThreadTests(unittest.TestCase): + """--allow-pthread is about code compiled with thread support (atomics / + shared memory), not about calling pthread_* functions""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = Path(directory.name) + + def check(self, name, data, allow_pthread=False): + path = self.directory / name + path.write_bytes(data) + check_no_threads(path, allow_pthread) + + def rejected(self, name, data): + with contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): + self.check(name, data) + + def test_objects(self): + default = ("+bulk-memory", "+mutable-globals", "+sign-ext") + # calls pthread_* but compiled without -pthread: fine + self.check("libplain.a", archive(("a.o", wasm_object(*default)))) + self.check("plain.o", wasm_object(*default)) + # compiled with -pthread: one such member is enough + threaded = wasm_object("+atomics", *default) + self.rejected("libthreads.a", archive(("a.o", wasm_object(*default)), ("b.o", threaded))) + self.rejected("threads.o", threaded) + self.check("libthreads.a", archive(("b.o", threaded)), allow_pthread=True) + + def test_linked_modules(self): + for flags in (0x00, 0x01, 0x04): + self.check("plain.so", linked_module(flags)) + for flags in (0x02, 0x03): + self.rejected("threads.so", linked_module(flags)) + # (a module without imports, e.g. the forwarder above) + self.check("facade.so", FACADE) + + def test_bitcode(self): + member = bitcode(b"wasm32-unknown-emscripten") + for disassembly, threaded in ( + (b'attributes #0 = { "target-features"="+bulk-memory,+sign-ext" }', False), + (b'attributes #0 = { "target-features"="+atomics,+bulk-memory" }', True), + ): + result = mock.Mock(stdout=disassembly) + with self.subTest(threaded=threaded), \ + mock.patch("generic_testing.check_lib.subprocess.run", return_value=result): + if threaded: + self.rejected("libexample.a", archive(("a.o", member))) + else: + self.check("libexample.a", archive(("a.o", member))) if __name__ == "__main__": diff --git a/recipes/recipes_wasm/python/HACL_LICENSE.txt b/recipes/recipes_wasm/python/HACL_LICENSE.txt new file mode 100644 index 00000000000..df2a74a4743 --- /dev/null +++ b/recipes/recipes_wasm/python/HACL_LICENSE.txt @@ -0,0 +1,26 @@ +HACL* (CPython's Modules/_hacl: the builtin hashlib hashes MD5, SHA-1, +SHA-2, SHA-3, BLAKE2). No license file of its own: the notice at the top of +its source files: + +MIT License + +Copyright (c) 2016-2022 INRIA, CMU and Microsoft Corporation +Copyright (c) 2022-2023 HACL* Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/recipes/recipes_wasm/python/Setup.local b/recipes/recipes_wasm/python/Setup.local index 550c6f00207..6106c99f3cf 100644 --- a/recipes/recipes_wasm/python/Setup.local +++ b/recipes/recipes_wasm/python/Setup.local @@ -1,6 +1,15 @@ - # This file gets copied into the Modules/ folder when building -# newlib configurations which do not support dynamic library -# loading. +# This file gets copied into the Modules/ folder when building. +# It decides which optional extension modules are builtin modules of +# libpythonX.Y.a (the slim python core). +# +# Everything the embedder of libpython must link statically is listed in the +# *static* section (plus what Modules/Setup.stdlib adds: makesetup uses the +# first rule of a module, so a module named here is not taken from there). +# +# The heavy optional modules (_ssl, _sqlite3, _lzma, the CJK codecs, the test +# modules) are NOT builtin: build.sh appends a *shared* section with their +# rules (see SIDE_MODULES there), they are built as emscripten side modules +# (lib/pythonX.Y/lib-dynload/*.so) and packaged in their own outputs. # # See build/Python-*/Modules/Setup for more details @@ -14,17 +23,14 @@ _posixsubprocess _posixsubprocess.c _bz2 _bz2module.c -lbz2 zlib zlibmodule.c -_ssl _ssl.c -lssl -lcrypto -L$(prefix)/lib -I$(prefix)/include -DOPENSSL_THREADS - fcntl fcntlmodule.c -L$(prefix)/lib -I$(prefix)/include #_xxsubinterpreters _xxsubinterpretersmodule.c -_lzma _lzmamodule.c -L$(prefix)/lib -I$(prefix)/include -llzma - +# _hashlib (openssl): not built, hashlib uses the builtin HACL* hashes. # _uuid requires libuuid link; uuid stdlib works without it (ImportError fallback). Disable for wasm to avoid link issues. *disabled* pwd _hashlib -_uuid \ No newline at end of file +_uuid diff --git a/recipes/recipes_wasm/python/browser_test.mjs b/recipes/recipes_wasm/python/browser_test.mjs index 0b06f1ca8fd..ee8392dbd3f 100644 --- a/recipes/recipes_wasm/python/browser_test.mjs +++ b/recipes/recipes_wasm/python/browser_test.mjs @@ -1,7 +1,9 @@ // Runs the plain python tests (python_tests.mjs) in the browser, driven by // browser_test.py (playwright). The python stdlib is preloaded into the // emscripten FS (--preload-file, see build_tests.sh). -import { pythonTests } from "./python_tests.mjs"; +import { pythonTests, testCode } from "./python_tests.mjs"; +// written by build_tests.sh: is this a core-only env (no extension outputs)? +import { coreOnly } from "./test_config.mjs"; function wasmGcSupported() { // a module with a wasm-gc struct type @@ -30,7 +32,7 @@ globalThis.runPythonTests = async function () { continue; } console.log(`=== ${test.name}`); - results.push({ name: test.name, ok: run(test.code) === 0 }); + results.push({ name: test.name, ok: run(testCode(test, coreOnly)) === 0 }); } return { results, diff --git a/recipes/recipes_wasm/python/build.sh b/recipes/recipes_wasm/python/build.sh index 0173a67911b..cd27bfeb776 100644 --- a/recipes/recipes_wasm/python/build.sh +++ b/recipes/recipes_wasm/python/build.sh @@ -69,8 +69,30 @@ export OPTFLAGS="${OPTFLAGS:--O2}" export DBGFLAGS="${DBGFLAGS:--g0}" export EXTRA_CFLAGS="${EXTRA_CFLAGS:-}" +# A debug build of the interpreter, only on request: PYTHON_DEBUG_BUILD=1. +# (These flags come after OPTFLAGS in CFLAGS_BASE below, and the last -O +# wins: they turn optimization off. Until build 13 they were always on, which +# made every embedder's python an -O0 build; pure-Python code in pyjs was +# measurably slower than in pyodide.) +if [[ "${PYTHON_DEBUG_BUILD:-0}" == "1" ]]; then + export EXTRA_CFLAGS="${EXTRA_CFLAGS} -O0 -g3 -gsource-map" +fi -export EXTRA_CFLAGS="${EXTRA_CFLAGS} -O0 -g3 -gsource-map" +# Link-time optimization of the interpreter (CPython's --with-lto, see the +# configure call). PYTHON_LTO=0 turns it off. It needs llvm-ar; emscripten's +# is emar. The objects in libpythonX.Y.a are LLVM bitcode then: an embedder +# linking it (pyjs, xeus-python) must use the same emscripten version, which +# the pinned compiler of this channel ensures. Extension modules built against +# this python are not affected (the LTO flags are in CFLAGS_NODIST, which is +# not passed on to them). generic-testing >= 0.4 accepts bitcode in static +# libraries and checks its target (wasm32 / wasm64) instead. +if [[ "${PYTHON_LTO:-1}" == "1" ]]; then + # (plain --with-lto: for emcc CPython's configure accepts no LTO variant + # like =full / =thin) + LTO_ARGS="--with-lto" +else + LTO_ARGS="" +fi export CFLAGS_BASE="${OPTFLAGS} ${DBGFLAGS} -fPIC -fwasm-exceptions -sSUPPORT_LONGJMP ${EXTRA_CFLAGS}" @@ -112,10 +134,96 @@ ln -sf "${BUILD_PREFIX}/bin/python${PY_VERSION}" "${BUILD_PREFIX}/bin/python.mjs cp "${RECIPE_DIR}/Setup.local" . cp "${RECIPE_DIR}/adjust_sysconfig.py" . +# --------------------------------------------------------------------------- +# Side modules: optional extension modules that are not part of the slim core +# (libpythonX.Y.a) but emscripten side modules in lib/pythonX.Y/lib-dynload, +# each one statically containing the C library it needs. The embedder of +# libpython (a MAIN_MODULE) then does not have to link openssl / sqlite / ... +# and `import ssl` works once the package with the side module is installed. +# The recipe outputs (python-ssl, python-sqlite3, ...) pick them by file name. +# --------------------------------------------------------------------------- +SIDE_MODULES_SSL="_ssl" +SIDE_MODULES_SQLITE3="_sqlite3" +SIDE_MODULES_LZMA="_lzma" +SIDE_MODULES_CJKCODECS="_multibytecodec _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw" +SIDE_MODULES_TEST="xxsubtype _xxtestfuzz _testbuffer _testinternalcapi _testcapi _testlimitedcapi _testclinic _testclinic_limited" +SIDE_MODULES="${SIDE_MODULES_SSL} ${SIDE_MODULES_SQLITE3} ${SIDE_MODULES_LZMA} ${SIDE_MODULES_CJKCODECS} ${SIDE_MODULES_TEST}" +# lib-dynload: CPython's standard directory for the stdlib's extension +# modules built as shared libraries (on Linux e.g. _ssl.cpython-314-x86_64- +# linux-gnu.so lives there). It is on sys.path by default, so `import _ssl` +# finds the side module there and python dlopens it; nothing to configure. +DYNLOAD_DIR="${PREFIX}/lib/python${PYMAJOR}.${PYMINOR}/lib-dynload" + +# Extra compiler flags a side module needs besides its MODULE__CFLAGS. +side_module_extra_cflags() { + case "$1" in + # _ssl.c has `#ifndef OPENSSL_THREADS / #error "Python requires + # thread-safe OpenSSL"` (libopenssl-static is built without threads, + # there are none in the browser). The define only silences that check: + # it compiles no thread code and links no thread library. The locks + # _ssl.c takes are CPython's own (PyMutex, PyThread_allocate_lock: no-ops + # without threads) and openssl's (X509_STORE_lock: no-ops in a no-threads + # openssl). generic-testing checks the side module has no thread code. + _ssl) echo "-DOPENSSL_THREADS" ;; + esac +} + +# Append a *shared* section with the rules of the side modules to Setup.local. +# A "rule" is a line of CPython's Setup file format: how to build one +# extension module, ` `, e.g. +# _lzma _lzmamodule.c +# (makesetup adds the configure flags MODULE__LZMA_CFLAGS / _LDFLAGS to a +# rule without flags). CPython's makesetup script turns each line into Makefile targets that +# compile and link that module; modules below `*shared*` become shared +# libraries (here: emscripten side modules) instead of builtins of +# libpython. The rules are taken from upstream's Modules/Setup.stdlib.in, so +# sources and flags follow CPython. +append_side_module_rules() { + local setup_local="$1" mod rule extra upper + echo '*shared*' >> "${setup_local}" + for mod in ${SIDE_MODULES}; do + rule="$(sed -n "s/^@MODULE_[A-Z0-9_]*_TRUE@\(${mod} .*\)\$/\1/p" "${BUILD}/Modules/Setup.stdlib.in")" + if [[ -z "${rule}" ]]; then + echo "no rule for side module ${mod} in Modules/Setup.stdlib.in" + exit 1 + fi + # makesetup only adds the configure flags to rules without any flag + extra="$(side_module_extra_cflags "${mod}")" + if [[ -n "${extra}" ]]; then + upper="$(echo "${mod}" | tr '[:lower:]' '[:upper:]')" + rule="${rule} \$(MODULE_${upper}_CFLAGS) ${extra} \$(MODULE_${upper}_LDFLAGS)" + fi + echo "${rule}" >> "${setup_local}" + done +} + +# Build one side module with CPython's own Makefile rule and install it. +# SIDE_MODULE=2 + the single exported init function: the linker only keeps +# what the module needs from the static C library (e.g. of libcrypto). +# The static C libraries must be built with -fvisibility=hidden (openssl, xz, +# sqlite >= build 5 are): a default-visibility function whose address is +# taken is exported by a side module (e.g. all of sqlite via its extension +# API table), and the dynamic linker may then bind it to another loaded copy. +build_side_module() { + local mod="$1" + local target="Modules/${mod}${EXT_SUFFIX}" + ( + cd "${BUILD}" + env -u INSTALL PREFIX="${PREFIX}" emmake make \ + PYTHON_FOR_BUILD="${HOSTPYTHON}" \ + CROSS_COMPILE=yes \ + BLDSHARED="\$(CC) -sSIDE_MODULE=2 -sEXPORTED_FUNCTIONS=_PyInit_${mod} -sWASM_BIGINT" \ + "${target}" \ + -j"${CPU_COUNT}" + cp "${target}" "${DYNLOAD_DIR}/" + ) +} + # --------------------------------------------------------------------------- # Configure # --------------------------------------------------------------------------- cp Setup.local "${BUILD}/Modules/" +append_side_module_rules "${BUILD}/Modules/Setup.local" ( cd "${BUILD}" @@ -142,6 +250,7 @@ cp Setup.local "${BUILD}/Modules/" BZIP2_LIBS="-L${PREFIX}/lib -lbz2" \ CONFIG_SITE=./Tools/wasm/config.site-wasm${WASM_BITNESS}-emscripten \ READELF=true \ + LLVM_AR="$(command -v emar)" \ emconfigure ./configure \ CFLAGS="${PYTHON_CFLAGS} -I${PREFIX}/include" \ CPPFLAGS="-I${PREFIX}" \ @@ -151,6 +260,7 @@ cp Setup.local "${BUILD}/Modules/" --disable-shared \ --disable-ipv6 \ --enable-big-digits=30 \ + ${LTO_ARGS} \ --host=wasm${WASM_BITNESS}-unknown-emscripten \ --build="$(./config.guess)" \ --prefix="${PREFIX}" \ @@ -196,6 +306,15 @@ cp Setup.local "${BUILD}/Modules/" -j"${CPU_COUNT}" ) +# --------------------------------------------------------------------------- +# Build the side modules (lib/pythonX.Y/lib-dynload/*.so) +# --------------------------------------------------------------------------- +EXT_SUFFIX="$(sed -n 's/^EXT_SUFFIX=[[:space:]]*//p' "${BUILD}/Makefile")" +mkdir -p "${DYNLOAD_DIR}" +for mod in ${SIDE_MODULES}; do + build_side_module "${mod}" +done + # --------------------------------------------------------------------------- # First sysconfigdata generation (matches former "sysconfigdata" make target) # --------------------------------------------------------------------------- diff --git a/recipes/recipes_wasm/python/build_tests.sh b/recipes/recipes_wasm/python/build_tests.sh index b8748df916a..5e6d12febe2 100644 --- a/recipes/recipes_wasm/python/build_tests.sh +++ b/recipes/recipes_wasm/python/build_tests.sh @@ -2,16 +2,35 @@ set -e +# Embeds libpython into a MAIN_MODULE executable and runs python_tests.mjs in +# node and in a browser. +# Usage: build_tests.sh core|full +# core: the env only has python-core. The extension modules of the other +# outputs (python-ssl, python-sqlite3, ...) must not be importable. +# full: the env has python (= core + all extension outputs): everything +# must work, the extension modules are dlopen'ed from lib-dynload. +# The executable is the same in both cases: only the slim core is linked +# (no openssl / sqlite / lzma). +FLAVOR="${1:?usage: build_tests.sh core|full}" +case "$FLAVOR" in + core) CORE_ONLY=true ;; + full) CORE_ONLY=false ;; + *) echo "unknown flavor: $FLAVOR"; exit 1 ;; +esac +echo "==> flavor: $FLAVOR" +echo "export const coreOnly = ${CORE_ONLY};" > test_config.mjs + echo "PY_VER: $PY_VER" PYTHON_LIB="$PREFIX/lib/libpython${PY_VER}.a" -OUT="${OUT:-embed.js}" -OBJ="${OUT%.js}.o" - - - +DYNLOAD_DIR="$PREFIX/lib/python${PY_VER}/lib-dynload" +if [ "$FLAVOR" = "core" ] && ls "$DYNLOAD_DIR"/*.so > /dev/null 2>&1; then + echo "core flavor, but there are extension modules in $DYNLOAD_DIR" + exit 1 +fi +# everything the slim core needs LIBS=( "$PREFIX/lib/python${PY_VER}/static/libexpat.a" "$PREFIX/lib/python${PY_VER}/static/libmpdec.a" @@ -22,12 +41,8 @@ LIBS=( "$PREFIX/lib/python${PY_VER}/static/libHacl_Hash_SHA3.a" "$PREFIX/lib/libbz2.a" "$PREFIX/lib/libz.a" - "$PREFIX/lib/libsqlite3.a" "$PREFIX/lib/libffi.a" "$PREFIX/lib/libzstd.a" - "$PREFIX/lib/libssl.a" - "$PREFIX/lib/libcrypto.a" - "$PREFIX/lib/liblzma.a" "$PYTHON_LIB" ) @@ -72,6 +87,12 @@ emcc \ "${LIBS[@]}" \ -o test_main.js +echo "==> size of the embed executable (MAIN_MODULE=1, slim core)" +ls -l test_main.wasm +if [ -d "$DYNLOAD_DIR" ]; then + echo "==> extension modules in lib-dynload" + ls -l "$DYNLOAD_DIR" +fi node node_test_wrapper.js @@ -87,10 +108,14 @@ if [ "${PYTHON_SKIP_BROWSER_TEST:-0}" = "1" ]; then exit 0 fi +# --use-preload-plugins: the extension modules (lib-dynload/*.so) are compiled +# asynchronously while the page loads, like the embedders do it (the main +# thread must not compile large wasm modules synchronously in dlopen) echo "==> compiling and linking (browser)" emcc \ "${FLAGS[@]}" \ -sENVIRONMENT=web,worker \ + --use-preload-plugins \ --preload-file "$PREFIX/lib/python${PY_VER}@/lib/python${PY_VER}" \ --exclude-file "*__pycache__*" \ --exclude-file "*/lib/python${PY_VER}/test/*" \ diff --git a/recipes/recipes_wasm/python/node_test_wrapper.js b/recipes/recipes_wasm/python/node_test_wrapper.js index d76ad992951..bfd7a392b4d 100644 --- a/recipes/recipes_wasm/python/node_test_wrapper.js +++ b/recipes/recipes_wasm/python/node_test_wrapper.js @@ -2,7 +2,9 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import createModule from "./test_main.js"; -import { pythonTests } from "./python_tests.mjs"; +import { pythonTests, testCode } from "./python_tests.mjs"; +// written by build_tests.sh: is this a core-only env (no extension outputs)? +import { coreOnly } from "./test_config.mjs"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -26,6 +28,8 @@ function ensureVirtualFSPathForFile(Module, fsPath) { } } +// copy the python files and the extension modules (lib-dynload/*.so, side +// modules that python dlopen's on import) into the emscripten FS function copyPyFiles(Module, hostDir, fsDir) { for (const entry of fs.readdirSync(hostDir, { withFileTypes: true })) { const hostPath = path.join(hostDir, entry.name); @@ -33,7 +37,7 @@ function copyPyFiles(Module, hostDir, fsDir) { if (entry.isDirectory()) { Module.FS.mkdirTree(fsPath); copyPyFiles(Module, hostPath, fsPath); - } else if (entry.isFile() && entry.name.endsWith(".py")) { + } else if (entry.isFile() && (entry.name.endsWith(".py") || entry.name.endsWith(".so"))) { ensureVirtualFSPathForFile(Module, fsPath); Module.FS.writeFile(fsPath, fs.readFileSync(hostPath)); } @@ -146,7 +150,7 @@ for (const test of pythonTests) { continue; } console.log(`=== ${test.name}`); - const ret = Number(Module.ccall('run_python', 'number', ['string'], [test.code])); + const ret = Number(Module.ccall('run_python', 'number', ['string'], [testCode(test, coreOnly)])); if (ret !== 0) { failed.push(test.name); } @@ -154,4 +158,4 @@ for (const test of pythonTests) { if (failed.length > 0) { throw new Error(`python tests failed: ${failed.join(", ")}`); } -console.log(`all ${pythonTests.length} python tests passed`); +console.log(`all ${pythonTests.length} python tests passed (${coreOnly ? "core-only env" : "full env"})`); diff --git a/recipes/recipes_wasm/python/python_tests.mjs b/recipes/recipes_wasm/python/python_tests.mjs index b0f07a0038d..c2424b44795 100644 --- a/recipes/recipes_wasm/python/python_tests.mjs +++ b/recipes/recipes_wasm/python/python_tests.mjs @@ -3,6 +3,28 @@ // Each snippet runs in a fresh interpreter (run_python: Py_Initialize .. // Py_FinalizeEx) and must not raise. `pointerSize` (optional): only run on // wasm32 (4) / wasm64 (8). +// `requires` (optional): extension modules that are not builtin modules of +// the python core but side modules (lib-dynload/*.so) of their own package +// (python-ssl, python-sqlite3, ...). With all packages installed the test +// runs as it is; in a core-only env these modules must not be importable. + +// The code to run for a test: the test itself, or (core-only env and the test +// requires extension modules) a check that those modules are missing. +export function testCode(test, coreOnly) { + if (!coreOnly || !test.requires) { + return test.code; + } + return ` +import importlib +for name in ${JSON.stringify(test.requires)}: + try: + importlib.import_module(name) + except ImportError as e: + print("not in the core, as expected:", e) + else: + raise AssertionError(name + " must not be importable in a core-only env") +`; +} export const pythonTests = [ { @@ -136,13 +158,12 @@ assert unicodedata.normalize("NFD", "é") == "e\\u0301" `, }, { - name: "compression (zlib / bz2 / lzma / zstd)", + name: "compression (zlib / bz2 / zstd)", code: ` -import zlib, bz2, lzma, gzip, zipfile, tarfile, io +import zlib, bz2, gzip, zipfile, tarfile, io data = b"pyjs " * 1000 assert zlib.decompress(zlib.compress(data)) == data assert bz2.decompress(bz2.compress(data)) == data -assert lzma.decompress(lzma.compress(data)) == data assert gzip.decompress(gzip.compress(data)) == data from compression import zstd assert zstd.decompress(zstd.compress(data)) == data @@ -152,12 +173,39 @@ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: with zipfile.ZipFile(buf) as z: assert z.read("a.txt") == data buf = io.BytesIO() +with tarfile.open(fileobj=buf, mode="w:bz2") as t: + info = tarfile.TarInfo("a.txt"); info.size = len(data) + t.addfile(info, io.BytesIO(data)) +buf.seek(0) +with tarfile.open(fileobj=buf, mode="r:bz2") as t: + assert t.extractfile("a.txt").read() == data +`, + }, + { + name: "lzma (python-lzma)", + requires: ["_lzma"], + code: ` +import lzma, tarfile, io +data = b"pyjs " * 1000 +assert lzma.decompress(lzma.compress(data)) == data +buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w:xz") as t: info = tarfile.TarInfo("a.txt"); info.size = len(data) t.addfile(info, io.BytesIO(data)) buf.seek(0) with tarfile.open(fileobj=buf, mode="r:xz") as t: assert t.extractfile("a.txt").read() == data +`, + }, + { + // these import ssl / lzma / _hashlib optionally: they must work in a + // core-only env too + name: "stdlib modules with optional extension modules", + code: ` +import http.client, urllib.request, urllib.parse, asyncio, tarfile, zipfile, shutil +import hashlib, hmac, uuid, email.message, logging.handlers, decimal, fractions +assert urllib.parse.urlparse("https://example.org/a?b=1").netloc == "example.org" +assert len(str(uuid.uuid4())) == 36 `, }, { @@ -174,12 +222,49 @@ assert len(secrets.token_bytes(16)) == 16 `, }, { - name: "ssl", + name: "ssl (python-ssl)", + requires: ["_ssl"], code: ` -import ssl +import ssl, _ssl +assert _ssl.__file__.endswith(".so"), _ssl.__file__ # a side module, not builtin assert ssl.OPENSSL_VERSION.startswith("OpenSSL"), ssl.OPENSSL_VERSION ctx = ssl.create_default_context() assert ctx.verify_mode == ssl.CERT_REQUIRED +assert len(ssl.RAND_bytes(16)) == 16 +# a TLS handshake start in memory (exercises libssl, not only the bindings) +incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO() +obj = ctx.wrap_bio(incoming, outgoing, server_hostname="example.org") +try: + obj.do_handshake() +except ssl.SSLWantReadError: + pass +assert outgoing.read()[:1] == b"\\x16" # TLS handshake record (ClientHello) +`, + }, + { + name: "cjk codecs (python-cjkcodecs)", + requires: ["_multibytecodec", "_codecs_cn", "_codecs_hk", "_codecs_iso2022", "_codecs_jp", "_codecs_kr", "_codecs_tw"], + code: ` +import _codecs_jp +assert _codecs_jp.__file__.endswith(".so"), _codecs_jp.__file__ +for text, encoding in [("日本語", "shift_jis"), ("日本語", "euc_jp"), ("日本語", "iso2022_jp"), + ("中文", "gb2312"), ("中文", "gbk"), ("中文", "big5"), ("中文", "big5hkscs"), + ("한국어", "euc_kr")]: + assert text.encode(encoding).decode(encoding) == text, encoding +assert "日本語".encode("shift_jis") == b"\\x93\\xfa\\x96\\x7b\\x8c\\xea" +`, + }, + { + name: "test modules (python-test-modules)", + requires: ["xxsubtype", "_xxtestfuzz", "_testbuffer", "_testinternalcapi", "_testcapi", "_testlimitedcapi", "_testclinic", "_testclinic_limited"], + code: ` +import xxsubtype, _xxtestfuzz, _testbuffer, _testinternalcapi, _testcapi, _testlimitedcapi +import _testclinic, _testclinic_limited +assert _testcapi.__file__.endswith(".so"), _testcapi.__file__ +assert _testcapi.INT_MAX == 2**31 - 1 +assert _testinternalcapi.get_recursion_depth() >= 1 +assert bytes(_testbuffer.ndarray([1, 2, 3], shape=[3], format="B")) == b"\\x01\\x02\\x03" +assert xxsubtype.spamlist([1]).getstate() == 0 `, }, { @@ -192,9 +277,11 @@ assert xml.dom.minidom.parseString("").documentElement.tagName == "a" `, }, { - name: "sqlite3", + name: "sqlite3 (python-sqlite3)", + requires: ["_sqlite3"], code: ` -import sqlite3 +import sqlite3, _sqlite3 +assert _sqlite3.__file__.endswith(".so"), _sqlite3.__file__ # a side module, not builtin con = sqlite3.connect(":memory:") con.execute("create table t (a integer, b text)") con.executemany("insert into t values (?, ?)", [(1, "x"), (2, "y")]) diff --git a/recipes/recipes_wasm/python/recipe.yaml b/recipes/recipes_wasm/python/recipe.yaml index aabdb03da5f..ca4d67b4d68 100644 --- a/recipes/recipes_wasm/python/recipe.yaml +++ b/recipes/recipes_wasm/python/recipe.yaml @@ -3,8 +3,10 @@ context: name: python ver2: '3.14' ver2nd: ${{ version | version_to_buildstring }} - build_number: 8 + build_number: 9 abi_tag: cp${{ ver2nd }} + # where the extension modules built as emscripten side modules are installed + dynload: lib/python${{ ver2 }}/lib-dynload build: number: ${{ build_number }} @@ -48,6 +50,32 @@ source: - patches/0013-remove_not_needed_emscripten_syscalls.patch - patches/0015-emit-abi-extension-suffix-for-static-builds.patch +# Outputs +# ------- +# The interpreter is split at the builtin-module line, so that an embedder +# (pyjs, xeus-python, ...: an emscripten MAIN_MODULE linking libpythonX.Y.a, +# which keeps every symbol of every linked archive) only has to link what the +# core needs: +# +# libpython-static libpythonX.Y.a + headers: the slim core. openssl, +# sqlite, lzma, the CJK codecs and the test modules are +# not builtin modules anymore. +# python-core the stdlib (as `python` before the split) +# python-ssl _ssl (+ libssl / libcrypto, linked statically) +# python-sqlite3 _sqlite3 (+ libsqlite3) +# python-lzma _lzma (+ liblzma) +# python-cjkcodecs _multibytecodec, _codecs_{cn,hk,iso2022,jp,kr,tw} +# python-test-modules _testcapi, _testinternalcapi, ... (CPython's own tests) +# each: emscripten side modules in lib-dynload, python +# dlopen's them on import (see SIDE_MODULES in build.sh) +# python meta package: python-core + all of the above except +# python-test-modules (only CPython's own tests use +# those: install python-test-modules explicitly) +# python-dev meta package: python + libpython-static + pkg-config +# +# Envs with `python` behave as before. A slim env has `python-core` plus the +# extension packages it needs; without e.g. python-ssl, `import ssl` raises +# ModuleNotFoundError: No module named '_ssl'. outputs: - staging: name: python-build @@ -135,12 +163,15 @@ outputs: - libzlib-static run: - python_abi ${{ ver2 }}.* *_${{ abi_tag }} - - ${{ pin_compatible("libopenssl-static", lower_bound='x.x', upper_bound='x.x') }} + # The static libraries libpythonX.Y.a needs at link time: whoever links + # it (the embedder) needs these archives too, so they are run + # dependencies of this package (the one with the .a; python-core has + # nothing to link, the side modules contain their libraries). + # openssl, lzma and sqlite are not needed: their modules are side + # modules now (python-ssl, ...); _uuid is disabled (Setup.local). + # Embedders that still list them on their link line need a rebuild. - ${{ pin_compatible("libffi-static", lower_bound='x.x', upper_bound='x.x') }} - - ${{ pin_compatible("liblzma-static", lower_bound='x', upper_bound='x') }} - ${{ pin_compatible("zstd-static", lower_bound='x.x', upper_bound='x.x') }} - - ${{ pin_compatible("libuuid-static", lower_bound='x', upper_bound='x') }} - - ${{ pin_compatible("libsqlite-static", lower_bound='x', upper_bound='x') }} - ${{ pin_compatible("libbzip2-static", lower_bound='x.x', upper_bound='x.x') }} - ${{ pin_compatible("libzlib-static", lower_bound='x.x', upper_bound='x.x') }} run_exports: @@ -169,13 +200,34 @@ outputs: # -- begin potential AI nonsense # Keeping -sUSE_PTHREADS=0 guarantees Emscripten binds the C Python pthread calls to single-threaded stubs. # -- end potential AI nonsense - - generic-testing --allow-pthread + - generic-testing requirements: build: - generic-testing + # the slim core alone: link it without openssl / sqlite / lzma and run + # the python tests in a core-only env. Node only: in this env there is + # no side module to load, and the browser-specific part (loading side + # modules from lib-dynload, compiled while the page loads) is what the + # browser run of the full test (python-dev, below) covers. A browser + # run here would test the same core code again, for the cost of + # installing playwright + a browser and a second link. + - script: + - PY_VER=${{ ver2 }} PYTHON_SKIP_BROWSER_TEST=1 bash build_tests.sh core + requirements: + build: + - ${{ compiler("c") }} + - nodejs + run: + - ${{ pin_subpackage('python-core', exact=True) }} + files: + recipe: + - build_tests.sh + - test_main.cpp + - node_test_wrapper.js + - python_tests.mjs - package: - name: python + name: python-core version: ${{ version }} inherit: python-build build: @@ -193,6 +245,8 @@ outputs: - "**/*.h" - '**/pkgconfig/**' - '**/*.pc' + # the extension modules have their own outputs + - ${{ dynload }}/** python: skip_pyc_compilation: @@ -201,6 +255,183 @@ outputs: requirements: run: - python_abi ${{ ver2 }}.* *_${{ abi_tag }} + # pyjs < 6 (and so xeus-python built on it) bootstraps the env by + # unpacking only the package named `python` before starting the + # interpreter: with the stdlib in python-core it finds none and fails. + # The solver gives those envs the unsplit python (build 8) instead. + run_constraints: + - pyjs >=6 + run_exports: + weak: + - python_abi ${{ ver2 }}.* *_${{ abi_tag }} + + tests: + - script: + - test ! -f $PREFIX/lib/libpython${{ver2}}.a + - test ! -f $PREFIX/include/python${{ver2}}/Python.h + - test ! -f $PREFIX/lib/pkgconfig/python-${{ver2}}.pc + - test -f $PREFIX/lib/python${{ver2}}/enum.py + - test -f $PREFIX/lib/python${{ver2}}/ast.py + - test -f $PREFIX/lib/python${{ver2}}/ssl.py + - test ! -e $PREFIX/${{ dynload }} + - generic-testing + requirements: + build: + - generic-testing + + # --- extension modules (emscripten side modules) --------------------------- + # Functional tests: the python-dev test below imports and uses all of them. + + - package: + name: python-ssl + version: ${{ version }} + inherit: python-build + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + script: echo "nothing to do here, we take all content from the python-build package" + files: + include: + - ${{ dynload }}/_ssl.*.so + requirements: + run: + - ${{ pin_subpackage('python-core', exact=True) }} + tests: + - package_contents: + files: + - ${{ dynload }}/_ssl.*.so + - script: generic-testing + requirements: + build: + - generic-testing + + - package: + name: python-sqlite3 + version: ${{ version }} + inherit: python-build + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + script: echo "nothing to do here, we take all content from the python-build package" + files: + include: + - ${{ dynload }}/_sqlite3.*.so + requirements: + run: + - ${{ pin_subpackage('python-core', exact=True) }} + tests: + - package_contents: + files: + - ${{ dynload }}/_sqlite3.*.so + - script: generic-testing + requirements: + build: + - generic-testing + + - package: + name: python-lzma + version: ${{ version }} + inherit: python-build + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + script: echo "nothing to do here, we take all content from the python-build package" + files: + include: + - ${{ dynload }}/_lzma.*.so + requirements: + run: + - ${{ pin_subpackage('python-core', exact=True) }} + tests: + - package_contents: + files: + - ${{ dynload }}/_lzma.*.so + - script: generic-testing + requirements: + build: + - generic-testing + + - package: + name: python-cjkcodecs + version: ${{ version }} + inherit: python-build + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + script: echo "nothing to do here, we take all content from the python-build package" + files: + include: + - ${{ dynload }}/_multibytecodec.*.so + - ${{ dynload }}/_codecs_*.so + requirements: + run: + - ${{ pin_subpackage('python-core', exact=True) }} + tests: + - package_contents: + files: + - ${{ dynload }}/_multibytecodec.*.so + - ${{ dynload }}/_codecs_cn.*.so + - ${{ dynload }}/_codecs_hk.*.so + - ${{ dynload }}/_codecs_iso2022.*.so + - ${{ dynload }}/_codecs_jp.*.so + - ${{ dynload }}/_codecs_kr.*.so + - ${{ dynload }}/_codecs_tw.*.so + - script: generic-testing + requirements: + build: + - generic-testing + + - package: + name: python-test-modules + version: ${{ version }} + inherit: python-build + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + script: echo "nothing to do here, we take all content from the python-build package" + files: + include: + - ${{ dynload }}/_test*.so + - ${{ dynload }}/_xxtestfuzz.*.so + - ${{ dynload }}/xxsubtype.*.so + requirements: + run: + - ${{ pin_subpackage('python-core', exact=True) }} + tests: + - package_contents: + files: + - ${{ dynload }}/_testcapi.*.so + - ${{ dynload }}/_testinternalcapi.*.so + - ${{ dynload }}/_testlimitedcapi.*.so + - ${{ dynload }}/_testbuffer.*.so + - ${{ dynload }}/_testclinic.*.so + - ${{ dynload }}/_testclinic_limited.*.so + - ${{ dynload }}/_xxtestfuzz.*.so + - ${{ dynload }}/xxsubtype.*.so + - script: generic-testing + requirements: + build: + - generic-testing + + # --- meta packages --------------------------------------------------------- + + # the stdlib with all extension modules, as before the split (no files of + # its own), but without python-test-modules (not dragged into every env) + - package: + name: python + version: ${{ version }} + build: + string: h_${{ hash }}_${{ build_number }}_${{ abi_tag }} + # (no build tree here: only CPython's LICENSE, the files are in the others) + about: + license: Python-2.0 + license_file: LICENSE + requirements: + run: + - python_abi ${{ ver2 }}.* *_${{ abi_tag }} + - ${{ pin_subpackage('python-core', exact=True) }} + - ${{ pin_subpackage('python-ssl', exact=True) }} + - ${{ pin_subpackage('python-sqlite3', exact=True) }} + - ${{ pin_subpackage('python-lzma', exact=True) }} + - ${{ pin_subpackage('python-cjkcodecs', exact=True) }} + # (see python-core) + run_constraints: + - pyjs >=6 run_exports: weak: - python_abi ${{ ver2 }}.* *_${{ abi_tag }} @@ -212,6 +443,11 @@ outputs: - test ! -f $PREFIX/lib/pkgconfig/python-${{ver2}}.pc - test -f $PREFIX/lib/python${{ver2}}/enum.py - test -f $PREFIX/lib/python${{ver2}}/ast.py + - ls $PREFIX/${{ dynload }}/_ssl.*.so + - ls $PREFIX/${{ dynload }}/_sqlite3.*.so + - ls $PREFIX/${{ dynload }}/_lzma.*.so + - ls $PREFIX/${{ dynload }}/_codecs_jp.*.so + - test ! -e $PREFIX/${{ dynload }}/_testcapi.*.so - generic-testing requirements: build: @@ -246,16 +482,24 @@ outputs: - test -f $PREFIX/lib/libpython${{ver2}}.a - test -f $PREFIX/lib/python${{ver2}}/enum.py - test -f $PREFIX/lib/python${{ver2}}/ast.py + # everything: the slim core + all extension modules loaded from + # lib-dynload, in node and in a browser (the test modules too: not part + # of the `python` meta package, so requested here) - script: - - build_tests.sh + - PY_VER=${{ ver2 }} bash build_tests.sh full requirements: + run: + - ${{ pin_subpackage('python-test-modules', exact=True) }} build: - ${{ compiler("c") }} - make - python=${{ver2}} - nodejs - - playwright - - playwright-python + # the node driver and its python API with the same version (a + # mismatch fails the browser launch: "BrowserType.launch: timeout: + # expected float, got undefined"), as in pytester + - playwright 1.62.* + - playwright-python 1.62.* files: recipe: - build_tests.sh @@ -268,7 +512,15 @@ outputs: about: license: Python-2.0 - license_file: LICENSE + # LICENSE: CPython itself; Doc/license.rst also has the licenses of the + # libraries CPython bundles and compiles in (expat, mpdecimal, HACL*, ...). + # (build.sh moves the source tree to build//Python-/) + license_file: + - LICENSE + - build/${{ version }}/Python-${{ version }}/Doc/license.rst + - build/${{ version }}/Python-${{ version }}/Modules/expat/COPYING + # (HACL* has its license only in its source files' headers: copied here) + - HACL_LICENSE.txt summary: General purpose programming language description: | Python is a widely used high-level, general-purpose, interpreted, dynamic diff --git a/recipes/recipes_wasm/regex/recipe.yaml b/recipes/recipes_wasm/regex/recipe.yaml index e7c2aef55e3..6998bcfafd3 100644 --- a/recipes/recipes_wasm/regex/recipe.yaml +++ b/recipes/recipes_wasm/regex/recipe.yaml @@ -11,7 +11,7 @@ source: sha256: f7b43acb2c46fb2cd506965b2d9cf4c5e64c9c612bac26c1187933c7296bf08c build: - number: 1 + number: 2 files: exclude: diff --git a/recipes/recipes_wasm/sqlite/LICENSE.md b/recipes/recipes_wasm/sqlite/LICENSE.md new file mode 100644 index 00000000000..8d95a46a85c --- /dev/null +++ b/recipes/recipes_wasm/sqlite/LICENSE.md @@ -0,0 +1,9 @@ +SQLite is in the public domain (https://www.sqlite.org/copyright.html). +The notice at the top of its source files (sqlite3.c, sqlite3.h): + + The author disclaims copyright to this source code. In place of + a legal notice, here is a blessing: + + May you do good and not evil. + May you find forgiveness for yourself and forgive others. + May you share freely, never taking more than you give. diff --git a/recipes/recipes_wasm/sqlite/build.sh b/recipes/recipes_wasm/sqlite/build.sh index c09b5c7a887..b2b750c74ad 100644 --- a/recipes/recipes_wasm/sqlite/build.sh +++ b/recipes/recipes_wasm/sqlite/build.sh @@ -1,27 +1,50 @@ -#!/bin/bash ddd - -echo "#!/usr/bin/env bash" > ldconfig -chmod +x ldconfig -export PATH=${PWD}:$PATH - - -echo "HOST" $HOST -echo "BUILD" $BUILD - - -emconfigure ./configure --prefix=${PREFIX} \ - --build=${BUILD} \ - --host=none \ - --disable-threadsafe \ - --disable-shared \ - --disable-static-shell \ - --disable-dependency-tracking \ - --disable-tcl \ - CFLAGS="${CFLAGS} -DSQLITE_ENABLE_COLUMN_METADATA=1 -I${PREFIX}/include -fPIC -sUSE_PTHREADS=0" - LDFLAGS="${LDFLAGS} -L${PREFIX}/lib -sUSE_PTHREADS=0" \ - CPPFLAGS="-DSQLITE_OMIT_POPEN"; \ - - -emmake make -j${CPU_COUNT} ${VERBOSE_AT} -emmake make install - +#!/bin/bash +set -e + +# Built from the amalgamation (one sqlite3.c, see recipe.yaml): no configure, +# no tcl / code generators needed, just emcc + emar. +# +# -fvisibility=hidden: the sqlite3_* symbols stay local to whatever links this +# static lib. Otherwise every side module using sqlite (python's _sqlite3, +# apsw, ...) exports the whole sqlite3_* API: the extension loader's table of +# pointers to all API functions (sqlite3Apis) makes them address-taken, and +# in a PIC side module address-taken default-visibility functions go through +# the GOT and are exported. The dynamic linker then binds them to another +# loaded copy of sqlite (e.g. one in the main module), whose state the module +# never initialized ("null function" trap in sqlite3_close). +# +# The options are the ones the configure build had: no threads, column +# metadata, math functions, JSON (default). +SQLITE_FLAGS=( + -DSQLITE_THREADSAFE=0 + -DSQLITE_ENABLE_COLUMN_METADATA=1 + -DSQLITE_ENABLE_MATH_FUNCTIONS + -DSQLITE_OMIT_POPEN + -DHAVE_USLEEP=1 + -DHAVE_LOCALTIME_R=1 + -DHAVE_GMTIME_R=1 + -DHAVE_FDATASYNC=1 + -DHAVE_STRCHRNUL=1 + -DHAVE_MALLOC_USABLE_SIZE=1 +) + +emcc ${CFLAGS} -O2 -fPIC -fvisibility=hidden "${SQLITE_FLAGS[@]}" -c sqlite3.c -o sqlite3.o +emar rcs libsqlite3.a sqlite3.o + +mkdir -p "${PREFIX}/lib/pkgconfig" "${PREFIX}/include" +cp libsqlite3.a "${PREFIX}/lib/" +cp sqlite3.h sqlite3ext.h "${PREFIX}/include/" + +cat > "${PREFIX}/lib/pkgconfig/sqlite3.pc" << EOF +prefix=${PREFIX} +exec_prefix=\${prefix} +libdir=\${exec_prefix}/lib +includedir=\${prefix}/include + +Name: SQLite +Description: SQL database engine +Version: ${PKG_VERSION} +Libs: -L\${libdir} -lsqlite3 +Libs.private: +Cflags: -I\${includedir} +EOF diff --git a/recipes/recipes_wasm/sqlite/recipe.yaml b/recipes/recipes_wasm/sqlite/recipe.yaml index 16a5556920e..a4b2b38c32e 100644 --- a/recipes/recipes_wasm/sqlite/recipe.yaml +++ b/recipes/recipes_wasm/sqlite/recipe.yaml @@ -1,23 +1,25 @@ context: version: 3.47.2 + # the amalgamation's file name: 3.47.2 -> 3470200, and its release year + version_code: 3470200 + year: 2024 package: name: libsqlite-static version: ${{ version }} +# the amalgamation (sqlite3.c + headers): builds without tcl / code generators source: - url: https://github.com/sqlite/sqlite/archive/refs/tags/version-${{ version }}.tar.gz - sha256: 2d966d1b37b4035e2b86fff4ee0260b6a9c12afd1fdae54a783814de5eb62929 + url: https://www.sqlite.org/${{ year }}/sqlite-autoconf-${{ version_code }}.tar.gz + sha256: f1b2ee412c28d7472bc95ba996368d6f0cdcf00362affdadb27ed286c179540b build: - number: 4 + number: 5 requirements: build: - ${{ compiler('c') }} - - make - - libtool host: - zlib-static run: