unixccompiler.py 15 KB

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