Debian Codegraph @

lib-python/3/_osx_support.py

raw symbols SCIP
1 """Shared OS X support functions."""
2
3 import os
4 import re
5 import sys
6
7 __all__ = [
8 'compiler_fixup',
9 'customize_config_vars',
10 'customize_compiler',
11 'get_platform_osx',
12 ]
13
14 # configuration variables that may contain universal build flags,
15 # like "-arch" or "-isdkroot", that may need customization for
16 # the user environment
17 _UNIVERSAL_CONFIG_VARS = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS', 'BASECFLAGS',
18 'BLDSHARED', 'LDSHARED', 'CC', 'CXX',
19 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS',
20 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS')
21
22 # configuration variables that may contain compiler calls
23 _COMPILER_CONFIG_VARS = ('BLDSHARED', 'LDSHARED', 'CC', 'CXX')
24
25 # prefix added to original configuration variable names
26 _INITPRE = '_OSX_SUPPORT_INITIAL_'
27
28
29 def _find_executable(executable, path=None):
30 """Tries to find 'executable' in the directories listed in 'path'.
31
32 A string listing directories separated by 'os.pathsep'; defaults to
33 os.environ['PATH']. Returns the complete filename or None if not found.
34 """
35 if path is None:
36 path = os.environ['PATH']
37
38 paths = path.split(os.pathsep)
39 base, ext = os.path.splitext(executable)
40
41 if (sys.platform == 'win32') and (ext != '.exe'):
42 executable = executable + '.exe'
43
44 if not os.path.isfile(executable):
45 for p in paths:
46 f = os.path.join(p, executable)
47 if os.path.isfile(f):
48 # the file exists, we have a shot at spawn working
49 return f
50 return None
51 else:
52 return executable
53
54
55 def _read_output(commandstring, capture_stderr=False):
56 """Output from successful command execution or None"""
57 # Similar to os.popen(commandstring, "r").read(),
58 # but without actually using os.popen because that
59 # function is not usable during python bootstrap.
60 # tempfile is also not available then.
61 import contextlib
62 try:
63 import tempfile
64 fp = tempfile.NamedTemporaryFile()
65 except ImportError:
66 fp = open("/tmp/_osx_support.%s"%(
67 os.getpid(),), "w+b")
68
69 with contextlib.closing(fp) as fp:
70 if capture_stderr:
71 cmd = "%s >'%s' 2>&1" % (commandstring, fp.name)
72 else:
73 cmd = "%s 2>/dev/null >'%s'" % (commandstring, fp.name)
74 return fp.read().decode('utf-8').strip() if not os.system(cmd) else None
75
76
77 def _find_build_tool(toolname):
78 """Find a build tool on current path or using xcrun"""
79 return (_find_executable(toolname)
80 or _read_output("/usr/bin/xcrun -find %s" % (toolname,))
81 or ''
82 )
83
84 _SYSTEM_VERSION = None
85
86 def _get_system_version():
87 """Return the OS X system version as a string"""
88 # Reading this plist is a documented way to get the system
89 # version (see the documentation for the Gestalt Manager)
90 # We avoid using platform.mac_ver to avoid possible bootstrap issues during
91 # the build of Python itself (distutils is used to build standard library
92 # extensions).
93
94 global _SYSTEM_VERSION
95
96 if _SYSTEM_VERSION is None:
97 _SYSTEM_VERSION = ''
98 try:
99 f = open('/System/Library/CoreServices/SystemVersion.plist', encoding="utf-8")
100 except OSError:
101 # We're on a plain darwin box, fall back to the default
102 # behaviour.
103 pass
104 else:
105 try:
106 m = re.search(r'<key>ProductUserVisibleVersion</key>\s*'
107 r'<string>(.*?)</string>', f.read())
108 finally:
109 f.close()
110 if m is not None:
111 _SYSTEM_VERSION = '.'.join(m.group(1).split('.')[:2])
112 # else: fall back to the default behaviour
113 if not _SYSTEM_VERSION:
114 # minimum supported MACOSX_DEPLOYMENT_TARGET version
115 return '10.9'
116 return _SYSTEM_VERSION
117
118 _SYSTEM_VERSION_TUPLE = None
119 def _get_system_version_tuple():
120 """
121 Return the macOS system version as a tuple
122
123 The return value is safe to use to compare
124 two version numbers.
125 """
126 global _SYSTEM_VERSION_TUPLE
127 if _SYSTEM_VERSION_TUPLE is None:
128 osx_version = _get_system_version()
129 if osx_version:
130 try:
131 _SYSTEM_VERSION_TUPLE = tuple(int(i) for i in osx_version.split('.'))
132 except ValueError:
133 _SYSTEM_VERSION_TUPLE = ()
134
135 return _SYSTEM_VERSION_TUPLE
136
137
138 def _remove_original_values(_config_vars):
139 """Remove original unmodified values for testing"""
140 # This is needed for higher-level cross-platform tests of get_platform.
141 for k in list(_config_vars):
142 if k.startswith(_INITPRE):
143 del _config_vars[k]
144
145 def _save_modified_value(_config_vars, cv, newvalue):
146 """Save modified and original unmodified value of configuration var"""
147
148 oldvalue = _config_vars.get(cv, '')
149 if (oldvalue != newvalue) and (_INITPRE + cv not in _config_vars):
150 _config_vars[_INITPRE + cv] = oldvalue
151 _config_vars[cv] = newvalue
152
153
154 _cache_default_sysroot = None
155 def _default_sysroot(cc):
156 """ Returns the root of the default SDK for this system, or '/' """
157 global _cache_default_sysroot
158
159 if _cache_default_sysroot is not None:
160 return _cache_default_sysroot
161
162 contents = _read_output('%s -c -E -v - </dev/null' % (cc,), True)
163 in_incdirs = False
164 for line in contents.splitlines():
165 if line.startswith("#include <...>"):
166 in_incdirs = True
167 elif line.startswith("End of search list"):
168 in_incdirs = False
169 elif in_incdirs:
170 line = line.strip()
171 if line == '/usr/include':
172 _cache_default_sysroot = '/'
173 elif line.endswith(".sdk/usr/include"):
174 _cache_default_sysroot = line[:-12]
175 if _cache_default_sysroot is None:
176 _cache_default_sysroot = '/'
177
178 return _cache_default_sysroot
179
180 def _supports_universal_builds():
181 """Returns True if universal builds are supported on this system"""
182 # As an approximation, we assume that if we are running on 10.4 or above,
183 # then we are running with an Xcode environment that supports universal
184 # builds, in particular -isysroot and -arch arguments to the compiler. This
185 # is in support of allowing 10.4 universal builds to run on 10.3.x systems.
186
187 osx_version = _get_system_version_tuple()
188 return bool(osx_version >= (10, 4)) if osx_version else False
189
190 def _supports_arm64_builds():
191 """Returns True if arm64 builds are supported on this system"""
192 # There are two sets of systems supporting macOS/arm64 builds:
193 # 1. macOS 11 and later, unconditionally
194 # 2. macOS 10.15 with Xcode 12.2 or later
195 # For now the second category is ignored.
196 osx_version = _get_system_version_tuple()
197 return osx_version >= (11, 0) if osx_version else False
198
199
200 def _find_appropriate_compiler(_config_vars):
201 """Find appropriate C compiler for extension module builds"""
202
203 # Issue #13590:
204 # The OSX location for the compiler varies between OSX
205 # (or rather Xcode) releases. With older releases (up-to 10.5)
206 # the compiler is in /usr/bin, with newer releases the compiler
207 # can only be found inside Xcode.app if the "Command Line Tools"
208 # are not installed.
209 #
210 # Furthermore, the compiler that can be used varies between
211 # Xcode releases. Up to Xcode 4 it was possible to use 'gcc-4.2'
212 # as the compiler, after that 'clang' should be used because
213 # gcc-4.2 is either not present, or a copy of 'llvm-gcc' that
214 # miscompiles Python.
215
216 # skip checks if the compiler was overridden with a CC env variable
217 if 'CC' in os.environ:
218 return _config_vars
219
220 # The CC config var might contain additional arguments.
221 # Ignore them while searching.
222 cc = oldcc = _config_vars['CC'].split()[0]
223 if not _find_executable(cc):
224 # Compiler is not found on the shell search PATH.
225 # Now search for clang, first on PATH (if the Command LIne
226 # Tools have been installed in / or if the user has provided
227 # another location via CC). If not found, try using xcrun
228 # to find an uninstalled clang (within a selected Xcode).
229
230 # NOTE: Cannot use subprocess here because of bootstrap
231 # issues when building Python itself (and os.popen is
232 # implemented on top of subprocess and is therefore not
233 # usable as well)
234
235 cc = _find_build_tool('clang')
236
237 elif os.path.basename(cc).startswith('gcc'):
238 # Compiler is GCC, check if it is LLVM-GCC
239 data = _read_output("'%s' --version"
240 % (cc.replace("'", "'\"'\"'"),))
241 if data and 'llvm-gcc' in data:
242 # Found LLVM-GCC, fall back to clang
243 cc = _find_build_tool('clang')
244
245 if not cc:
246 raise SystemError(
247 "Cannot locate working compiler")
248
249 if cc != oldcc:
250 # Found a replacement compiler.
251 # Modify config vars using new compiler, if not already explicitly
252 # overridden by an env variable, preserving additional arguments.
253 for cv in _COMPILER_CONFIG_VARS:
254 if cv in _config_vars and cv not in os.environ:
255 cv_split = _config_vars[cv].split()
256 cv_split[0] = cc if cv != 'CXX' else cc + '++'
257 _save_modified_value(_config_vars, cv, ' '.join(cv_split))
258
259 return _config_vars
260
261
262 def _remove_universal_flags(_config_vars):
263 """Remove all universal build arguments from config vars"""
264
265 for cv in _UNIVERSAL_CONFIG_VARS:
266 # Do not alter a config var explicitly overridden by env var
267 if cv in _config_vars and cv not in os.environ:
268 flags = _config_vars[cv]
269 flags = re.sub(r'-arch\s+\w+\s', ' ', flags, flags=re.ASCII)
270 flags = re.sub(r'-isysroot\s*\S+', ' ', flags)
271 _save_modified_value(_config_vars, cv, flags)
272
273 return _config_vars
274
275
276 def _remove_unsupported_archs(_config_vars):
277 """Remove any unsupported archs from config vars"""
278 # Different Xcode releases support different sets for '-arch'
279 # flags. In particular, Xcode 4.x no longer supports the
280 # PPC architectures.
281 #
282 # This code automatically removes '-arch ppc' and '-arch ppc64'
283 # when these are not supported. That makes it possible to
284 # build extensions on OSX 10.7 and later with the prebuilt
285 # 32-bit installer on the python.org website.
286
287 # skip checks if the compiler was overridden with a CC env variable
288 if 'CC' in os.environ:
289 return _config_vars
290
291 if re.search(r'-arch\s+ppc', _config_vars['CFLAGS']) is not None:
292 # NOTE: Cannot use subprocess here because of bootstrap
293 # issues when building Python itself
294 status = os.system(
295 """echo 'int main{};' | """
296 """'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null"""
297 %(_config_vars['CC'].replace("'", "'\"'\"'"),))
298 if status:
299 # The compile failed for some reason. Because of differences
300 # across Xcode and compiler versions, there is no reliable way
301 # to be sure why it failed. Assume here it was due to lack of
302 # PPC support and remove the related '-arch' flags from each
303 # config variables not explicitly overridden by an environment
304 # variable. If the error was for some other reason, we hope the
305 # failure will show up again when trying to compile an extension
306 # module.
307 for cv in _UNIVERSAL_CONFIG_VARS:
308 if cv in _config_vars and cv not in os.environ:
309 flags = _config_vars[cv]
310 flags = re.sub(r'-arch\s+ppc\w*\s', ' ', flags)
311 _save_modified_value(_config_vars, cv, flags)
312
313 return _config_vars
314
315
316 def _override_all_archs(_config_vars):
317 """Allow override of all archs with ARCHFLAGS env var"""
318 # NOTE: This name was introduced by Apple in OSX 10.5 and
319 # is used by several scripting languages distributed with
320 # that OS release.
321 if 'ARCHFLAGS' in os.environ:
322 arch = os.environ['ARCHFLAGS']
323 for cv in _UNIVERSAL_CONFIG_VARS:
324 if cv in _config_vars and '-arch' in _config_vars[cv]:
325 flags = _config_vars[cv]
326 flags = re.sub(r'-arch\s+\w+\s', ' ', flags)
327 flags = flags + ' ' + arch
328 _save_modified_value(_config_vars, cv, flags)
329
330 return _config_vars
331
332
333 def _check_for_unavailable_sdk(_config_vars):
334 """Remove references to any SDKs not available"""
335 # If we're on OSX 10.5 or later and the user tries to
336 # compile an extension using an SDK that is not present
337 # on the current machine it is better to not use an SDK
338 # than to fail. This is particularly important with
339 # the standalone Command Line Tools alternative to a
340 # full-blown Xcode install since the CLT packages do not
341 # provide SDKs. If the SDK is not present, it is assumed
342 # that the header files and dev libs have been installed
343 # to /usr and /System/Library by either a standalone CLT
344 # package or the CLT component within Xcode.
345 cflags = _config_vars.get('CFLAGS', '')
346 m = re.search(r'-isysroot\s*(\S+)', cflags)
347 if m is not None:
348 sdk = m.group(1)
349 if not os.path.exists(sdk):
350 for cv in _UNIVERSAL_CONFIG_VARS:
351 # Do not alter a config var explicitly overridden by env var
352 if cv in _config_vars and cv not in os.environ:
353 flags = _config_vars[cv]
354 flags = re.sub(r'-isysroot\s*\S+(?:\s|$)', ' ', flags)
355 _save_modified_value(_config_vars, cv, flags)
356
357 return _config_vars
358
359
360 def compiler_fixup(compiler_so, cc_args):
361 """
362 This function will strip '-isysroot PATH' and '-arch ARCH' from the
363 compile flags if the user has specified one them in extra_compile_flags.
364
365 This is needed because '-arch ARCH' adds another architecture to the
366 build, without a way to remove an architecture. Furthermore GCC will
367 barf if multiple '-isysroot' arguments are present.
368 """
369 stripArch = stripSysroot = False
370
371 compiler_so = list(compiler_so)
372
373 if not _supports_universal_builds():
374 # OSX before 10.4.0, these don't support -arch and -isysroot at
375 # all.
376 stripArch = stripSysroot = True
377 else:
378 stripArch = '-arch' in cc_args
379 stripSysroot = any(arg for arg in cc_args if arg.startswith('-isysroot'))
380
381 if stripArch or 'ARCHFLAGS' in os.environ:
382 while True:
383 try:
384 index = compiler_so.index('-arch')
385 # Strip this argument and the next one:
386 del compiler_so[index:index+2]
387 except ValueError:
388 break
389
390 elif not _supports_arm64_builds():
391 # Look for "-arch arm64" and drop that
392 for idx in reversed(range(len(compiler_so))):
393 if compiler_so[idx] == '-arch' and compiler_so[idx+1] == "arm64":
394 del compiler_so[idx:idx+2]
395
396 if 'ARCHFLAGS' in os.environ and not stripArch:
397 # User specified different -arch flags in the environ,
398 # see also distutils.sysconfig
399 compiler_so = compiler_so + os.environ['ARCHFLAGS'].split()
400
401 if stripSysroot:
402 while True:
403 indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
404 if not indices:
405 break
406 index = indices[0]
407 if compiler_so[index] == '-isysroot':
408 # Strip this argument and the next one:
409 del compiler_so[index:index+2]
410 else:
411 # It's '-isysroot/some/path' in one arg
412 del compiler_so[index:index+1]
413
414 # Check if the SDK that is used during compilation actually exists,
415 # the universal build requires the usage of a universal SDK and not all
416 # users have that installed by default.
417 sysroot = None
418 argvar = cc_args
419 indices = [i for i,x in enumerate(cc_args) if x.startswith('-isysroot')]
420 if not indices:
421 argvar = compiler_so
422 indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
423
424 for idx in indices:
425 if argvar[idx] == '-isysroot':
426 sysroot = argvar[idx+1]
427 break
428 else:
429 sysroot = argvar[idx][len('-isysroot'):]
430 break
431
432 if sysroot and not os.path.isdir(sysroot):
433 sys.stderr.write(f"Compiling with an SDK that doesn't seem to exist: {sysroot}\n")
434 sys.stderr.write("Please check your Xcode installation\n")
435 sys.stderr.flush()
436
437 return compiler_so
438
439
440 def customize_config_vars(_config_vars):
441 """Customize Python build configuration variables.
442
443 Called internally from sysconfig with a mutable mapping
444 containing name/value pairs parsed from the configured
445 makefile used to build this interpreter. Returns
446 the mapping updated as needed to reflect the environment
447 in which the interpreter is running; in the case of
448 a Python from a binary installer, the installed
449 environment may be very different from the build
450 environment, i.e. different OS levels, different
451 built tools, different available CPU architectures.
452
453 This customization is performed whenever
454 distutils.sysconfig.get_config_vars() is first
455 called. It may be used in environments where no
456 compilers are present, i.e. when installing pure
457 Python dists. Customization of compiler paths
458 and detection of unavailable archs is deferred
459 until the first extension module build is
460 requested (in distutils.sysconfig.customize_compiler).
461
462 Currently called from distutils.sysconfig
463 """
464
465 if not _supports_universal_builds():
466 # On Mac OS X before 10.4, check if -arch and -isysroot
467 # are in CFLAGS or LDFLAGS and remove them if they are.
468 # This is needed when building extensions on a 10.3 system
469 # using a universal build of python.
470 _remove_universal_flags(_config_vars)
471
472 # Allow user to override all archs with ARCHFLAGS env var
473 _override_all_archs(_config_vars)
474
475 # Remove references to sdks that are not found
476 _check_for_unavailable_sdk(_config_vars)
477
478 return _config_vars
479
480
481 def customize_compiler(_config_vars):
482 """Customize compiler path and configuration variables.
483
484 This customization is performed when the first
485 extension module build is requested
486 in distutils.sysconfig.customize_compiler.
487 """
488
489 # Find a compiler to use for extension module builds
490 _find_appropriate_compiler(_config_vars)
491
492 # Remove ppc arch flags if not supported here
493 _remove_unsupported_archs(_config_vars)
494
495 # Allow user to override all archs with ARCHFLAGS env var
496 _override_all_archs(_config_vars)
497
498 return _config_vars
499
500
501 def get_platform_osx(_config_vars, osname, release, machine):
502 """Filter values for get_platform()"""
503 # called from get_platform() in sysconfig and distutils.util
504 #
505 # For our purposes, we'll assume that the system version from
506 # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
507 # to. This makes the compatibility story a bit more sane because the
508 # machine is going to compile and link as if it were
509 # MACOSX_DEPLOYMENT_TARGET.
510
511 macver = _config_vars.get('MACOSX_DEPLOYMENT_TARGET', '')
512 if macver and '.' not in macver:
513 # Ensure that the version includes at least a major
514 # and minor version, even if MACOSX_DEPLOYMENT_TARGET
515 # is set to a single-label version like "14".
516 macver += '.0'
517 macrelease = _get_system_version() or macver
518 macver = macver or macrelease
519
520 if macver:
521 release = macver
522 osname = "macosx"
523
524 # Use the original CFLAGS value, if available, so that we
525 # return the same machine type for the platform string.
526 # Otherwise, distutils may consider this a cross-compiling
527 # case and disallow installs.
528 cflags = _config_vars.get(_INITPRE+'CFLAGS',
529 _config_vars.get('CFLAGS', ''))
530 if macrelease:
531 try:
532 macrelease = tuple(int(i) for i in macrelease.split('.')[0:2])
533 except ValueError:
534 macrelease = (10, 3)
535 else:
536 # assume no universal support
537 macrelease = (10, 3)
538
539 if (macrelease >= (10, 4)) and '-arch' in cflags.strip():
540 # The universal build will build fat binaries, but not on
541 # systems before 10.4
542
543 machine = 'fat'
544
545 archs = re.findall(r'-arch\s+(\S+)', cflags)
546 archs = tuple(sorted(set(archs)))
547
548 if len(archs) == 1:
549 machine = archs[0]
550 elif archs == ('arm64', 'x86_64'):
551 machine = 'universal2'
552 elif archs == ('i386', 'ppc'):
553 machine = 'fat'
554 elif archs == ('i386', 'x86_64'):
555 machine = 'intel'
556 elif archs == ('i386', 'ppc', 'x86_64'):
557 machine = 'fat3'
558 elif archs == ('ppc64', 'x86_64'):
559 machine = 'fat64'
560 elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
561 machine = 'universal'
562 else:
563 raise ValueError(
564 "Don't know machine value for archs=%r" % (archs,))
565
566 elif machine == 'i386':
567 # On OSX the machine type returned by uname is always the
568 # 32-bit variant, even if the executable architecture is
569 # the 64-bit variant
570 if sys.maxsize >= 2**32:
571 machine = 'x86_64'
572
573 elif machine in ('PowerPC', 'Power_Macintosh'):
574 # Pick a sane name for the PPC architecture.
575 # See 'i386' case
576 if sys.maxsize >= 2**32:
577 machine = 'ppc64'
578 else:
579 machine = 'ppc'
580
581 return (osname, release, machine)