Tarek Ziade | 1231a4e | 2011-05-19 13:07:25 +0200 | [diff] [blame^] | 1 | """CCompiler implementation for Unix compilers. |
| 2 | |
| 3 | This module contains the UnixCCompiler class, a subclass of CCompiler |
| 4 | that handles the "typical" Unix-style command-line C compiler: |
| 5 | * macros defined with -Dname[=value] |
| 6 | * macros undefined with -Uname |
| 7 | * include search directories specified with -Idir |
| 8 | * libraries specified with -lllib |
| 9 | * library search directories specified with -Ldir |
| 10 | * compile handled by 'cc' (or similar) executable with -c option: |
| 11 | compiles .c to .o |
| 12 | * link static library handled by 'ar' command (possibly with 'ranlib') |
| 13 | * link shared library handled by 'cc -shared' |
| 14 | """ |
| 15 | |
| 16 | import os, sys |
| 17 | |
| 18 | from packaging.util import newer |
| 19 | from packaging.compiler.ccompiler import CCompiler |
| 20 | from packaging.compiler import gen_preprocess_options, gen_lib_options |
| 21 | from packaging.errors import (PackagingExecError, CompileError, |
| 22 | LibError, LinkError) |
| 23 | from packaging import logger |
| 24 | import sysconfig |
| 25 | |
| 26 | |
| 27 | # XXX Things not currently handled: |
| 28 | # * optimization/debug/warning flags; we just use whatever's in Python's |
| 29 | # Makefile and live with it. Is this adequate? If not, we might |
| 30 | # have to have a bunch of subclasses GNUCCompiler, SGICCompiler, |
| 31 | # SunCCompiler, and I suspect down that road lies madness. |
| 32 | # * even if we don't know a warning flag from an optimization flag, |
| 33 | # we need some way for outsiders to feed preprocessor/compiler/linker |
| 34 | # flags in to us -- eg. a sysadmin might want to mandate certain flags |
| 35 | # via a site config file, or a user might want to set something for |
| 36 | # compiling this module distribution only via the setup.py command |
| 37 | # line, whatever. As long as these options come from something on the |
| 38 | # current system, they can be as system-dependent as they like, and we |
| 39 | # should just happily stuff them into the preprocessor/compiler/linker |
| 40 | # options and carry on. |
| 41 | |
| 42 | def _darwin_compiler_fixup(compiler_so, cc_args): |
| 43 | """ |
| 44 | This function will strip '-isysroot PATH' and '-arch ARCH' from the |
| 45 | compile flags if the user has specified one them in extra_compile_flags. |
| 46 | |
| 47 | This is needed because '-arch ARCH' adds another architecture to the |
| 48 | build, without a way to remove an architecture. Furthermore GCC will |
| 49 | barf if multiple '-isysroot' arguments are present. |
| 50 | """ |
| 51 | stripArch = stripSysroot = False |
| 52 | |
| 53 | compiler_so = list(compiler_so) |
| 54 | kernel_version = os.uname()[2] # 8.4.3 |
| 55 | major_version = int(kernel_version.split('.')[0]) |
| 56 | |
| 57 | if major_version < 8: |
| 58 | # OSX before 10.4.0, these don't support -arch and -isysroot at |
| 59 | # all. |
| 60 | stripArch = stripSysroot = True |
| 61 | else: |
| 62 | stripArch = '-arch' in cc_args |
| 63 | stripSysroot = '-isysroot' in cc_args |
| 64 | |
| 65 | if stripArch or 'ARCHFLAGS' in os.environ: |
| 66 | while True: |
| 67 | try: |
| 68 | index = compiler_so.index('-arch') |
| 69 | # Strip this argument and the next one: |
| 70 | del compiler_so[index:index+2] |
| 71 | except ValueError: |
| 72 | break |
| 73 | |
| 74 | if 'ARCHFLAGS' in os.environ and not stripArch: |
| 75 | # User specified different -arch flags in the environ, |
| 76 | # see also the sysconfig |
| 77 | compiler_so = compiler_so + os.environ['ARCHFLAGS'].split() |
| 78 | |
| 79 | if stripSysroot: |
| 80 | try: |
| 81 | index = compiler_so.index('-isysroot') |
| 82 | # Strip this argument and the next one: |
| 83 | del compiler_so[index:index+2] |
| 84 | except ValueError: |
| 85 | pass |
| 86 | |
| 87 | # Check if the SDK that is used during compilation actually exists, |
| 88 | # the universal build requires the usage of a universal SDK and not all |
| 89 | # users have that installed by default. |
| 90 | sysroot = None |
| 91 | if '-isysroot' in cc_args: |
| 92 | idx = cc_args.index('-isysroot') |
| 93 | sysroot = cc_args[idx+1] |
| 94 | elif '-isysroot' in compiler_so: |
| 95 | idx = compiler_so.index('-isysroot') |
| 96 | sysroot = compiler_so[idx+1] |
| 97 | |
| 98 | if sysroot and not os.path.isdir(sysroot): |
| 99 | logger.warning( |
| 100 | "compiling with an SDK that doesn't seem to exist: %r;\n" |
| 101 | "please check your Xcode installation", sysroot) |
| 102 | |
| 103 | return compiler_so |
| 104 | |
| 105 | class UnixCCompiler(CCompiler): |
| 106 | |
| 107 | name = 'unix' |
| 108 | description = 'Standard UNIX-style compiler' |
| 109 | |
| 110 | # These are used by CCompiler in two places: the constructor sets |
| 111 | # instance attributes 'preprocessor', 'compiler', etc. from them, and |
| 112 | # 'set_executable()' allows any of these to be set. The defaults here |
| 113 | # are pretty generic; they will probably have to be set by an outsider |
| 114 | # (eg. using information discovered by the sysconfig about building |
| 115 | # Python extensions). |
| 116 | executables = {'preprocessor' : None, |
| 117 | 'compiler' : ["cc"], |
| 118 | 'compiler_so' : ["cc"], |
| 119 | 'compiler_cxx' : ["cc"], |
| 120 | 'linker_so' : ["cc", "-shared"], |
| 121 | 'linker_exe' : ["cc"], |
| 122 | 'archiver' : ["ar", "-cr"], |
| 123 | 'ranlib' : None, |
| 124 | } |
| 125 | |
| 126 | if sys.platform[:6] == "darwin": |
| 127 | executables['ranlib'] = ["ranlib"] |
| 128 | |
| 129 | # Needed for the filename generation methods provided by the base |
| 130 | # class, CCompiler. NB. whoever instantiates/uses a particular |
| 131 | # UnixCCompiler instance should set 'shared_lib_ext' -- we set a |
| 132 | # reasonable common default here, but it's not necessarily used on all |
| 133 | # Unices! |
| 134 | |
| 135 | src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"] |
| 136 | obj_extension = ".o" |
| 137 | static_lib_extension = ".a" |
| 138 | shared_lib_extension = ".so" |
| 139 | dylib_lib_extension = ".dylib" |
| 140 | static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" |
| 141 | if sys.platform == "cygwin": |
| 142 | exe_extension = ".exe" |
| 143 | |
| 144 | def preprocess(self, source, |
| 145 | output_file=None, macros=None, include_dirs=None, |
| 146 | extra_preargs=None, extra_postargs=None): |
| 147 | ignore, macros, include_dirs = \ |
| 148 | self._fix_compile_args(None, macros, include_dirs) |
| 149 | pp_opts = gen_preprocess_options(macros, include_dirs) |
| 150 | pp_args = self.preprocessor + pp_opts |
| 151 | if output_file: |
| 152 | pp_args.extend(('-o', output_file)) |
| 153 | if extra_preargs: |
| 154 | pp_args[:0] = extra_preargs |
| 155 | if extra_postargs: |
| 156 | pp_args.extend(extra_postargs) |
| 157 | pp_args.append(source) |
| 158 | |
| 159 | # We need to preprocess: either we're being forced to, or we're |
| 160 | # generating output to stdout, or there's a target output file and |
| 161 | # the source file is newer than the target (or the target doesn't |
| 162 | # exist). |
| 163 | if self.force or output_file is None or newer(source, output_file): |
| 164 | if output_file: |
| 165 | self.mkpath(os.path.dirname(output_file)) |
| 166 | try: |
| 167 | self.spawn(pp_args) |
| 168 | except PackagingExecError as msg: |
| 169 | raise CompileError(msg) |
| 170 | |
| 171 | def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): |
| 172 | compiler_so = self.compiler_so |
| 173 | if sys.platform == 'darwin': |
| 174 | compiler_so = _darwin_compiler_fixup(compiler_so, cc_args + extra_postargs) |
| 175 | try: |
| 176 | self.spawn(compiler_so + cc_args + [src, '-o', obj] + |
| 177 | extra_postargs) |
| 178 | except PackagingExecError as msg: |
| 179 | raise CompileError(msg) |
| 180 | |
| 181 | def create_static_lib(self, objects, output_libname, |
| 182 | output_dir=None, debug=False, target_lang=None): |
| 183 | objects, output_dir = self._fix_object_args(objects, output_dir) |
| 184 | |
| 185 | output_filename = \ |
| 186 | self.library_filename(output_libname, output_dir=output_dir) |
| 187 | |
| 188 | if self._need_link(objects, output_filename): |
| 189 | self.mkpath(os.path.dirname(output_filename)) |
| 190 | self.spawn(self.archiver + |
| 191 | [output_filename] + |
| 192 | objects + self.objects) |
| 193 | |
| 194 | # Not many Unices required ranlib anymore -- SunOS 4.x is, I |
| 195 | # think the only major Unix that does. Maybe we need some |
| 196 | # platform intelligence here to skip ranlib if it's not |
| 197 | # needed -- or maybe Python's configure script took care of |
| 198 | # it for us, hence the check for leading colon. |
| 199 | if self.ranlib: |
| 200 | try: |
| 201 | self.spawn(self.ranlib + [output_filename]) |
| 202 | except PackagingExecError as msg: |
| 203 | raise LibError(msg) |
| 204 | else: |
| 205 | logger.debug("skipping %s (up-to-date)", output_filename) |
| 206 | |
| 207 | def link(self, target_desc, objects, |
| 208 | output_filename, output_dir=None, libraries=None, |
| 209 | library_dirs=None, runtime_library_dirs=None, |
| 210 | export_symbols=None, debug=False, extra_preargs=None, |
| 211 | extra_postargs=None, build_temp=None, target_lang=None): |
| 212 | objects, output_dir = self._fix_object_args(objects, output_dir) |
| 213 | libraries, library_dirs, runtime_library_dirs = \ |
| 214 | self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) |
| 215 | |
| 216 | lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, |
| 217 | libraries) |
| 218 | if type(output_dir) not in (str, type(None)): |
| 219 | raise TypeError("'output_dir' must be a string or None") |
| 220 | if output_dir is not None: |
| 221 | output_filename = os.path.join(output_dir, output_filename) |
| 222 | |
| 223 | if self._need_link(objects, output_filename): |
| 224 | ld_args = (objects + self.objects + |
| 225 | lib_opts + ['-o', output_filename]) |
| 226 | if debug: |
| 227 | ld_args[:0] = ['-g'] |
| 228 | if extra_preargs: |
| 229 | ld_args[:0] = extra_preargs |
| 230 | if extra_postargs: |
| 231 | ld_args.extend(extra_postargs) |
| 232 | self.mkpath(os.path.dirname(output_filename)) |
| 233 | try: |
| 234 | if target_desc == CCompiler.EXECUTABLE: |
| 235 | linker = self.linker_exe[:] |
| 236 | else: |
| 237 | linker = self.linker_so[:] |
| 238 | if target_lang == "c++" and self.compiler_cxx: |
| 239 | # skip over environment variable settings if /usr/bin/env |
| 240 | # is used to set up the linker's environment. |
| 241 | # This is needed on OSX. Note: this assumes that the |
| 242 | # normal and C++ compiler have the same environment |
| 243 | # settings. |
| 244 | i = 0 |
| 245 | if os.path.basename(linker[0]) == "env": |
| 246 | i = 1 |
| 247 | while '=' in linker[i]: |
| 248 | i = i + 1 |
| 249 | |
| 250 | linker[i] = self.compiler_cxx[i] |
| 251 | |
| 252 | if sys.platform == 'darwin': |
| 253 | linker = _darwin_compiler_fixup(linker, ld_args) |
| 254 | |
| 255 | self.spawn(linker + ld_args) |
| 256 | except PackagingExecError as msg: |
| 257 | raise LinkError(msg) |
| 258 | else: |
| 259 | logger.debug("skipping %s (up-to-date)", output_filename) |
| 260 | |
| 261 | # -- Miscellaneous methods ----------------------------------------- |
| 262 | # These are all used by the 'gen_lib_options() function, in |
| 263 | # ccompiler.py. |
| 264 | |
| 265 | def library_dir_option(self, dir): |
| 266 | return "-L" + dir |
| 267 | |
| 268 | def _is_gcc(self, compiler_name): |
| 269 | return "gcc" in compiler_name or "g++" in compiler_name |
| 270 | |
| 271 | def runtime_library_dir_option(self, dir): |
| 272 | # XXX Hackish, at the very least. See Python bug #445902: |
| 273 | # http://sourceforge.net/tracker/index.php |
| 274 | # ?func=detail&aid=445902&group_id=5470&atid=105470 |
| 275 | # Linkers on different platforms need different options to |
| 276 | # specify that directories need to be added to the list of |
| 277 | # directories searched for dependencies when a dynamic library |
| 278 | # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to |
| 279 | # be told to pass the -R option through to the linker, whereas |
| 280 | # other compilers and gcc on other systems just know this. |
| 281 | # Other compilers may need something slightly different. At |
| 282 | # this time, there's no way to determine this information from |
| 283 | # the configuration data stored in the Python installation, so |
| 284 | # we use this hack. |
| 285 | |
| 286 | compiler = os.path.basename(sysconfig.get_config_var("CC")) |
| 287 | if sys.platform[:6] == "darwin": |
| 288 | # MacOSX's linker doesn't understand the -R flag at all |
| 289 | return "-L" + dir |
| 290 | elif sys.platform[:5] == "hp-ux": |
| 291 | if self._is_gcc(compiler): |
| 292 | return ["-Wl,+s", "-L" + dir] |
| 293 | return ["+s", "-L" + dir] |
| 294 | elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5": |
| 295 | return ["-rpath", dir] |
| 296 | elif self._is_gcc(compiler): |
| 297 | # gcc on non-GNU systems does not need -Wl, but can |
| 298 | # use it anyway. Since distutils has always passed in |
| 299 | # -Wl whenever gcc was used in the past it is probably |
| 300 | # safest to keep doing so. |
| 301 | if sysconfig.get_config_var("GNULD") == "yes": |
| 302 | # GNU ld needs an extra option to get a RUNPATH |
| 303 | # instead of just an RPATH. |
| 304 | return "-Wl,--enable-new-dtags,-R" + dir |
| 305 | else: |
| 306 | return "-Wl,-R" + dir |
| 307 | elif sys.platform[:3] == "aix": |
| 308 | return "-blibpath:" + dir |
| 309 | else: |
| 310 | # No idea how --enable-new-dtags would be passed on to |
| 311 | # ld if this system was using GNU ld. Don't know if a |
| 312 | # system like this even exists. |
| 313 | return "-R" + dir |
| 314 | |
| 315 | def library_option(self, lib): |
| 316 | return "-l" + lib |
| 317 | |
| 318 | def find_library_file(self, dirs, lib, debug=False): |
| 319 | shared_f = self.library_filename(lib, lib_type='shared') |
| 320 | dylib_f = self.library_filename(lib, lib_type='dylib') |
| 321 | static_f = self.library_filename(lib, lib_type='static') |
| 322 | |
| 323 | for dir in dirs: |
| 324 | shared = os.path.join(dir, shared_f) |
| 325 | dylib = os.path.join(dir, dylib_f) |
| 326 | static = os.path.join(dir, static_f) |
| 327 | # We're second-guessing the linker here, with not much hard |
| 328 | # data to go on: GCC seems to prefer the shared library, so I'm |
| 329 | # assuming that *all* Unix C compilers do. And of course I'm |
| 330 | # ignoring even GCC's "-static" option. So sue me. |
| 331 | if os.path.exists(dylib): |
| 332 | return dylib |
| 333 | elif os.path.exists(shared): |
| 334 | return shared |
| 335 | elif os.path.exists(static): |
| 336 | return static |
| 337 | |
| 338 | # Oops, didn't find it in *any* of 'dirs' |
| 339 | return None |