Debian Codegraph @

setup.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3 import glob
4 import os
5 import os.path
6 import platform
7 import re
8 import setuptools
9 import setuptools.command.build_ext
10 import shutil
11 import subprocess
12 import sys
13 import sysconfig
14 from setuptools.command.bdist_wheel import bdist_wheel
15
16 if sys.platform == 'win32':
17 # distutils is deprecated in Python 3.10 and removed in 3.12. However, it still works because Python defines a compatibility interface as long as setuptools is installed.
18 # We don't have an official alternative for distutils.ccompiler as of September 2024. See: https://github.com/pypa/setuptools/issues/2806
19 # Once that issue is resolved, we can migrate to the official solution.
20 # For now, restrict distutils to Windows only, where it's needed.
21 import distutils.ccompiler
22
23 # The minimum MACOSX_DEPLOYMENT_TARGET required for the library. If not
24 # set, the library will use the default value from python
25 # sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET').
26 MACOS_DEPLOYMENT_TARGET_MIN = "10.15"
27
28 # True if this is a free-threaded Python build.
29 FREE_THREADED_BUILD = sysconfig.get_config_var("Py_GIL_DISABLED") == 1
30
31 # This is the minimum version of the Windows SDK needed for schannel.h with SCH_CREDENTIALS and
32 # TLS_PARAMETERS. These are required to build Windows Binaries with TLS 1.3 support.
33 WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT = "10.0.17763.0"
34
35 # Regex to match a Windows SDK version directory name in the format of major.minor.build.revision
36 SDK_VERSION_RE = re.compile(r'^(\d+)\.(\d+)\.(\d+)\.(\d+)$')
37
38
39 def parse_version(version_string):
40 return tuple(int(x) for x in version_string.split("."))
41
42
43 def is_64bit():
44 return sys.maxsize > 2 ** 32
45
46
47 def is_32bit():
48 return is_64bit() == False
49
50
51 # TODO: Fix this. Since adding pyproject.toml, it always returns False
52 def is_development_mode():
53 """Return whether we're building in Development Mode (a.k.a. “Editable Installs”).
54 https://setuptools.pypa.io/en/latest/userguide/development_mode.html
55 These builds can take shortcuts to encourage faster iteration,
56 and turn on more warnings as errors to encourage correct code."""
57 return 'develop' in sys.argv
58
59
60 def get_xcode_major_version():
61 """Return major version of xcode present on the system"""
62 try:
63 output = subprocess.check_output(
64 ['xcodebuild', '-version'], text=True)
65 version_line = output.split('\n')[0]
66 version = version_line.split(' ')[-1]
67 return int(version.split('.')[0])
68 except BaseException:
69 return 0
70
71
72 def run_cmd(args):
73 print('>', subprocess.list2cmdline(args))
74 subprocess.check_call(args)
75
76
77 def copy_tree(src, dst):
78 shutil.copytree(src, dst, dirs_exist_ok=True)
79
80
81 def is_macos_universal2():
82 """Return whether extension should build as an Apple universal binary (works on both x86_64 and arm64)"""
83 if not sys.platform == 'darwin':
84 return False
85
86 cflags = sysconfig.get_config_var('CFLAGS')
87 return '-arch x86_64' in cflags and '-arch arm64' in cflags
88
89
90 def determine_cross_compile_args():
91 host_arch = platform.machine()
92 if (host_arch == 'AMD64' or host_arch == 'x86_64') and is_32bit() and sys.platform != 'win32':
93 return ['-DCMAKE_C_FLAGS=-m32']
94 return []
95
96
97 def get_windows_sdk_versions():
98 """Return a list of installed Windows SDK versions, sorted from newest to oldest.
99
100 Uses the Windows registry to find the SDK installation path.
101 """
102 if sys.platform != 'win32':
103 return []
104
105 import winreg
106
107 sdk_versions = []
108 sdk_paths = []
109
110 # Try to get SDK path from registry
111 try:
112 with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
113 r"SOFTWARE\Microsoft\Windows Kits\Installed Roots") as key:
114 sdk_root = winreg.QueryValueEx(key, "KitsRoot10")[0]
115 sdk_paths.append(os.path.join(sdk_root, "Include"))
116 except (OSError, FileNotFoundError):
117 # Registry key not found, fall back to common installation paths
118 sdk_paths = [
119 os.path.join(os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)'),
120 'Windows Kits', '10', 'Include'),
121 os.path.join(os.environ.get('ProgramFiles', 'C:\\Program Files'),
122 'Windows Kits', '10', 'Include'),
123 ]
124
125 for sdk_path in sdk_paths:
126 if os.path.exists(sdk_path):
127 try:
128 for entry in os.listdir(sdk_path):
129 # SDK version directories look like "major.minor.build.revision" (e.g. "10.0.17763.0")
130 if SDK_VERSION_RE.match(entry) and os.path.isdir(os.path.join(sdk_path, entry)):
131 if entry not in sdk_versions:
132 sdk_versions.append(entry)
133 except OSError:
134 continue
135
136 # Sort versions from newest to oldest
137 sdk_versions.sort(key=parse_version, reverse=True)
138 return sdk_versions
139
140
141 def get_best_windows_sdk_version():
142 """Return the best Windows SDK version to use for TLS 1.3 support.
143
144 Returns the latest installed SDK version that is >= WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT.
145 Raises RuntimeError if no suitable SDK is found.
146 """
147 installed_versions = get_windows_sdk_versions()
148
149 if installed_versions:
150 # We only need to check against the newest available version.
151 if parse_version(installed_versions[0]) >= parse_version(WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT):
152 version = installed_versions[0]
153 print(f"Found Windows SDK {version} (>= {WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT} required for TLS 1.3)")
154 return version
155 else:
156 raise RuntimeError(
157 f"No Windows SDK >= {WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT} found. "
158 f"Installed versions: {', '.join(installed_versions)}. "
159 f"Please install Windows SDK {WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT} or later for TLS 1.3 support.")
160 else:
161 raise RuntimeError(
162 f"No Windows SDK found. "
163 f"Please install Windows SDK {WINDOWS_SDK_MIN_VERSION_TLS1_3_SUPPORT} or later for TLS 1.3 support.")
164
165
166 def determine_generator_args(cmake_version=None, windows_sdk_version=None):
167 if sys.platform == 'win32':
168 try:
169 # See which compiler python picks
170 compiler = distutils.ccompiler.new_compiler()
171 compiler.initialize()
172
173 # Look at compiler path to divine the Visual Studio version.
174 # This technique may not work with customized VS install paths.
175 # An alternative would be to utilize private python calls:
176 # (distutils._msvccompiler._find_vc2017() and _find_vc2015()).
177 if '\\Microsoft Visual Studio\\18' in compiler.cc:
178 vs_version = 18
179 vs_year = 2026
180 elif '\\Microsoft Visual Studio\\2022' in compiler.cc:
181 vs_version = 17
182 vs_year = 2022
183 elif '\\Microsoft Visual Studio\\2019' in compiler.cc:
184 vs_version = 16
185 vs_year = 2019
186 elif '\\Microsoft Visual Studio\\2017' in compiler.cc:
187 vs_version = 15
188 vs_year = 2017
189 elif '\\Microsoft Visual Studio 14.0' in compiler.cc:
190 vs_version = 14
191 vs_year = 2015
192 assert (vs_version and vs_year)
193 except Exception:
194 raise RuntimeError('No supported version of MSVC compiler could be found!')
195 vs_version_gen_str = "Visual Studio {} {}".format(vs_version, vs_year)
196
197 print('Using Visual Studio', vs_version, vs_year)
198
199 if vs_year <= 2017:
200 # For VS2017 and earlier, architecture goes at end of generator string
201 if is_64bit():
202 vs_version_gen_str += " Win64"
203 return ['-G', vs_version_gen_str]
204
205 # For VS2019 (and presumably later), architecture is passed via -A flag
206 arch_str = "x64" if is_64bit() else "Win32"
207
208 # Set the target windows SDK version. We have a minimum required version of the Windows SDK needed for schannel.h with SCH_CREDENTIALS and
209 # TLS_PARAMETERS. These are required to build Windows Binaries with TLS 1.3 support.
210 # Introduced in cmake 3.27+, the generator string supports a version field to specify the windows sdk version in use
211 # https://cmake.org/cmake/help/latest/variable/CMAKE_GENERATOR_PLATFORM.html#variable:CMAKE_GENERATOR_PLATFORM
212 if cmake_version >= (3, 27):
213 # Set windows sdk version to the one that supports TLS 1.3
214 arch_str += f",version={windows_sdk_version}"
215
216 print('Using Visual Studio', vs_version, vs_year, 'with architecture', arch_str)
217
218 return ['-G', vs_version_gen_str, '-A', arch_str]
219
220 return []
221
222
223 cmake_found = None
224
225
226 def get_cmake_path():
227 global cmake_found
228 if cmake_found:
229 return cmake_found
230
231 for cmake_alias in ['cmake3', 'cmake']:
232 cmake_found = shutil.which(cmake_alias)
233 if cmake_found:
234 return cmake_found
235
236 raise Exception("CMake must be installed to build from source.")
237
238
239 def get_cmake_version():
240 """Return the version of CMake installed on the system."""
241 cmake_path = get_cmake_path()
242 if not cmake_path:
243 return (0, 0, 0)
244 try:
245 output = subprocess.check_output([cmake_path, '--version'], text=True)
246 version_line = output.split('\n')[0]
247 version = version_line.split(' ')[-1]
248 print(f"Found CMake version: {version}")
249 return parse_version(version)
250 except BaseException:
251 return (0, 0, 0) # Return a default version if cmake is not found or fails
252
253
254 def using_system_libs():
255 """If true, don't build any dependencies. Use the libs that are already on the system."""
256 return (os.getenv('AWS_CRT_BUILD_USE_SYSTEM_LIBS') == '1'
257 or not os.path.exists(os.path.join(PROJECT_DIR, 'crt', 'aws-c-common', 'CMakeLists.txt')))
258
259
260 def using_libcrypto():
261 """If true, libcrypto is used, even on win/mac."""
262 if sys.platform == 'darwin' or sys.platform == 'win32':
263 # use libcrypto on mac/win to support ed25519, unless its disabled via env-var
264 return not os.getenv('AWS_CRT_BUILD_DISABLE_LIBCRYPTO_USE_FOR_ED25519_EVERYWHERE') == '1'
265 else:
266 # on Unix we always use libcrypto
267 return True
268
269
270 def using_system_libcrypto():
271 """If true, don't build AWS-LC. Use the libcrypto that's already on the system."""
272 return using_system_libs() or os.getenv('AWS_CRT_BUILD_USE_SYSTEM_LIBCRYPTO') == '1'
273
274
275 def forcing_static_libs():
276 """If true, force libs to be linked statically."""
277 return os.getenv('AWS_CRT_BUILD_FORCE_STATIC_LIBS') == '1'
278
279
280 def get_extra_library_dirs():
281 """Return list of additional library directories from AWS_EXTRA_LIB_DIR env var.
282
283 Supports multiple directories separated by os.pathsep (: on Unix, ; on Windows).
284 Returns empty list if not set.
285 """
286 extra_dirs = os.getenv('AWS_EXTRA_LIB_DIR', '')
287 if not extra_dirs:
288 return []
289 return [d for d in extra_dirs.split(os.pathsep) if d]
290
291
292 class AwsLib:
293 def __init__(self, name, extra_cmake_args=[], libname=None):
294 self.name = name
295 self.extra_cmake_args = extra_cmake_args
296 self.libname = libname if libname else name
297
298
299 # The extension depends on these libs.
300 # They're built along with the extension (unless using_system_libs() is True)
301 AWS_LIBS = []
302
303 if using_libcrypto():
304 # aws-lc produces libcrypto.a
305 AWS_LIBS.append(AwsLib('aws-lc', libname='crypto'))
306
307 if sys.platform != 'win32':
308 AWS_LIBS.append(AwsLib('s2n'))
309
310 AWS_LIBS.append(AwsLib('aws-c-common'))
311 AWS_LIBS.append(AwsLib('aws-c-sdkutils'))
312 AWS_LIBS.append(AwsLib('aws-c-cal'))
313 AWS_LIBS.append(AwsLib('aws-c-io'))
314 AWS_LIBS.append(AwsLib('aws-checksums'))
315 AWS_LIBS.append(AwsLib('aws-c-compression'))
316 AWS_LIBS.append(AwsLib('aws-c-event-stream'))
317 AWS_LIBS.append(AwsLib('aws-c-http'))
318 AWS_LIBS.append(AwsLib('aws-c-auth'))
319 AWS_LIBS.append(AwsLib('aws-c-mqtt'))
320 AWS_LIBS.append(AwsLib('aws-c-s3'))
321
322 PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
323
324 VERSION_RE = re.compile(r""".*__version__ = ["'](.*?)['"]""", re.S)
325
326
327 class awscrt_build_ext(setuptools.command.build_ext.build_ext):
328 def _build_dependencies_impl(self, build_dir, install_path, osx_arch=None):
329 cmake = get_cmake_path()
330
331 # enable parallel builds for cmake 3.12+
332 # setting environ because "--parallel" arg doesn't exist in older cmake versions.
333 # setting a number because if it's blank then "make" will go absolutely
334 # bananas and run out of memory on low-end machines.
335 if 'CMAKE_BUILD_PARALLEL_LEVEL' not in os.environ:
336 os.environ['CMAKE_BUILD_PARALLEL_LEVEL'] = f'{os.cpu_count()}'
337
338 source_dir = os.path.join(PROJECT_DIR, 'crt')
339
340 build_type = 'Debug' if self.debug else 'RelWithDebInfo'
341
342 if osx_arch:
343 print(f"--- Building arch: {osx_arch} ---")
344
345 # cmake configure
346 cmake_args = [cmake]
347 cmake_args.append(f'-H{source_dir}')
348 cmake_args.append(f'-B{build_dir}')
349
350 if sys.platform == 'win32':
351 windows_sdk_version = os.getenv('AWS_CRT_WINDOWS_SDK_VERSION')
352 if windows_sdk_version is None:
353 windows_sdk_version = get_best_windows_sdk_version()
354
355 cmake_version = get_cmake_version()
356
357 cmake_args.extend(
358 determine_generator_args(
359 cmake_version=cmake_version,
360 windows_sdk_version=windows_sdk_version))
361
362 if cmake_version < (3, 27):
363 # Set the target windows SDK version. We have a minimum required version of the Windows SDK needed for schannel.h with SCH_CREDENTIALS and
364 # TLS_PARAMETERS. These are required to build Windows Binaries with TLS 1.3 support.
365 # for cmake < 3.27, we have to specify the version with CMAKE_SYSTEM_VERSION. Please note this flag will be
366 # ignored by cmake versions >= 3.27.
367 # checkout determine_generator_args() for the case of cmake >= 3.27
368 cmake_args.append(f'-DCMAKE_SYSTEM_VERSION={windows_sdk_version}')
369
370 cmake_args.extend(determine_cross_compile_args())
371 cmake_args.extend([
372 f'-DCMAKE_INSTALL_PREFIX={install_path}',
373 f'-DCMAKE_BUILD_TYPE={build_type}',
374 ])
375
376 if using_libcrypto():
377 if using_system_libcrypto():
378 cmake_args.append('-DUSE_OPENSSL=ON')
379
380 cmake_args.append('-DAWS_USE_LIBCRYPTO_TO_SUPPORT_ED25519_EVERYWHERE=ON')
381
382 if sys.platform == 'darwin':
383 # get Python's MACOSX_DEPLOYMENT_TARGET version
384 macosx_target_ver = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
385 # If MACOS_DEPLOYMENT_TARGET_MIN is set to a later version than python distribution,
386 # override MACOSX_DEPLOYMENT_TARGET.
387 if macosx_target_ver is None or parse_version(
388 MACOS_DEPLOYMENT_TARGET_MIN) > parse_version(macosx_target_ver):
389 macosx_target_ver = MACOS_DEPLOYMENT_TARGET_MIN
390 os.environ['MACOSX_DEPLOYMENT_TARGET'] = macosx_target_ver
391 cmake_args.append(f'-DCMAKE_OSX_DEPLOYMENT_TARGET={macosx_target_ver}')
392
393 if osx_arch:
394 cmake_args.append(f'-DCMAKE_OSX_ARCHITECTURES={osx_arch}')
395
396 run_cmd(cmake_args)
397
398 # cmake build/install
399 build_cmd = [
400 cmake,
401 '--build', build_dir,
402 '--config', build_type,
403 '--target', 'install',
404 ]
405 run_cmd(build_cmd)
406
407 def _build_dependencies(self):
408 build_dir = os.path.join(self.build_temp, 'deps')
409 install_path = os.path.join(self.build_temp, 'deps', 'install')
410
411 if is_macos_universal2() and not is_development_mode():
412 # create macOS universal binary by compiling for x86_64 and arm64,
413 # each in its own subfolder, and then creating a universal binary
414 # by gluing the two together using `lipo`.
415 #
416 # The AWS C libs don't support building for multiple architectures
417 # simultaneously (too much confusion at cmake configure time).
418 # So we build each architecture one at a time.
419 #
420 # BUT skip this in development mode. Building everything twice takes
421 # too long and development builds only ever run on the host machine.
422
423 # x86_64
424 self._build_dependencies_impl(
425 build_dir=os.path.join(build_dir, 'x86_64'),
426 install_path=os.path.join(build_dir, 'x86_64', 'install'),
427 osx_arch='x86_64')
428
429 # arm64
430 self._build_dependencies_impl(
431 build_dir=os.path.join(build_dir, 'arm64'),
432 install_path=os.path.join(build_dir, 'arm64', 'install'),
433 osx_arch='arm64')
434
435 # Create a universal binary for each lib at expected install_path
436 lib_dir = os.path.join(install_path, 'lib')
437 os.makedirs(lib_dir, exist_ok=True)
438 for aws_lib in AWS_LIBS:
439 lib_file = f'lib{aws_lib.libname}.a'
440 run_cmd(['lipo', '-create',
441 '-output', os.path.join(lib_dir, lib_file),
442 os.path.join(build_dir, 'x86_64', 'install', 'lib', lib_file),
443 os.path.join(build_dir, 'arm64', 'install', 'lib', lib_file)])
444
445 # copy headers to expected install_path
446 copy_tree(os.path.join(build_dir, 'arm64', 'install', 'include'),
447 os.path.join(install_path, 'include'))
448
449 else:
450 # normal build for a single architecture
451 self._build_dependencies_impl(build_dir, install_path)
452
453 # update paths so awscrt_ext can access dependencies.
454 # add to the front of any list so that our dependencies are preferred
455 # over anything that might already be on the system (i.e. libcrypto.a)
456
457 self.include_dirs.insert(0, os.path.join(install_path, 'include'))
458
459 # some platforms (ex: fedora) use /lib64 instead of just /lib
460 lib_dir = 'lib'
461 if is_64bit() and os.path.exists(os.path.join(install_path, 'lib64')):
462 lib_dir = 'lib64'
463 if is_32bit() and os.path.exists(os.path.join(install_path, 'lib32')):
464 lib_dir = 'lib32'
465
466 self.library_dirs.insert(0, os.path.join(install_path, lib_dir))
467
468 def build_extension(self, ext):
469
470 # Warning: very hacky. feel free to replace with something cleaner
471 # Problem: if you install python through homebrew, python config ldflags
472 # will point to homebrew lib folder.
473 # setuptools puts python ldflags before any of our lib paths, so if there is openssl or
474 # another libcrypto in homebrew libs, it will get picked up before aws-lc we are building against.
475 # And then we have fun failures due to lib mismatch.
476 # I could not find a cleaner way, so lets just hook into linker command and make sure
477 # our libs appear before other libs.
478 if sys.platform == 'darwin' and using_libcrypto() and not using_system_libs() and not using_system_libcrypto():
479
480 orig_linker_so = self.compiler.linker_so[:]
481
482 for i, item in enumerate(self.compiler.linker_so):
483 if item.startswith('-L'):
484 self.compiler.linker_so[i:i] = [
485 f"-L{item}" for item in self.library_dirs] + ['-Wl,-search_paths_first']
486 break
487
488 try:
489 super().build_extension(ext)
490 finally:
491 self.compiler.linker_so = orig_linker_so
492 else:
493 super().build_extension(ext)
494
495 def run(self):
496 if using_system_libs():
497 print("Skip building dependencies")
498 else:
499 self._build_dependencies()
500
501 # continue with normal build_ext.run()
502 super().run()
503
504
505 class bdist_wheel_abi3(bdist_wheel):
506 def get_tag(self):
507 python, abi, plat = super().get_tag()
508 # on CPython, our wheels are abi3 and compatible back to 3.11
509 if FREE_THREADED_BUILD:
510 # free-threaded builds don't use limited API, so skip abi3 tag
511 return python, abi, plat
512 elif python.startswith("cp") and sys.version_info >= (3, 13):
513 # 3.13 deprecates PyWeakref_GetObject(), adds alternative
514 return "cp313", "abi3", plat
515 elif python.startswith("cp") and sys.version_info >= (3, 11):
516 # 3.11 is the first stable ABI that has everything we need
517 return "cp311", "abi3", plat
518
519 return python, abi, plat
520
521
522 def awscrt_ext():
523 # fetch the CFLAGS/LDFLAGS from env
524 extra_compile_args = os.environ.get('CFLAGS', '').split()
525 extra_link_args = os.environ.get('LDFLAGS', '').split()
526 extra_objects = []
527 define_macros = []
528 py_limited_api = False
529
530 libraries = [x.libname for x in AWS_LIBS]
531
532 # libraries must be passed to the linker with upstream dependencies listed last.
533 libraries.reverse()
534
535 if sys.platform == 'win32':
536 # the windows apis being used under the hood. Since we're static linking we have to follow the entire chain down
537 libraries += ['Secur32', 'Crypt32', 'Advapi32', 'NCrypt', 'BCrypt', 'Kernel32', 'Ws2_32', 'Shlwapi']
538 # Ensure that debug info is in the obj files, and that it is linked into the .pyd so that
539 # stack traces and dumps are useful
540 extra_compile_args += ['/Z7']
541 extra_link_args += ['/DEBUG']
542
543 elif sys.platform == 'darwin':
544 extra_link_args += ['-framework', 'Security']
545
546 else: # unix
547 if forcing_static_libs():
548 # linker will prefer shared libraries over static if it can find both.
549 # force linker to choose static variant by using
550 # "-l:libaws-c-common.a" syntax instead of just "-laws-c-common".
551 #
552 # This helps AWS developers creating Lambda applications from Brazil.
553 # In Brazil, both shared and static libs are available.
554 # But Lambda requires all shared libs to be explicitly packaged up.
555 # So it's simpler to link them in statically and have less runtime dependencies.
556 #
557 # Don't apply this trick to dependencies that are always on the OS (e.g. librt)
558 libraries = [':lib{}.a'.format(x) for x in libraries]
559
560 # OpenBSD doesn't have librt; functions are found in libc instead.
561 if not sys.platform.startswith('openbsd'):
562 libraries += ['rt']
563
564 # OpenBSD 7.4+ defaults to linking with --execute-only, which is bad for AWS-LC.
565 # See: https://github.com/aws/aws-lc/blob/4b07805bddc55f68e5ce8c42f215da51c7a4e099/CMakeLists.txt#L44-L53
566 # (If AWS-LC's CMakeLists.txt removes these lines in the future, we can remove this hack here as well)
567 if sys.platform.startswith('openbsd'):
568 if not using_system_libcrypto():
569 extra_link_args += ['-Wl,--no-execute-only']
570
571 # FreeBSD doesn't have execinfo as a part of libc like other Unix variant.
572 # Passing linker flag to link execinfo properly
573 if sys.platform.startswith('freebsd'):
574 libraries += ['execinfo']
575
576 # python usually adds -pthread automatically, but we've observed
577 # rare cases where that didn't happen, so let's be explicit.
578 extra_link_args += ['-pthread']
579
580 # hide the symbols from libcrypto.a
581 # this prevents weird crashes if an application also ends up using
582 # libcrypto.so from the system's OpenSSL installation.
583 # Do this even if using system libcrypto, since it could still be a static lib.
584 extra_link_args += ['-Wl,--exclude-libs,libcrypto.a']
585
586 if sys.platform != 'win32' or distutils.ccompiler.get_default_compiler() != 'msvc':
587 extra_compile_args += ['-Wno-strict-aliasing', '-std=gnu99']
588
589 # treat warnings as errors in development mode
590 if is_development_mode() or os.getenv('AWS_CRT_BUILD_WARNINGS_ARE_ERRORS') == '1':
591 extra_compile_args += ['-Wextra', '-Werror']
592
593 # ...except when we take shortcuts in development mode and don't make
594 # a proper MacOS Universal2 binary. The linker warns us about this,
595 # but WHATEVER. Building everything twice (x86_64 and arm64) takes too long.
596 if not is_macos_universal2():
597 if sys.platform == 'darwin':
598 extra_link_args += ['-Wl,-fatal_warnings']
599 # xcode 15 introduced a new linker that generates a warning
600 # when it sees duplicate libs or rpath during bundling.
601 # pyenv installed from homebrew put duplicate rpath entries
602 # into sysconfig, and setuptools happily passes them along
603 # to xcode, resulting in a warning
604 # (which is fatal in this branch).
605 # ex. https://github.com/pyenv/pyenv/issues/2890
606 # lets revert back to old linker on xcode >= 15 until one of
607 # the involved parties fixes the issue.
608 if get_xcode_major_version() >= 15:
609 extra_link_args += ['-Wl,-ld_classic']
610 elif 'bsd' in sys.platform:
611 extra_link_args += ['-Wl,-fatal-warnings']
612 else:
613 extra_link_args += ['-Wl,--fatal-warnings']
614
615 # prefer building with stable ABI, so a wheel can work with multiple major versions
616 if FREE_THREADED_BUILD and sys.version_info[:2] <= (3, 14):
617 # 3.14 free threaded (aka no gil) does not support limited api.
618 # disable it for now. 3.15 promises to support limited api + free threading combo
619 py_limited_api = False
620 elif sys.version_info >= (3, 13):
621 # 3.13 deprecates PyWeakref_GetObject(), adds alternative
622 define_macros.append(('Py_LIMITED_API', '0x030D0000'))
623 py_limited_api = True
624 elif sys.version_info >= (3, 11):
625 # 3.11 is the first stable ABI that has everything we need
626 define_macros.append(('Py_LIMITED_API', '0x030B0000'))
627 py_limited_api = True
628
629 return setuptools.Extension(
630 '_awscrt',
631 language='c',
632 library_dirs=get_extra_library_dirs(),
633 libraries=libraries,
634 sources=glob.glob('source/*.c'),
635 extra_compile_args=extra_compile_args,
636 extra_link_args=extra_link_args,
637 extra_objects=extra_objects,
638 define_macros=define_macros,
639 py_limited_api=py_limited_api,
640 )
641
642
643 def _load_version():
644 init_path = os.path.join(PROJECT_DIR, 'awscrt', '__init__.py')
645 with open(init_path) as fp:
646 return VERSION_RE.match(fp.read()).group(1)
647
648
649 setuptools.setup(
650 version=_load_version(),
651 # Note: find_packages() without extra args will end up installing test/
652 packages=setuptools.find_packages(include=['awscrt*']),
653 ext_modules=[awscrt_ext()],
654 cmdclass={'build_ext': awscrt_build_ext, "bdist_wheel": bdist_wheel_abi3},
655 )