Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

unixccompiler.py 15KB

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