icpp-binaryen 116.0.0__py3-none-macosx_11_0_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ """icpp-binaryen: cffi bindings over Binaryen's C API, with the official
2
+ Binaryen shared library bundled per platform.
3
+
4
+ Public API — all of it:
5
+
6
+ from icpp_binaryen import ffi, lib # raw escape hatch
7
+ from icpp_binaryen import Module # load / optimize / emit / write
8
+ from icpp_binaryen import fix_globals_limit # the IC globals-limit fix
9
+ from icpp_binaryen import BINARYEN_VERSION # int, from bundled version.txt
10
+ """
11
+
12
+ from icpp_binaryen.version import __version__
13
+ from icpp_binaryen._lib import BINARYEN_VERSION, ffi, lib
14
+ from icpp_binaryen.module import Module
15
+ from icpp_binaryen.fix_globals import GlobalsFixReport, fix_globals_limit
16
+
17
+ __all__ = [
18
+ "BINARYEN_VERSION",
19
+ "GlobalsFixReport",
20
+ "Module",
21
+ "__version__",
22
+ "ffi",
23
+ "fix_globals_limit",
24
+ "lib",
25
+ ]
icpp_binaryen/_cdef.py ADDED
@@ -0,0 +1,40 @@
1
+ """Hand-curated cffi cdef: the subset of binaryen-c.h that the public API needs.
2
+
3
+ Signatures are verified against the bundled Binaryen version's binaryen-c.h
4
+ (the header ships in every official release tarball). Do NOT auto-translate
5
+ the full header — add declarations one by one, only when a new API needs them.
6
+ """
7
+
8
+ CDEF = """
9
+ typedef uint32_t BinaryenIndex;
10
+ typedef uint32_t BinaryenExternalKind;
11
+ typedef struct BinaryenModule *BinaryenModuleRef;
12
+ typedef struct BinaryenExport *BinaryenExportRef;
13
+
14
+ BinaryenExternalKind BinaryenExternalGlobal(void);
15
+
16
+ BinaryenModuleRef BinaryenModuleRead(char *input, size_t inputSize);
17
+ void BinaryenModuleDispose(BinaryenModuleRef module);
18
+ bool BinaryenModuleValidate(BinaryenModuleRef module);
19
+ void BinaryenModuleOptimize(BinaryenModuleRef module);
20
+ void BinaryenSetOptimizeLevel(int level);
21
+ void BinaryenSetShrinkLevel(int level);
22
+
23
+ BinaryenIndex BinaryenGetNumExports(BinaryenModuleRef module);
24
+ BinaryenExportRef BinaryenGetExportByIndex(BinaryenModuleRef module,
25
+ BinaryenIndex index);
26
+ BinaryenExternalKind BinaryenExportGetKind(BinaryenExportRef export_);
27
+ const char *BinaryenExportGetName(BinaryenExportRef export_);
28
+ void BinaryenRemoveExport(BinaryenModuleRef module, const char *externalName);
29
+
30
+ BinaryenIndex BinaryenGetNumGlobals(BinaryenModuleRef module);
31
+
32
+ typedef struct BinaryenModuleAllocateAndWriteResult {
33
+ void *binary;
34
+ size_t binaryBytes;
35
+ char *sourceMap;
36
+ } BinaryenModuleAllocateAndWriteResult;
37
+ BinaryenModuleAllocateAndWriteResult
38
+ BinaryenModuleAllocateAndWrite(BinaryenModuleRef module,
39
+ const char *sourceMapUrl);
40
+ """
icpp_binaryen/_lib.py ADDED
@@ -0,0 +1,58 @@
1
+ """Load the bundled libbinaryen with cffi in ABI mode (ffi.dlopen).
2
+
3
+ No compiled extension module: the same wheel works for every supported
4
+ Python version on its platform.
5
+ """
6
+
7
+ import platform
8
+ from pathlib import Path
9
+ from typing import Any, cast
10
+
11
+ from cffi import FFI
12
+
13
+ from icpp_binaryen._cdef import CDEF
14
+ from icpp_binaryen.version import __version__
15
+
16
+ LIB_DIR = Path(__file__).parent / "lib"
17
+
18
+ ffi = FFI()
19
+ ffi.cdef(CDEF)
20
+
21
+
22
+ def _lib_path() -> Path:
23
+ system = platform.system()
24
+ if system == "Darwin":
25
+ return LIB_DIR / "libbinaryen.dylib"
26
+ if system == "Linux":
27
+ return LIB_DIR / "libbinaryen.so"
28
+ raise ImportError(
29
+ f"icpp-binaryen does not support platform '{system}'. "
30
+ "Supported: macOS and Linux (on Windows, use WSL)."
31
+ )
32
+
33
+
34
+ _path = _lib_path()
35
+ if not _path.exists():
36
+ raise ImportError(
37
+ f"icpp-binaryen: bundled library not found at {_path}. "
38
+ "In a source checkout, run `make get-binaryen` first."
39
+ )
40
+
41
+ lib = cast(Any, ffi.dlopen(str(_path)))
42
+
43
+ BINARYEN_VERSION: int = int(
44
+ (LIB_DIR / "version.txt").read_text(encoding="utf-8").strip()
45
+ )
46
+ _expected = int(__version__.split(".", maxsplit=1)[0])
47
+ if BINARYEN_VERSION != _expected:
48
+ raise ImportError(
49
+ f"icpp-binaryen {__version__} expects bundled Binaryen {_expected}, "
50
+ f"but lib/version.txt says {BINARYEN_VERSION}"
51
+ )
52
+
53
+ # Binaryen's Allocate-and-write APIs return malloc'ed buffers that the caller
54
+ # must free. In ABI mode free() is not a libbinaryen symbol, so take it from
55
+ # the process' libc.
56
+ _ffi_libc = FFI()
57
+ _ffi_libc.cdef("void free(void *ptr);")
58
+ libc = cast(Any, _ffi_libc.dlopen(None))
@@ -0,0 +1,75 @@
1
+ """The one high-level entry point: the IC globals-limit fix.
2
+
3
+ The Internet Computer rejects a wasm module with more than 1000 *defined*
4
+ globals (install error IC0505). A wasi-sdk build of a large C++ project blows
5
+ past this. The fix: remove every export of kind global (an exported global is
6
+ otherwise kept alive), then run Binaryen's optimizer, which drops the now-dead
7
+ globals.
8
+ """
9
+
10
+ import shutil
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Union
14
+
15
+ from icpp_binaryen.module import Module
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class GlobalsFixReport:
20
+ """Before/after counts of a fix_globals_limit run."""
21
+
22
+ wasm_path: Path
23
+ backup_path: Path
24
+ exports_before: int
25
+ exports_after: int
26
+ globals_before: int
27
+ globals_after: int
28
+
29
+ def summary(self) -> str:
30
+ """The 4-line summary optimize_wasm.py prints today."""
31
+ return (
32
+ f"Exports before optimization: {self.exports_before}\n"
33
+ f"Exports after optimization: {self.exports_after}\n"
34
+ f"Globals before optimization: {self.globals_before}\n"
35
+ f"Globals after optimization: {self.globals_after}"
36
+ )
37
+
38
+
39
+ def fix_globals_limit(
40
+ wasm_path: Union[Path, str], *, backup_suffix: str = "_before_opt"
41
+ ) -> GlobalsFixReport:
42
+ """Rewrite the wasm at wasm_path in place, keeping a backup copy.
43
+
44
+ The backup (default `<stem>_before_opt.wasm`) is a byte-identical copy of
45
+ the input: the optimize pass strips the wasm name section, and the backup
46
+ is what keeps named backtraces possible (e.g. under wasmtime).
47
+ """
48
+ path = Path(wasm_path).resolve()
49
+ backup_path = path.with_name(path.stem + backup_suffix + path.suffix)
50
+ shutil.copy(path, backup_path)
51
+
52
+ with Module.load(path) as module:
53
+ exports_before = module.num_exports
54
+ globals_before = module.num_globals
55
+
56
+ # Two passes: removing while iterating would invalidate the indices.
57
+ for name in module.global_export_names():
58
+ module.remove_export(name)
59
+
60
+ # Levels 0/0: this is an export-strip + dead-global removal, not a
61
+ # size optimization.
62
+ module.optimize(shrink_level=0, optimize_level=0)
63
+
64
+ exports_after = module.num_exports
65
+ globals_after = module.num_globals
66
+ module.write(path)
67
+
68
+ return GlobalsFixReport(
69
+ wasm_path=path,
70
+ backup_path=backup_path,
71
+ exports_before=exports_before,
72
+ exports_after=exports_after,
73
+ globals_before=globals_before,
74
+ globals_after=globals_after,
75
+ )
Binary file
@@ -0,0 +1 @@
1
+ 116
@@ -0,0 +1,117 @@
1
+ """Pythonic wrapper around the raw Binaryen C API (read / inspect / optimize /
2
+ emit). The raw `ffi` / `lib` pair stays available as the escape hatch."""
3
+
4
+ from pathlib import Path
5
+ from types import TracebackType
6
+ from typing import Any, Optional, Union
7
+
8
+ from icpp_binaryen._lib import ffi, lib, libc
9
+
10
+
11
+ class Module:
12
+ """A Binaryen module handle."""
13
+
14
+ def __init__(self, ref: Any, keepalive: Any = None) -> None:
15
+ # keepalive holds the cffi buffer BinaryenModuleRead parsed from:
16
+ # the C API takes a non-const char* and the buffer must outlive the
17
+ # module.
18
+ self._ref: Any = ref
19
+ self._keepalive = keepalive
20
+
21
+ @classmethod
22
+ def read(cls, wasm_bytes: bytes) -> "Module":
23
+ """Construct a Module from wasm bytes."""
24
+ buf = ffi.new("char[]", wasm_bytes)
25
+ ref = lib.BinaryenModuleRead(buf, len(wasm_bytes))
26
+ if ref == ffi.NULL:
27
+ raise ValueError("BinaryenModuleRead failed to parse the wasm")
28
+ return cls(ref, keepalive=buf)
29
+
30
+ @classmethod
31
+ def load(cls, wasm_path: Union[Path, str]) -> "Module":
32
+ """Construct a Module from a wasm file."""
33
+ return cls.read(Path(wasm_path).read_bytes())
34
+
35
+ @property
36
+ def ref(self) -> Any:
37
+ """The raw BinaryenModuleRef, for use with `lib` directly."""
38
+ return self._ref
39
+
40
+ @property
41
+ def num_exports(self) -> int:
42
+ """Number of exports of any kind."""
43
+ return int(lib.BinaryenGetNumExports(self._ref))
44
+
45
+ @property
46
+ def num_globals(self) -> int:
47
+ """Number of *defined* globals (what the IC's 1000 limit counts)."""
48
+ return int(lib.BinaryenGetNumGlobals(self._ref))
49
+
50
+ def global_export_names(self) -> list[str]:
51
+ """Names of all exports of kind global."""
52
+ kind_global = lib.BinaryenExternalGlobal()
53
+ names: list[str] = []
54
+ for i in range(self.num_exports):
55
+ export_ref = lib.BinaryenGetExportByIndex(self._ref, i)
56
+ if lib.BinaryenExportGetKind(export_ref) == kind_global:
57
+ name = ffi.string(lib.BinaryenExportGetName(export_ref))
58
+ if isinstance(name, bytes):
59
+ name = name.decode("utf-8")
60
+ names.append(name)
61
+ return names
62
+
63
+ def remove_export(self, external_name: str) -> None:
64
+ """Remove the export with the given external name."""
65
+ lib.BinaryenRemoveExport(self._ref, external_name.encode("utf-8"))
66
+
67
+ def optimize(self, shrink_level: int, optimize_level: int) -> None:
68
+ """Run Binaryen's default optimization pipeline at the given levels.
69
+
70
+ Note: the optimizer strips the wasm name section — keep a copy of the
71
+ input when named backtraces matter.
72
+ """
73
+ lib.BinaryenSetShrinkLevel(shrink_level)
74
+ lib.BinaryenSetOptimizeLevel(optimize_level)
75
+ lib.BinaryenModuleOptimize(self._ref)
76
+
77
+ def validate(self) -> bool:
78
+ """Run Binaryen validation on the module."""
79
+ return bool(lib.BinaryenModuleValidate(self._ref))
80
+
81
+ def emit(self) -> bytes:
82
+ """Serialize the module to wasm bytes."""
83
+ result = lib.BinaryenModuleAllocateAndWrite(self._ref, ffi.NULL)
84
+ try:
85
+ return bytes(ffi.buffer(result.binary, result.binaryBytes))
86
+ finally:
87
+ libc.free(result.binary)
88
+ if result.sourceMap != ffi.NULL:
89
+ libc.free(result.sourceMap)
90
+
91
+ def write(self, wasm_path: Union[Path, str]) -> None:
92
+ """Serialize the module to a wasm file."""
93
+ Path(wasm_path).write_bytes(self.emit())
94
+
95
+ def dispose(self) -> None:
96
+ """Free the Binaryen module; safe to call more than once."""
97
+ if self._ref is not None:
98
+ lib.BinaryenModuleDispose(self._ref)
99
+ self._ref = None
100
+ self._keepalive = None
101
+
102
+ def __enter__(self) -> "Module":
103
+ return self
104
+
105
+ def __exit__(
106
+ self,
107
+ exc_type: Optional[type[BaseException]],
108
+ exc: Optional[BaseException],
109
+ traceback: Optional[TracebackType],
110
+ ) -> None:
111
+ self.dispose()
112
+
113
+ def __del__(self) -> None:
114
+ try:
115
+ self.dispose()
116
+ except Exception: # pylint: disable = broad-exception-caught
117
+ pass # interpreter shutdown: lib may already be unloaded
icpp_binaryen/py.typed ADDED
File without changes
@@ -0,0 +1,7 @@
1
+ """Version of icpp-binaryen: <binaryen>.<minor>.<patch>.
2
+
3
+ The major component IS the bundled Binaryen version; do not add anything but
4
+ the version number here!
5
+ """
6
+
7
+ __version__ = "116.0.0"
@@ -0,0 +1,339 @@
1
+ Metadata-Version: 2.4
2
+ Name: icpp-binaryen
3
+ Version: 116.0.0
4
+ Summary: cffi bindings over Binaryen's C API with the official Binaryen shared library bundled per platform
5
+ Author-email: icpp-pro <icpp@icpp.world>
6
+ Maintainer-email: icpp-pro <icpp@icpp.world>
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "{}"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright {yyyy} {name of copyright owner}
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+ Project-URL: Homepage, https://www.onicai.com/
209
+ Project-URL: Documentation, https://docs.icpp.world/
210
+ Project-URL: Repository, https://github.com/icppWorld/icpp-binaryen
211
+ Project-URL: Issues, https://github.com/icppWorld/icpp-binaryen/issues
212
+ Project-URL: Changelog, https://github.com/icppWorld/icpp-binaryen/blob/main/CHANGELOG.md
213
+ Keywords: Binaryen,WebAssembly,wasm,Internet Computer,blockchain
214
+ Classifier: Development Status :: 4 - Beta
215
+ Classifier: License :: OSI Approved :: Apache Software License
216
+ Classifier: Programming Language :: Python :: 3
217
+ Classifier: Programming Language :: Python :: 3.11
218
+ Classifier: Programming Language :: Python :: 3.12
219
+ Classifier: Programming Language :: Python :: 3.13
220
+ Classifier: Programming Language :: Python :: 3.14
221
+ Classifier: Programming Language :: Python :: 3 :: Only
222
+ Requires-Python: >=3.11
223
+ Description-Content-Type: text/markdown
224
+ License-File: LICENSE
225
+ Requires-Dist: cffi>=1.15.1
226
+ Provides-Extra: dev
227
+ Requires-Dist: black==26.3.1; extra == "dev"
228
+ Requires-Dist: pylint==3.3.4; extra == "dev"
229
+ Requires-Dist: mypy==1.13.0; extra == "dev"
230
+ Requires-Dist: build==1.2.2; extra == "dev"
231
+ Requires-Dist: twine==6.0.1; extra == "dev"
232
+ Requires-Dist: pytest==8.3.4; extra == "dev"
233
+ Requires-Dist: types-cffi==2.1.0.20260827; extra == "dev"
234
+ Requires-Dist: wasmtime==29.0.0; extra == "dev"
235
+ Dynamic: license-file
236
+
237
+ # icpp-binaryen
238
+
239
+ [cffi](https://cffi.readthedocs.io/) bindings over
240
+ [Binaryen](https://github.com/WebAssembly/binaryen)'s C API, with the official
241
+ Binaryen shared library bundled per platform.
242
+
243
+ Built and maintained by [icppWorld](https://github.com/icppWorld) for the
244
+ [icpp-pro](https://docs.icpp.world) toolchain of the Internet Computer, and
245
+ usable by any project that needs Binaryen from Python.
246
+
247
+ ## Why
248
+
249
+ The Internet Computer rejects a wasm module with more than 1000 *defined*
250
+ globals (install error `IC0505`). A wasi-sdk build of a large C++ project
251
+ blows past this. The fix: remove every export of kind global (an exported
252
+ global is otherwise kept alive), then run Binaryen's optimizer, which drops
253
+ the now-dead globals. `fix_globals_limit` does exactly that.
254
+
255
+ ## Install
256
+
257
+ ```bash
258
+ pip install icpp-binaryen
259
+ ```
260
+
261
+ One wheel per platform (macOS x86_64 / arm64, Linux x86_64) covers every
262
+ Python version >= 3.11: the bindings use cffi in ABI mode, so there is no
263
+ compiled extension module. On Windows, use WSL.
264
+
265
+ ## Public API — all of it
266
+
267
+ ```python
268
+ from icpp_binaryen import fix_globals_limit # the one high-level entry point
269
+ from icpp_binaryen import Module # load / optimize / emit / write
270
+ from icpp_binaryen import ffi, lib # raw escape hatch
271
+ from icpp_binaryen import BINARYEN_VERSION # int, from the bundled version.txt
272
+ ```
273
+
274
+ ### fix_globals_limit
275
+
276
+ ```python
277
+ from pathlib import Path
278
+ from icpp_binaryen import fix_globals_limit
279
+
280
+ report = fix_globals_limit(Path("build/my_canister.wasm"))
281
+ print(report.summary())
282
+ ```
283
+
284
+ Rewrites the wasm in place and keeps a byte-identical backup copy (default
285
+ `<stem>_before_opt.wasm`). Returns a `GlobalsFixReport` with the
286
+ before/after counts of exports and defined globals.
287
+
288
+ Documented side effect: the optimize pass strips the wasm *name section*.
289
+ The `_before_opt` backup is what keeps named backtraces possible (e.g. under
290
+ wasmtime). This is by design — do not delete the backup pair.
291
+
292
+ ### Module
293
+
294
+ ```python
295
+ from icpp_binaryen import Module
296
+
297
+ with Module.load("my.wasm") as module: # or Module.read(wasm_bytes)
298
+ print(module.num_exports, module.num_globals)
299
+ for name in module.global_export_names():
300
+ module.remove_export(name)
301
+ module.optimize(shrink_level=0, optimize_level=0)
302
+ assert module.validate()
303
+ module.write("my_fixed.wasm") # or wasm_bytes = module.emit()
304
+ ```
305
+
306
+ ### ffi / lib
307
+
308
+ The raw ABI-mode cffi handles, for post-processing needs beyond the wrapper.
309
+ The cdef is a hand-curated subset of `binaryen-c.h` — see
310
+ `src/icpp_binaryen/_cdef.py` for what is available. `module.ref` hands you
311
+ the raw `BinaryenModuleRef` for use with `lib` directly.
312
+
313
+ ## Versioning
314
+
315
+ `<binaryen>.<minor>.<patch>` — the major component IS the bundled Binaryen
316
+ version, asserted at import time. The wasm bytes this package emits are part
317
+ of its contract: minor/patch releases are byte-identical in
318
+ `fix_globals_limit` output; a Binaryen bump is a major release.
319
+
320
+ ## Contributing
321
+
322
+ See [README-feature-guide.md](README-feature-guide.md) (the ceremony-based
323
+ development process) and
324
+ [README-release-guide.md](README-release-guide.md). Development setup:
325
+
326
+ ```bash
327
+ conda create --name icpp-binaryen python=3.11
328
+ conda activate icpp-binaryen
329
+ make install-python
330
+ make get-binaryen # fetch the official Binaryen lib for this platform
331
+ make all-tests
332
+ ```
333
+
334
+ ## Credits & license
335
+
336
+ Apache-2.0, like [Binaryen](https://github.com/WebAssembly/binaryen) itself.
337
+ The cffi-over-libbinaryen approach was inspired by
338
+ [jonathanharg/binaryen.py](https://github.com/jonathanharg/binaryen.py),
339
+ which this package replaces for the icpp-pro toolchain.
@@ -0,0 +1,14 @@
1
+ icpp_binaryen/__init__.py,sha256=NnmVb0YuE3iqsVYjpGJcZq4uaqNAJMQTY2ZJehntJsQ,816
2
+ icpp_binaryen/_cdef.py,sha256=kfJOa55b81k-JsgjtZuBEZADSkVswYUjhdbdaJWODcw,1652
3
+ icpp_binaryen/_lib.py,sha256=hWKemZBxQuppIe0OT6QRkYd7IMnAZNSph1hCSKgAzrQ,1641
4
+ icpp_binaryen/fix_globals.py,sha256=JEe0rZflzopON0d-JpIjJAUu40xKOG8elfZRSmyQ9AY,2542
5
+ icpp_binaryen/module.py,sha256=S6sRSpSB7PfPejCpMOgd_4Jwiol0GoEctn736UcY9J4,4282
6
+ icpp_binaryen/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ icpp_binaryen/version.py,sha256=bR4JP7tii83QkwfG47j6xQh6YJd3xwV8rsfc0aQFhFg,189
8
+ icpp_binaryen/lib/libbinaryen.dylib,sha256=JqF-Y5KHigf0HsVeuZXUpmukMUsHn5FS9RHqmcPgmeE,17002480
9
+ icpp_binaryen/lib/version.txt,sha256=5bhhptipZt_KfnNBzT62vpkBaI1UenLr7QsfXhTz0I0,3
10
+ icpp_binaryen-116.0.0.dist-info/licenses/LICENSE,sha256=xazLvYVG6Uw0rtJK_miaYXYn0Y7tWmxIJ35I21fCOFE,11356
11
+ icpp_binaryen-116.0.0.dist-info/METADATA,sha256=XBZwTr0Mk3jxErwp9NyOtiIXmnKyki2eIw-clHlx6Ac,18188
12
+ icpp_binaryen-116.0.0.dist-info/WHEEL,sha256=FPT8q8lmwJmqWWKWOfxFvTTs_idkkncMGBHC_t8YJ3M,111
13
+ icpp_binaryen-116.0.0.dist-info/top_level.txt,sha256=FkeMNx9-Zs1gg9hmChsugE7vn-iog3RBqLuOasfVTlc,14
14
+ icpp_binaryen-116.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-macosx_11_0_universal2
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ icpp_binaryen