unixccompiler.py 15 KB

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