unix.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. """distutils.unixccompiler
  2. Contains the UnixCCompiler class, a subclass of CCompiler that handles
  3. the "typical" Unix-style command-line C compiler:
  4. * macros defined with -Dname[=value]
  5. * macros undefined with -Uname
  6. * include search directories specified with -Idir
  7. * libraries specified with -lllib
  8. * library search directories specified with -Ldir
  9. * compile handled by 'cc' (or similar) executable with -c option:
  10. compiles .c to .o
  11. * link static library handled by 'ar' command (possibly with 'ranlib')
  12. * link shared library handled by 'cc -shared'
  13. """
  14. from __future__ import annotations
  15. import itertools
  16. import os
  17. import re
  18. import shlex
  19. import sys
  20. from collections.abc import Iterable
  21. from ... import sysconfig
  22. from ..._log import log
  23. from ..._macos_compat import compiler_fixup
  24. from ..._modified import newer
  25. from ...compat import consolidate_linker_args
  26. from ...errors import DistutilsExecError
  27. from . import base
  28. from .base import _Macro, gen_lib_options, gen_preprocess_options
  29. from .errors import (
  30. CompileError,
  31. LibError,
  32. LinkError,
  33. )
  34. # XXX Things not currently handled:
  35. # * optimization/debug/warning flags; we just use whatever's in Python's
  36. # Makefile and live with it. Is this adequate? If not, we might
  37. # have to have a bunch of subclasses GNUCCompiler, SGICCompiler,
  38. # SunCCompiler, and I suspect down that road lies madness.
  39. # * even if we don't know a warning flag from an optimization flag,
  40. # we need some way for outsiders to feed preprocessor/compiler/linker
  41. # flags in to us -- eg. a sysadmin might want to mandate certain flags
  42. # via a site config file, or a user might want to set something for
  43. # compiling this module distribution only via the setup.py command
  44. # line, whatever. As long as these options come from something on the
  45. # current system, they can be as system-dependent as they like, and we
  46. # should just happily stuff them into the preprocessor/compiler/linker
  47. # options and carry on.
  48. def _split_env(cmd):
  49. """
  50. For macOS, split command into 'env' portion (if any)
  51. and the rest of the linker command.
  52. >>> _split_env(['a', 'b', 'c'])
  53. ([], ['a', 'b', 'c'])
  54. >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
  55. (['/usr/bin/env', 'A=3'], ['gcc'])
  56. """
  57. pivot = 0
  58. if os.path.basename(cmd[0]) == "env":
  59. pivot = 1
  60. while '=' in cmd[pivot]:
  61. pivot += 1
  62. return cmd[:pivot], cmd[pivot:]
  63. def _split_aix(cmd):
  64. """
  65. AIX platforms prefix the compiler with the ld_so_aix
  66. script, so split that from the linker command.
  67. >>> _split_aix(['a', 'b', 'c'])
  68. ([], ['a', 'b', 'c'])
  69. >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
  70. (['/bin/foo/ld_so_aix'], ['gcc'])
  71. """
  72. pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
  73. return cmd[:pivot], cmd[pivot:]
  74. def _linker_params(linker_cmd, compiler_cmd):
  75. """
  76. The linker command usually begins with the compiler
  77. command (possibly multiple elements), followed by zero or more
  78. params for shared library building.
  79. If the LDSHARED env variable overrides the linker command,
  80. however, the commands may not match.
  81. Return the best guess of the linker parameters by stripping
  82. the linker command. If the compiler command does not
  83. match the linker command, assume the linker command is
  84. just the first element.
  85. >>> _linker_params('gcc foo bar'.split(), ['gcc'])
  86. ['foo', 'bar']
  87. >>> _linker_params('gcc foo bar'.split(), ['other'])
  88. ['foo', 'bar']
  89. >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
  90. ['foo', 'bar']
  91. >>> _linker_params(['gcc'], ['gcc'])
  92. []
  93. """
  94. c_len = len(compiler_cmd)
  95. pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
  96. return linker_cmd[pivot:]
  97. class Compiler(base.Compiler):
  98. compiler_type = 'unix'
  99. # These are used by CCompiler in two places: the constructor sets
  100. # instance attributes 'preprocessor', 'compiler', etc. from them, and
  101. # 'set_executable()' allows any of these to be set. The defaults here
  102. # are pretty generic; they will probably have to be set by an outsider
  103. # (eg. using information discovered by the sysconfig about building
  104. # Python extensions).
  105. executables = {
  106. 'preprocessor': None,
  107. 'compiler': ["cc"],
  108. 'compiler_so': ["cc"],
  109. 'compiler_cxx': ["c++"],
  110. 'compiler_so_cxx': ["c++"],
  111. 'linker_so': ["cc", "-shared"],
  112. 'linker_so_cxx': ["c++", "-shared"],
  113. 'linker_exe': ["cc"],
  114. 'linker_exe_cxx': ["c++", "-shared"],
  115. 'archiver': ["ar", "-cr"],
  116. 'ranlib': None,
  117. }
  118. if sys.platform[:6] == "darwin":
  119. executables['ranlib'] = ["ranlib"]
  120. # Needed for the filename generation methods provided by the base
  121. # class, CCompiler. NB. whoever instantiates/uses a particular
  122. # UnixCCompiler instance should set 'shared_lib_ext' -- we set a
  123. # reasonable common default here, but it's not necessarily used on all
  124. # Unices!
  125. src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"]
  126. obj_extension = ".o"
  127. static_lib_extension = ".a"
  128. shared_lib_extension = ".so"
  129. dylib_lib_extension = ".dylib"
  130. xcode_stub_lib_extension = ".tbd"
  131. static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
  132. xcode_stub_lib_format = dylib_lib_format
  133. if sys.platform == "cygwin":
  134. exe_extension = ".exe"
  135. shared_lib_extension = ".dll.a"
  136. dylib_lib_extension = ".dll"
  137. dylib_lib_format = "cyg%s%s"
  138. def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
  139. """Remove standard library path from rpath"""
  140. libraries, library_dirs, runtime_library_dirs = super()._fix_lib_args(
  141. libraries, library_dirs, runtime_library_dirs
  142. )
  143. libdir = sysconfig.get_config_var('LIBDIR')
  144. if (
  145. runtime_library_dirs
  146. and libdir.startswith("/usr/lib")
  147. and (libdir in runtime_library_dirs)
  148. ):
  149. runtime_library_dirs.remove(libdir)
  150. return libraries, library_dirs, runtime_library_dirs
  151. def preprocess(
  152. self,
  153. source: str | os.PathLike[str],
  154. output_file: str | os.PathLike[str] | None = None,
  155. macros: list[_Macro] | None = None,
  156. include_dirs: list[str] | tuple[str, ...] | None = None,
  157. extra_preargs: list[str] | None = None,
  158. extra_postargs: Iterable[str] | None = None,
  159. ):
  160. fixed_args = self._fix_compile_args(None, macros, include_dirs)
  161. ignore, macros, include_dirs = fixed_args
  162. pp_opts = gen_preprocess_options(macros, include_dirs)
  163. pp_args = self.preprocessor + pp_opts
  164. if output_file:
  165. pp_args.extend(['-o', output_file])
  166. if extra_preargs:
  167. pp_args[:0] = extra_preargs
  168. if extra_postargs:
  169. pp_args.extend(extra_postargs)
  170. pp_args.append(source)
  171. # reasons to preprocess:
  172. # - force is indicated
  173. # - output is directed to stdout
  174. # - source file is newer than the target
  175. preprocess = self.force or output_file is None or newer(source, output_file)
  176. if not preprocess:
  177. return
  178. if output_file:
  179. self.mkpath(os.path.dirname(output_file))
  180. try:
  181. self.spawn(pp_args)
  182. except DistutilsExecError as msg:
  183. raise CompileError(msg)
  184. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  185. compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
  186. compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs)
  187. try:
  188. if self.detect_language(src) == 'c++':
  189. self.spawn(
  190. compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs
  191. )
  192. else:
  193. self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
  194. except DistutilsExecError as msg:
  195. raise CompileError(msg)
  196. def create_static_lib(
  197. self, objects, output_libname, output_dir=None, debug=False, target_lang=None
  198. ):
  199. objects, output_dir = self._fix_object_args(objects, output_dir)
  200. output_filename = self.library_filename(output_libname, output_dir=output_dir)
  201. if self._need_link(objects, output_filename):
  202. self.mkpath(os.path.dirname(output_filename))
  203. self.spawn(self.archiver + [output_filename] + objects + self.objects)
  204. # Not many Unices required ranlib anymore -- SunOS 4.x is, I
  205. # think the only major Unix that does. Maybe we need some
  206. # platform intelligence here to skip ranlib if it's not
  207. # needed -- or maybe Python's configure script took care of
  208. # it for us, hence the check for leading colon.
  209. if self.ranlib:
  210. try:
  211. self.spawn(self.ranlib + [output_filename])
  212. except DistutilsExecError as msg:
  213. raise LibError(msg)
  214. else:
  215. log.debug("skipping %s (up-to-date)", output_filename)
  216. def link(
  217. self,
  218. target_desc,
  219. objects: list[str] | tuple[str, ...],
  220. output_filename,
  221. output_dir: str | None = None,
  222. libraries: list[str] | tuple[str, ...] | None = None,
  223. library_dirs: list[str] | tuple[str, ...] | None = None,
  224. runtime_library_dirs: list[str] | tuple[str, ...] | None = None,
  225. export_symbols=None,
  226. debug=False,
  227. extra_preargs=None,
  228. extra_postargs=None,
  229. build_temp=None,
  230. target_lang=None,
  231. ):
  232. objects, output_dir = self._fix_object_args(objects, output_dir)
  233. fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
  234. libraries, library_dirs, runtime_library_dirs = fixed_args
  235. lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
  236. if not isinstance(output_dir, (str, type(None))):
  237. raise TypeError("'output_dir' must be a string or None")
  238. if output_dir is not None:
  239. output_filename = os.path.join(output_dir, output_filename)
  240. if self._need_link(objects, output_filename):
  241. ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
  242. if debug:
  243. ld_args[:0] = ['-g']
  244. if extra_preargs:
  245. ld_args[:0] = extra_preargs
  246. if extra_postargs:
  247. ld_args.extend(extra_postargs)
  248. self.mkpath(os.path.dirname(output_filename))
  249. try:
  250. # Select a linker based on context: linker_exe when
  251. # building an executable or linker_so (with shared options)
  252. # when building a shared library.
  253. building_exe = target_desc == base.Compiler.EXECUTABLE
  254. target_cxx = target_lang == "c++"
  255. linker = (
  256. (self.linker_exe_cxx if target_cxx else self.linker_exe)
  257. if building_exe
  258. else (self.linker_so_cxx if target_cxx else self.linker_so)
  259. )[:]
  260. if target_cxx and self.compiler_cxx:
  261. env, linker_ne = _split_env(linker)
  262. aix, linker_na = _split_aix(linker_ne)
  263. _, compiler_cxx_ne = _split_env(self.compiler_cxx)
  264. _, linker_exe_ne = _split_env(self.linker_exe_cxx)
  265. params = _linker_params(linker_na, linker_exe_ne)
  266. linker = env + aix + compiler_cxx_ne + params
  267. linker = compiler_fixup(linker, ld_args)
  268. self.spawn(linker + ld_args)
  269. except DistutilsExecError as msg:
  270. raise LinkError(msg)
  271. else:
  272. log.debug("skipping %s (up-to-date)", output_filename)
  273. # -- Miscellaneous methods -----------------------------------------
  274. # These are all used by the 'gen_lib_options() function, in
  275. # ccompiler.py.
  276. def library_dir_option(self, dir):
  277. return "-L" + dir
  278. def _is_gcc(self):
  279. cc_var = sysconfig.get_config_var("CC")
  280. compiler = os.path.basename(shlex.split(cc_var)[0])
  281. return "gcc" in compiler or "g++" in compiler
  282. def runtime_library_dir_option(self, dir: str) -> str | list[str]: # type: ignore[override] # Fixed in pypa/distutils#339
  283. # XXX Hackish, at the very least. See Python bug #445902:
  284. # https://bugs.python.org/issue445902
  285. # Linkers on different platforms need different options to
  286. # specify that directories need to be added to the list of
  287. # directories searched for dependencies when a dynamic library
  288. # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to
  289. # be told to pass the -R option through to the linker, whereas
  290. # other compilers and gcc on other systems just know this.
  291. # Other compilers may need something slightly different. At
  292. # this time, there's no way to determine this information from
  293. # the configuration data stored in the Python installation, so
  294. # we use this hack.
  295. if sys.platform[:6] == "darwin":
  296. from distutils.util import get_macosx_target_ver, split_version
  297. macosx_target_ver = get_macosx_target_ver()
  298. if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
  299. return "-Wl,-rpath," + dir
  300. else: # no support for -rpath on earlier macOS versions
  301. return "-L" + dir
  302. elif sys.platform[:7] == "freebsd":
  303. return "-Wl,-rpath=" + dir
  304. elif sys.platform[:5] == "hp-ux":
  305. return [
  306. "-Wl,+s" if self._is_gcc() else "+s",
  307. "-L" + dir,
  308. ]
  309. # For all compilers, `-Wl` is the presumed way to pass a
  310. # compiler option to the linker
  311. if sysconfig.get_config_var("GNULD") == "yes":
  312. return consolidate_linker_args([
  313. # Force RUNPATH instead of RPATH
  314. "-Wl,--enable-new-dtags",
  315. "-Wl,-rpath," + dir,
  316. ])
  317. else:
  318. return "-Wl,-R" + dir
  319. def library_option(self, lib):
  320. return "-l" + lib
  321. @staticmethod
  322. def _library_root(dir):
  323. """
  324. macOS users can specify an alternate SDK using'-isysroot'.
  325. Calculate the SDK root if it is specified.
  326. Note that, as of Xcode 7, Apple SDKs may contain textual stub
  327. libraries with .tbd extensions rather than the normal .dylib
  328. shared libraries installed in /. The Apple compiler tool
  329. chain handles this transparently but it can cause problems
  330. for programs that are being built with an SDK and searching
  331. for specific libraries. Callers of find_library_file need to
  332. keep in mind that the base filename of the returned SDK library
  333. file might have a different extension from that of the library
  334. file installed on the running system, for example:
  335. /Applications/Xcode.app/Contents/Developer/Platforms/
  336. MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
  337. usr/lib/libedit.tbd
  338. vs
  339. /usr/lib/libedit.dylib
  340. """
  341. cflags = sysconfig.get_config_var('CFLAGS')
  342. match = re.search(r'-isysroot\s*(\S+)', cflags)
  343. apply_root = (
  344. sys.platform == 'darwin'
  345. and match
  346. and (
  347. dir.startswith('/System/')
  348. or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
  349. )
  350. )
  351. return os.path.join(match.group(1), dir[1:]) if apply_root else dir
  352. def find_library_file(self, dirs, lib, debug=False):
  353. """
  354. Second-guess the linker with not much hard
  355. data to go on: GCC seems to prefer the shared library, so
  356. assume that *all* Unix C compilers do,
  357. ignoring even GCC's "-static" option.
  358. """
  359. lib_names = (
  360. self.library_filename(lib, lib_type=type)
  361. for type in 'dylib xcode_stub shared static'.split()
  362. )
  363. roots = map(self._library_root, dirs)
  364. searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names))
  365. found = filter(os.path.exists, searched)
  366. # Return None if it could not be found in any dir.
  367. return next(found, None)