Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
242 lines (204 loc) · 9.74 KB
/
Copy pathsetup.py
File metadata and controls
242 lines (204 loc) · 9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import platform
import sys
import tempfile
from distutils.errors import CompileError
from setuptools import setup
from setuptools.extension import Extension
from setuptools.command.build_ext import build_ext
# This fallback is only for jinja, which is used by conda to analyze this setup.py before any build environment
# is set up.
try:
from Cython.Build import cythonize
except ImportError:
cythonize = None
# Opt-in build against the Python 3.14 stable ABI. The normal build remains per-version. Invoke
# explicitly, e.g. CIBW_BUILD="cp314-*" INDEXED_BZIP2_ABI3=enable python -m cibuildwheel python/indexed_bzip2
withAbi3 = os.environ.get('INDEXED_BZIP2_ABI3', 'disable').lower() not in ('', '0', 'disable', 'off', 'false')
abi3Version = '0x030E0000'
abi3WheelTag = 'cp314'
# Valid options for dependencies:
# INDEXED_BZIP2_BUILD_BZIP2
# INDEXED_BZIP2_BUILD_LIBSAIS
# Valid values for dependencies:
# enable
# system
# Not specifying an option implies 'enable', which uses the packaged source code. 'system' links
# the library from the build environment.
optionsPrefix = 'INDEXED_BZIP2_BUILD_'
buildConfig = {key: value for key, value in os.environ.items() if key.startswith(optionsPrefix)}
print("\nIndexed_bzip2 build options:")
for key, value in buildConfig.items():
print(f" {key}={value}")
def getDependencyOption(key, default='enable'):
key = optionsPrefix + key
option = buildConfig.get(key, default)
validValues = ['enable', 'system']
if option not in validValues:
print(f"Unrecognized option for indexed_bzip2 dependency: {key}={option}. Valid values are: {validValues}")
return option if option in validValues else default
withLibsais = getDependencyOption('LIBSAIS')
withBzip2 = getDependencyOption('BZIP2')
print("Final indexed_bzip2 build configuration:")
print(f" libsais: {withLibsais}")
print(f" bzip2: {withBzip2}")
print(f" abi3: {withAbi3}")
libsais_sources = ['src/external/libsais_prefixed.c'] if withLibsais == 'enable' else []
bzip2_sources = [] if withBzip2 == 'system' else [
'src/external/bzip2/blocksort.c',
'src/external/bzip2/huffman.c',
'src/external/bzip2/crctable.c',
'src/external/bzip2/randtable.c',
'src/external/bzip2/compress.c',
'src/external/bzip2/bzlib.c',
]
include_dirs = ['src', 'src/external', 'src/external/cxxopts/include']
if withLibsais == 'enable':
include_dirs += ['src/external/libsais/include']
if withBzip2 == 'enable':
include_dirs += ['src/external/bzip2', 'src/external/bzip2_version']
define_macros = [('LIBRAPIDARCHIVE_WITH_BZIP2_COMPRESSION', None)]
if withLibsais == 'system':
# Make libsais_prefix.h a no-op and link the shared system library.
define_macros += [('LIBRAPIDARCHIVE_LIBSAIS_PREFIX', ''), ('LIBSAIS_SHARED', None)]
if withBzip2 == 'system':
define_macros += [('LIBRAPIDARCHIVE_USE_SYSTEM_BZIP2', None)]
if withAbi3:
define_macros.append(('Py_LIMITED_API', abi3Version))
extensions = [
Extension(
# fmt: off
name = 'indexed_bzip2',
sources = ['indexed_bzip2.pyx'] + libsais_sources + bzip2_sources,
include_dirs = include_dirs,
language = 'c++',
define_macros = define_macros,
py_limited_api = withAbi3,
# fmt: on
),
]
if cythonize:
extensions = cythonize(extensions, compiler_directives={'language_level': '3'})
def supportsFlag(compiler, flag):
with tempfile.NamedTemporaryFile('w', suffix='.cpp') as file:
file.write('int main() { return 0; }')
try:
compiler.compile([file.name], extra_postargs=[flag])
except CompileError:
print("[Info] Compiling with argument failed. Will try another one. The above error can be ignored!")
return False
return True
def isExternalSource(source):
return '/external/' in source.replace('\\', '/')
# https://github.com/cython/cython/blob/master/docs/src/tutorial/appendix.rst#python-38
class Build(build_ext):
def build_extensions(self):
oldCompile = self.compiler.compile
def newCompile(sources, *args, **kwargs):
cSources = [source for source in sources if source.endswith('.c')]
cppSources = [source for source in sources if not source.endswith('.c')]
if not cSources:
return oldCompile(sources, *args, **kwargs)
cppCompileArgs = [
'-fconstexpr-ops-limit=99000100',
'-fconstexpr-steps=99000100',
'-std=c++17',
'/std:c++17',
]
cppPostArgs = kwargs.get('extra_postargs', [])
cPostArgs = [argument for argument in cppPostArgs if argument not in cppCompileArgs]
externalWarningFlag = ['/w'] if self.compiler.compiler_type == 'msvc' else ['-w']
objects = oldCompile(cppSources, *args, **kwargs) if cppSources else []
for cSource in cSources:
if 'extra_postargs' in kwargs:
kwargs['extra_postargs'] = cPostArgs + (
externalWarningFlag if isExternalSource(cSource) else []
)
objects.extend(oldCompile([cSource], *args, **kwargs))
if 'extra_postargs' in kwargs:
kwargs['extra_postargs'] = cppPostArgs
return objects
self.compiler.compile = newCompile
for ext in self.extensions:
ext.extra_compile_args = [
'-std=c++17',
'-O3',
'-DNDEBUG',
'-DWITH_PYTHON_SUPPORT',
'-D_GLIBCXX_ASSERTIONS',
]
if withLibsais == 'system':
ext.libraries = list(ext.libraries or []) + [
'libsais' if self.compiler.compiler_type == 'msvc' else 'sais'
]
if withBzip2 == 'system':
ext.libraries = list(ext.libraries or []) + [
'libbz2' if self.compiler.compiler_type == 'msvc' else 'bz2'
]
if supportsFlag(self.compiler, '-flto=auto'):
ext.extra_compile_args += ['-flto=auto']
elif supportsFlag(self.compiler, '-flto'):
ext.extra_compile_args += ['-flto']
if supportsFlag(self.compiler, '-D_FORTIFY_SOURCE=2'):
ext.extra_compile_args += ['-D_FORTIFY_SOURCE=2', '-D_FILE_OFFSET_BITS=64']
# https://github.com/cython/cython/issues/2670#issuecomment-432212671
# https://github.com/cython/cython/issues/3405#issuecomment-596975159
# https://bugs.python.org/issue35037
# https://bugs.python.org/issue4709
if platform.system() == 'Windows' and platform.machine().endswith('64'):
ext.extra_compile_args += ['-DMS_WIN64']
if self.compiler.compiler_type == 'mingw32':
# GCC can spill AVX registers to stack slots it assumes are 32/64-byte aligned, but the
# Win64 ABI only guarantees 16 bytes. See the top-level CMakeLists.txt for the bug
# references and why the assembler rewrite is the safe fix.
if supportsFlag(self.compiler, '-Wa,-muse-unaligned-vector-move'):
ext.extra_compile_args += ['-Wa,-muse-unaligned-vector-move']
ext.extra_link_args = [
'-static-libgcc',
'-static-libstdc++',
'-Wl,-Bstatic,--whole-archive',
'-lwinpthread',
'-Wl,--no-whole-archive',
]
elif self.compiler.compiler_type == 'msvc':
ext.extra_compile_args = [
'/std:c++17',
'/experimental:c11atomics',
'/O2',
'/DNDEBUG',
'/DWITH_PYTHON_SUPPORT',
'/constexpr:steps99000100',
]
else:
# The default limit is ~33 M (1<<25) and 99 M seem to be enough to compile currently on GCC 11.
if supportsFlag(self.compiler, '-fconstexpr-ops-limit=99000100'):
ext.extra_compile_args += ['-fconstexpr-ops-limit=99000100']
elif supportsFlag(self.compiler, '-fconstexpr-steps=99000100'):
ext.extra_compile_args += ['-fconstexpr-steps=99000100']
# Keep vendored bzip2, libsais, and the embedded CLI out of the extension's
# dynamic symbol table. PyMODINIT_FUNC keeps PyInit_<module> visible.
if supportsFlag(self.compiler, '-fvisibility=hidden'):
ext.extra_compile_args += ['-fvisibility=hidden']
# Add some hardening. See e.g.:
# https://www.phoronix.com/news/GCC-fhardened-Hardening-Option
# https://developers.redhat.com/blog/2018/03/21/compiler-and-linker-flags-gcc
# I have not observed any performance impact for these.
ext.extra_compile_args += ['-fstack-protector-strong']
ext.extra_link_args += ['-fstack-clash-protection']
# AppleClang seems to not like this flag:
if supportsFlag(self.compiler, '-fcf-protection=full'):
ext.extra_compile_args += ['-fcf-protection=full']
if sys.platform.startswith('darwin') and supportsFlag(self.compiler, '-mmacosx-version-min=13.0'):
ext.extra_compile_args += ['-mmacosx-version-min=13.0']
ext.extra_link_args += ['-mmacosx-version-min=13.0']
super().build_extensions()
setup(
# fmt: off
py_modules = ['indexed_bzip2'],
ext_modules = extensions,
cmdclass = {'build_ext': Build},
options = {'bdist_wheel': {'py_limited_api': abi3WheelTag}} if withAbi3 else {},
# fmt: on
)