home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / distutils / msvccompiler.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  20.9 KB  |  601 lines

  1. """distutils.msvccompiler
  2.  
  3. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  4. for the Microsoft Visual Studio.
  5. """
  6.  
  7. # Written by Perry Stoll
  8. # hacked by Robin Becker and Thomas Heller to do a better job of
  9. #   finding DevStudio (through the registry)
  10.  
  11. # This module should be kept compatible with Python 2.1.
  12.  
  13. __revision__ = "$Id: msvccompiler.py 50980 2006-07-30 13:31:20Z martin.v.loewis $"
  14.  
  15. import sys, os, string
  16. from distutils.errors import \
  17.      DistutilsExecError, DistutilsPlatformError, \
  18.      CompileError, LibError, LinkError
  19. from distutils.ccompiler import \
  20.      CCompiler, gen_preprocess_options, gen_lib_options
  21. from distutils import log
  22.  
  23. _can_read_reg = 0
  24. try:
  25.     import _winreg
  26.  
  27.     _can_read_reg = 1
  28.     hkey_mod = _winreg
  29.  
  30.     RegOpenKeyEx = _winreg.OpenKeyEx
  31.     RegEnumKey = _winreg.EnumKey
  32.     RegEnumValue = _winreg.EnumValue
  33.     RegError = _winreg.error
  34.  
  35. except ImportError:
  36.     try:
  37.         import win32api
  38.         import win32con
  39.         _can_read_reg = 1
  40.         hkey_mod = win32con
  41.  
  42.         RegOpenKeyEx = win32api.RegOpenKeyEx
  43.         RegEnumKey = win32api.RegEnumKey
  44.         RegEnumValue = win32api.RegEnumValue
  45.         RegError = win32api.error
  46.  
  47.     except ImportError:
  48.         log.info("Warning: Can't read registry to find the "
  49.                  "necessary compiler setting\n"
  50.                  "Make sure that Python modules _winreg, "
  51.                  "win32api or win32con are installed.")
  52.         pass
  53.  
  54. if _can_read_reg:
  55.     HKEYS = (hkey_mod.HKEY_USERS,
  56.              hkey_mod.HKEY_CURRENT_USER,
  57.              hkey_mod.HKEY_LOCAL_MACHINE,
  58.              hkey_mod.HKEY_CLASSES_ROOT)
  59.  
  60. def read_keys(base, key):
  61.     """Return list of registry keys."""
  62.  
  63.     try:
  64.         handle = RegOpenKeyEx(base, key)
  65.     except RegError:
  66.         return None
  67.     L = []
  68.     i = 0
  69.     while 1:
  70.         try:
  71.             k = RegEnumKey(handle, i)
  72.         except RegError:
  73.             break
  74.         L.append(k)
  75.         i = i + 1
  76.     return L
  77.  
  78. def read_values(base, key):
  79.     """Return dict of registry keys and values.
  80.  
  81.     All names are converted to lowercase.
  82.     """
  83.     try:
  84.         handle = RegOpenKeyEx(base, key)
  85.     except RegError:
  86.         return None
  87.     d = {}
  88.     i = 0
  89.     while 1:
  90.         try:
  91.             name, value, type = RegEnumValue(handle, i)
  92.         except RegError:
  93.             break
  94.         name = name.lower()
  95.         d[convert_mbcs(name)] = convert_mbcs(value)
  96.         i = i + 1
  97.     return d
  98.  
  99. def convert_mbcs(s):
  100.     enc = getattr(s, "encode", None)
  101.     if enc is not None:
  102.         try:
  103.             s = enc("mbcs")
  104.         except UnicodeError:
  105.             pass
  106.     return s
  107.  
  108. class MacroExpander:
  109.  
  110.     def __init__(self, version):
  111.         self.macros = {}
  112.         self.load_macros(version)
  113.  
  114.     def set_macro(self, macro, path, key):
  115.         for base in HKEYS:
  116.             d = read_values(base, path)
  117.             if d:
  118.                 self.macros["$(%s)" % macro] = d[key]
  119.                 break
  120.  
  121.     def load_macros(self, version):
  122.         vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
  123.         self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
  124.         self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")
  125.         net = r"Software\Microsoft\.NETFramework"
  126.         self.set_macro("FrameworkDir", net, "installroot")
  127.         try:
  128.             if version > 7.0:
  129.                 self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
  130.             else:
  131.                 self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
  132.         except KeyError, exc: #
  133.             raise DistutilsPlatformError, \
  134.                   ("""Python was built with Visual Studio 2003;
  135. extensions must be built with a compiler than can generate compatible binaries.
  136. Visual Studio 2003 was not found on this system. If you have Cygwin installed,
  137. you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
  138.  
  139.         p = r"Software\Microsoft\NET Framework Setup\Product"
  140.         for base in HKEYS:
  141.             try:
  142.                 h = RegOpenKeyEx(base, p)
  143.             except RegError:
  144.                 continue
  145.             key = RegEnumKey(h, 0)
  146.             d = read_values(base, r"%s\%s" % (p, key))
  147.             self.macros["$(FrameworkVersion)"] = d["version"]
  148.  
  149.     def sub(self, s):
  150.         for k, v in self.macros.items():
  151.             s = string.replace(s, k, v)
  152.         return s
  153.  
  154. def get_build_version():
  155.     """Return the version of MSVC that was used to build Python.
  156.  
  157.     For Python 2.3 and up, the version number is included in
  158.     sys.version.  For earlier versions, assume the compiler is MSVC 6.
  159.     """
  160.  
  161.     prefix = "MSC v."
  162.     i = string.find(sys.version, prefix)
  163.     if i == -1:
  164.         return 6
  165.     i = i + len(prefix)
  166.     s, rest = sys.version[i:].split(" ", 1)
  167.     majorVersion = int(s[:-2]) - 6
  168.     minorVersion = int(s[2:3]) / 10.0
  169.     # I don't think paths are affected by minor version in version 6
  170.     if majorVersion == 6:
  171.         minorVersion = 0
  172.     if majorVersion >= 6:
  173.         return majorVersion + minorVersion
  174.     # else we don't know what version of the compiler this is
  175.     return None
  176.  
  177.  
  178. class MSVCCompiler (CCompiler) :
  179.     """Concrete class that implements an interface to Microsoft Visual C++,
  180.        as defined by the CCompiler abstract class."""
  181.  
  182.     compiler_type = 'msvc'
  183.  
  184.     # Just set this so CCompiler's constructor doesn't barf.  We currently
  185.     # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  186.     # as it really isn't necessary for this sort of single-compiler class.
  187.     # Would be nice to have a consistent interface with UnixCCompiler,
  188.     # though, so it's worth thinking about.
  189.     executables = {}
  190.  
  191.     # Private class data (need to distinguish C from C++ source for compiler)
  192.     _c_extensions = ['.c']
  193.     _cpp_extensions = ['.cc', '.cpp', '.cxx']
  194.     _rc_extensions = ['.rc']
  195.     _mc_extensions = ['.mc']
  196.  
  197.     # Needed for the filename generation methods provided by the
  198.     # base class, CCompiler.
  199.     src_extensions = (_c_extensions + _cpp_extensions +
  200.                       _rc_extensions + _mc_extensions)
  201.     res_extension = '.res'
  202.     obj_extension = '.obj'
  203.     static_lib_extension = '.lib'
  204.     shared_lib_extension = '.dll'
  205.     static_lib_format = shared_lib_format = '%s%s'
  206.     exe_extension = '.exe'
  207.  
  208.     def __init__ (self, verbose=0, dry_run=0, force=0):
  209.         CCompiler.__init__ (self, verbose, dry_run, force)
  210.         self.__version = get_build_version()
  211.         if self.__version >= 7:
  212.             self.__root = r"Software\Microsoft\VisualStudio"
  213.             self.__macros = MacroExpander(self.__version)
  214.         else:
  215.             self.__root = r"Software\Microsoft\Devstudio"
  216.         self.initialized = False
  217.  
  218.     def initialize(self):
  219.         self.__paths = self.get_msvc_paths("path")
  220.  
  221.         if len (self.__paths) == 0:
  222.             raise DistutilsPlatformError, \
  223.                   ("Python was built with version %s of Visual Studio, "
  224.                    "and extensions need to be built with the same "
  225.                    "version of the compiler, but it isn't installed." % self.__version)
  226.  
  227.         self.cc = self.find_exe("cl.exe")
  228.         self.linker = self.find_exe("link.exe")
  229.         self.lib = self.find_exe("lib.exe")
  230.         self.rc = self.find_exe("rc.exe")   # resource compiler
  231.         self.mc = self.find_exe("mc.exe")   # message compiler
  232.         self.set_path_env_var('lib')
  233.         self.set_path_env_var('include')
  234.  
  235.         # extend the MSVC path with the current path
  236.         try:
  237.             for p in string.split(os.environ['path'], ';'):
  238.                 self.__paths.append(p)
  239.         except KeyError:
  240.             pass
  241.         os.environ['path'] = string.join(self.__paths, ';')
  242.  
  243.         self.preprocess_options = None
  244.         self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' ,
  245.                                  '/DNDEBUG']
  246.         self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX',
  247.                                       '/Z7', '/D_DEBUG']
  248.  
  249.         self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  250.         if self.__version >= 7:
  251.             self.ldflags_shared_debug = [
  252.                 '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
  253.                 ]
  254.         else:
  255.             self.ldflags_shared_debug = [
  256.                 '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
  257.                 ]
  258.         self.ldflags_static = [ '/nologo']
  259.  
  260.         self.initialized = True
  261.  
  262.  
  263.     # -- Worker methods ------------------------------------------------
  264.  
  265.     def object_filenames (self,
  266.                           source_filenames,
  267.                           strip_dir=0,
  268.                           output_dir=''):
  269.         # Copied from ccompiler.py, extended to return .res as 'object'-file
  270.         # for .rc input file
  271.         if output_dir is None: output_dir = ''
  272.         obj_names = []
  273.         for src_name in source_filenames:
  274.             (base, ext) = os.path.splitext (src_name)
  275.             base = os.path.splitdrive(base)[1] # Chop off the drive
  276.             base = base[os.path.isabs(base):]  # If abs, chop off leading /
  277.             if ext not in self.src_extensions:
  278.                 # Better to raise an exception instead of silently continuing
  279.                 # and later complain about sources and targets having
  280.                 # different lengths
  281.                 raise CompileError ("Don't know how to compile %s" % src_name)
  282.             if strip_dir:
  283.                 base = os.path.basename (base)
  284.             if ext in self._rc_extensions:
  285.                 obj_names.append (os.path.join (output_dir,
  286.                                                 base + self.res_extension))
  287.             elif ext in self._mc_extensions:
  288.                 obj_names.append (os.path.join (output_dir,
  289.                                                 base + self.res_extension))
  290.             else:
  291.                 obj_names.append (os.path.join (output_dir,
  292.                                                 base + self.obj_extension))
  293.         return obj_names
  294.  
  295.     # object_filenames ()
  296.  
  297.  
  298.     def compile(self, sources,
  299.                 output_dir=None, macros=None, include_dirs=None, debug=0,
  300.                 extra_preargs=None, extra_postargs=None, depends=None):
  301.  
  302.         if not self.initialized: self.initialize()
  303.         macros, objects, extra_postargs, pp_opts, build = \
  304.                 self._setup_compile(output_dir, macros, include_dirs, sources,
  305.                                     depends, extra_postargs)
  306.  
  307.         compile_opts = extra_preargs or []
  308.         compile_opts.append ('/c')
  309.         if debug:
  310.             compile_opts.extend(self.compile_options_debug)
  311.         else:
  312.             compile_opts.extend(self.compile_options)
  313.  
  314.         for obj in objects:
  315.             try:
  316.                 src, ext = build[obj]
  317.             except KeyError:
  318.                 continue
  319.             if debug:
  320.                 # pass the full pathname to MSVC in debug mode,
  321.                 # this allows the debugger to find the source file
  322.                 # without asking the user to browse for it
  323.                 src = os.path.abspath(src)
  324.  
  325.             if ext in self._c_extensions:
  326.                 input_opt = "/Tc" + src
  327.             elif ext in self._cpp_extensions:
  328.                 input_opt = "/Tp" + src
  329.             elif ext in self._rc_extensions:
  330.                 # compile .RC to .RES file
  331.                 input_opt = src
  332.                 output_opt = "/fo" + obj
  333.                 try:
  334.                     self.spawn ([self.rc] + pp_opts +
  335.                                 [output_opt] + [input_opt])
  336.                 except DistutilsExecError, msg:
  337.                     raise CompileError, msg
  338.                 continue
  339.             elif ext in self._mc_extensions:
  340.  
  341.                 # Compile .MC to .RC file to .RES file.
  342.                 #   * '-h dir' specifies the directory for the
  343.                 #     generated include file
  344.                 #   * '-r dir' specifies the target directory of the
  345.                 #     generated RC file and the binary message resource
  346.                 #     it includes
  347.                 #
  348.                 # For now (since there are no options to change this),
  349.                 # we use the source-directory for the include file and
  350.                 # the build directory for the RC file and message
  351.                 # resources. This works at least for win32all.
  352.  
  353.                 h_dir = os.path.dirname (src)
  354.                 rc_dir = os.path.dirname (obj)
  355.                 try:
  356.                     # first compile .MC to .RC and .H file
  357.                     self.spawn ([self.mc] +
  358.                                 ['-h', h_dir, '-r', rc_dir] + [src])
  359.                     base, _ = os.path.splitext (os.path.basename (src))
  360.                     rc_file = os.path.join (rc_dir, base + '.rc')
  361.                     # then compile .RC to .RES file
  362.                     self.spawn ([self.rc] +
  363.                                 ["/fo" + obj] + [rc_file])
  364.  
  365.                 except DistutilsExecError, msg:
  366.                     raise CompileError, msg
  367.                 continue
  368.             else:
  369.                 # how to handle this file?
  370.                 raise CompileError (
  371.                     "Don't know how to compile %s to %s" % \
  372.                     (src, obj))
  373.  
  374.             output_opt = "/Fo" + obj
  375.             try:
  376.                 self.spawn ([self.cc] + compile_opts + pp_opts +
  377.                             [input_opt, output_opt] +
  378.                             extra_postargs)
  379.             except DistutilsExecError, msg:
  380.                 raise CompileError, msg
  381.  
  382.         return objects
  383.  
  384.     # compile ()
  385.  
  386.  
  387.     def create_static_lib (self,
  388.                            objects,
  389.                            output_libname,
  390.                            output_dir=None,
  391.                            debug=0,
  392.                            target_lang=None):
  393.  
  394.         if not self.initialized: self.initialize()
  395.         (objects, output_dir) = self._fix_object_args (objects, output_dir)
  396.         output_filename = \
  397.             self.library_filename (output_libname, output_dir=output_dir)
  398.  
  399.         if self._need_link (objects, output_filename):
  400.             lib_args = objects + ['/OUT:' + output_filename]
  401.             if debug:
  402.                 pass                    # XXX what goes here?
  403.             try:
  404.                 self.spawn ([self.lib] + lib_args)
  405.             except DistutilsExecError, msg:
  406.                 raise LibError, msg
  407.  
  408.         else:
  409.             log.debug("skipping %s (up-to-date)", output_filename)
  410.  
  411.     # create_static_lib ()
  412.  
  413.     def link (self,
  414.               target_desc,
  415.               objects,
  416.               output_filename,
  417.               output_dir=None,
  418.               libraries=None,
  419.               library_dirs=None,
  420.               runtime_library_dirs=None,
  421.               export_symbols=None,
  422.               debug=0,
  423.               extra_preargs=None,
  424.               extra_postargs=None,
  425.               build_temp=None,
  426.               target_lang=None):
  427.  
  428.         if not self.initialized: self.initialize()
  429.         (objects, output_dir) = self._fix_object_args (objects, output_dir)
  430.         (libraries, library_dirs, runtime_library_dirs) = \
  431.             self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
  432.  
  433.         if runtime_library_dirs:
  434.             self.warn ("I don't know what to do with 'runtime_library_dirs': "
  435.                        + str (runtime_library_dirs))
  436.  
  437.         lib_opts = gen_lib_options (self,
  438.                                     library_dirs, runtime_library_dirs,
  439.                                     libraries)
  440.         if output_dir is not None:
  441.             output_filename = os.path.join (output_dir, output_filename)
  442.  
  443.         if self._need_link (objects, output_filename):
  444.  
  445.             if target_desc == CCompiler.EXECUTABLE:
  446.                 if debug:
  447.                     ldflags = self.ldflags_shared_debug[1:]
  448.                 else:
  449.                     ldflags = self.ldflags_shared[1:]
  450.             else:
  451.                 if debug:
  452.                     ldflags = self.ldflags_shared_debug
  453.                 else:
  454.                     ldflags = self.ldflags_shared
  455.  
  456.             export_opts = []
  457.             for sym in (export_symbols or []):
  458.                 export_opts.append("/EXPORT:" + sym)
  459.  
  460.             ld_args = (ldflags + lib_opts + export_opts +
  461.                        objects + ['/OUT:' + output_filename])
  462.  
  463.             # The MSVC linker generates .lib and .exp files, which cannot be
  464.             # suppressed by any linker switches. The .lib files may even be
  465.             # needed! Make sure they are generated in the temporary build
  466.             # directory. Since they have different names for debug and release
  467.             # builds, they can go into the same directory.
  468.             if export_symbols is not None:
  469.                 (dll_name, dll_ext) = os.path.splitext(
  470.                     os.path.basename(output_filename))
  471.                 implib_file = os.path.join(
  472.                     os.path.dirname(objects[0]),
  473.                     self.library_filename(dll_name))
  474.                 ld_args.append ('/IMPLIB:' + implib_file)
  475.  
  476.             if extra_preargs:
  477.                 ld_args[:0] = extra_preargs
  478.             if extra_postargs:
  479.                 ld_args.extend(extra_postargs)
  480.  
  481.             self.mkpath (os.path.dirname (output_filename))
  482.             try:
  483.                 self.spawn ([self.linker] + ld_args)
  484.             except DistutilsExecError, msg:
  485.                 raise LinkError, msg
  486.  
  487.         else:
  488.             log.debug("skipping %s (up-to-date)", output_filename)
  489.  
  490.     # link ()
  491.  
  492.  
  493.     # -- Miscellaneous methods -----------------------------------------
  494.     # These are all used by the 'gen_lib_options() function, in
  495.     # ccompiler.py.
  496.  
  497.     def library_dir_option (self, dir):
  498.         return "/LIBPATH:" + dir
  499.  
  500.     def runtime_library_dir_option (self, dir):
  501.         raise DistutilsPlatformError, \
  502.               "don't know how to set runtime library search path for MSVC++"
  503.  
  504.     def library_option (self, lib):
  505.         return self.library_filename (lib)
  506.  
  507.  
  508.     def find_library_file (self, dirs, lib, debug=0):
  509.         # Prefer a debugging library if found (and requested), but deal
  510.         # with it if we don't have one.
  511.         if debug:
  512.             try_names = [lib + "_d", lib]
  513.         else:
  514.             try_names = [lib]
  515.         for dir in dirs:
  516.             for name in try_names:
  517.                 libfile = os.path.join(dir, self.library_filename (name))
  518.                 if os.path.exists(libfile):
  519.                     return libfile
  520.         else:
  521.             # Oops, didn't find it in *any* of 'dirs'
  522.             return None
  523.  
  524.     # find_library_file ()
  525.  
  526.     # Helper methods for using the MSVC registry settings
  527.  
  528.     def find_exe(self, exe):
  529.         """Return path to an MSVC executable program.
  530.  
  531.         Tries to find the program in several places: first, one of the
  532.         MSVC program search paths from the registry; next, the directories
  533.         in the PATH environment variable.  If any of those work, return an
  534.         absolute path that is known to exist.  If none of them work, just
  535.         return the original program name, 'exe'.
  536.         """
  537.  
  538.         for p in self.__paths:
  539.             fn = os.path.join(os.path.abspath(p), exe)
  540.             if os.path.isfile(fn):
  541.                 return fn
  542.  
  543.         # didn't find it; try existing path
  544.         for p in string.split(os.environ['Path'],';'):
  545.             fn = os.path.join(os.path.abspath(p),exe)
  546.             if os.path.isfile(fn):
  547.                 return fn
  548.  
  549.         return exe
  550.  
  551.     def get_msvc_paths(self, path, platform='x86'):
  552.         """Get a list of devstudio directories (include, lib or path).
  553.  
  554.         Return a list of strings.  The list will be empty if unable to
  555.         access the registry or appropriate registry keys not found.
  556.         """
  557.  
  558.         if not _can_read_reg:
  559.             return []
  560.  
  561.         path = path + " dirs"
  562.         if self.__version >= 7:
  563.             key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"
  564.                    % (self.__root, self.__version))
  565.         else:
  566.             key = (r"%s\6.0\Build System\Components\Platforms"
  567.                    r"\Win32 (%s)\Directories" % (self.__root, platform))
  568.  
  569.         for base in HKEYS:
  570.             d = read_values(base, key)
  571.             if d:
  572.                 if self.__version >= 7:
  573.                     return string.split(self.__macros.sub(d[path]), ";")
  574.                 else:
  575.                     return string.split(d[path], ";")
  576.         # MSVC 6 seems to create the registry entries we need only when
  577.         # the GUI is run.
  578.         if self.__version == 6:
  579.             for base in HKEYS:
  580.                 if read_values(base, r"%s\6.0" % self.__root) is not None:
  581.                     self.warn("It seems you have Visual Studio 6 installed, "
  582.                         "but the expected registry settings are not present.\n"
  583.                         "You must at least run the Visual Studio GUI once "
  584.                         "so that these entries are created.")
  585.                     break
  586.         return []
  587.  
  588.     def set_path_env_var(self, name):
  589.         """Set environment variable 'name' to an MSVC path type value.
  590.  
  591.         This is equivalent to a SET command prior to execution of spawned
  592.         commands.
  593.         """
  594.  
  595.         if name == "lib":
  596.             p = self.get_msvc_paths("library")
  597.         else:
  598.             p = self.get_msvc_paths(name)
  599.         if p:
  600.             os.environ[name] = string.join(p, ';')
  601.