msvccompiler.py 16.8 KB
Newer Older
1
"""distutils.msvccompiler
2 3

Contains MSVCCompiler, an implementation of the abstract CCompiler class
4
for the Microsoft Visual Studio."""
5 6 7


# created 1999/08/19, Perry Stoll
8 9 10
# hacked by Robin Becker and Thomas Heller to do a better job of
#   finding DevStudio (through the registry)

11
__revision__ = "$Id$"
12

13 14
import sys, os, string
from types import *
15 16
from distutils.errors import \
     DistutilsExecError, DistutilsPlatformError, \
17
     CompileError, LibError, LinkError
18 19
from distutils.ccompiler import \
     CCompiler, gen_preprocess_options, gen_lib_options
20

21 22
_can_read_reg = 0
try:
23
    import _winreg
24

25
    _can_read_reg = 1
26
    hkey_mod = _winreg
27

28 29 30 31
    RegOpenKeyEx = _winreg.OpenKeyEx
    RegEnumKey = _winreg.EnumKey
    RegEnumValue = _winreg.EnumValue
    RegError = _winreg.error
32

33 34 35 36 37
except ImportError:
    try:
        import win32api
        import win32con
        _can_read_reg = 1
38
        hkey_mod = win32con
39 40 41 42 43 44

        RegOpenKeyEx = win32api.RegOpenKeyEx
        RegEnumKey = win32api.RegEnumKey
        RegEnumValue = win32api.RegEnumValue
        RegError = win32api.error

45 46
    except ImportError:
        pass
47 48 49 50 51 52 53

if _can_read_reg:
    HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
    HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
    HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
    HKEY_USERS = hkey_mod.HKEY_USERS
    
54 55
    

56 57
def get_devstudio_versions ():
    """Get list of devstudio versions from the Windows registry.  Return a
58
       list of strings containing version numbers; the list will be
59 60
       empty if we were unable to access the registry (eg. couldn't import
       a registry-access module) or the appropriate registry keys weren't
61 62
       found."""

63
    if not _can_read_reg:
64
        return []
65 66 67

    K = 'Software\\Microsoft\\Devstudio'
    L = []
68 69 70 71
    for base in (HKEY_CLASSES_ROOT,
                 HKEY_LOCAL_MACHINE,
                 HKEY_CURRENT_USER,
                 HKEY_USERS):
72
        try:
73
            k = RegOpenKeyEx(base,K)
74 75 76
            i = 0
            while 1:
                try:
77
                    p = RegEnumKey(k,i)
78 79
                    if p[0] in '123456789' and p not in L:
                        L.append(p)
80
                except RegError:
81 82
                    break
                i = i + 1
83
        except RegError:
84 85 86 87 88
            pass
    L.sort()
    L.reverse()
    return L

89 90 91 92
# get_devstudio_versions ()


def get_msvc_paths (path, version='6.0', platform='x86'):
93 94 95 96
    """Get a list of devstudio directories (include, lib or path).  Return
       a list of strings; will be empty list if unable to access the
       registry or appropriate registry keys not found."""
       
97
    if not _can_read_reg:
98
        return []
99 100

    L = []
101 102
    if path=='lib':
        path= 'Library'
103
    path = string.upper(path + ' Dirs')
104 105 106
    K = ('Software\\Microsoft\\Devstudio\\%s\\' +
         'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \
        (version,platform)
107 108 109 110
    for base in (HKEY_CLASSES_ROOT,
                 HKEY_LOCAL_MACHINE,
                 HKEY_CURRENT_USER,
                 HKEY_USERS):
111
        try:
112
            k = RegOpenKeyEx(base,K)
113 114 115
            i = 0
            while 1:
                try:
116
                    (p,v,t) = RegEnumValue(k,i)
117
                    if string.upper(p) == path:
118 119
                        V = string.split(v,';')
                        for v in V:
120
                            if v == '' or v in L: continue
121 122 123
                            L.append(v)
                        break
                    i = i + 1
124
                except RegError:
125
                    break
126
        except RegError:
127 128 129
            pass
    return L

130 131 132
# get_msvc_paths()


133 134 135 136 137 138 139
def find_exe (exe, version_number):
    """Try to find an MSVC executable program 'exe' (from version
       'version_number' of MSVC) in several places: first, one of the MSVC
       program search paths from the registry; next, the directories in the
       PATH environment variable.  If any of those work, return an absolute
       path that is known to exist.  If none of them work, just return the
       original program name, 'exe'."""
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154
    for p in get_msvc_paths ('path', version_number):
        fn = os.path.join (os.path.abspath(p), exe)
        if os.path.isfile(fn):
            return fn

    # didn't find it; try existing path
    for p in string.split (os.environ['Path'],';'):
        fn = os.path.join(os.path.abspath(p),exe)
        if os.path.isfile(fn):
            return fn

    return exe                          # last desperate hope 


155 156 157 158
def set_path_env_var (name, version_number):
    """Set environment variable 'name' to an MSVC path type value obtained
       from 'get_msvc_paths()'.  This is equivalent to a SET command prior
       to execution of spawned commands."""
159

160
    p = get_msvc_paths (name, version_number)
161
    if p:
162
        os.environ[name] = string.join (p,';')
163

164

165 166 167
class MSVCCompiler (CCompiler) :
    """Concrete class that implements an interface to Microsoft Visual C++,
       as defined by the CCompiler abstract class."""
168

169 170
    compiler_type = 'msvc'

171 172 173 174 175 176 177
    # Just set this so CCompiler's constructor doesn't barf.  We currently
    # don't use the 'set_executables()' bureaucracy provided by CCompiler,
    # as it really isn't necessary for this sort of single-compiler class.
    # Would be nice to have a consistent interface with UnixCCompiler,
    # though, so it's worth thinking about.
    executables = {}

178 179
    # Private class data (need to distinguish C from C++ source for compiler)
    _c_extensions = ['.c']
180
    _cpp_extensions = ['.cc', '.cpp', '.cxx']
181 182 183 184 185 186 187 188 189 190 191

    # Needed for the filename generation methods provided by the
    # base class, CCompiler.
    src_extensions = _c_extensions + _cpp_extensions
    obj_extension = '.obj'
    static_lib_extension = '.lib'
    shared_lib_extension = '.dll'
    static_lib_format = shared_lib_format = '%s%s'
    exe_extension = '.exe'


192 193
    def __init__ (self,
                  verbose=0,
194 195
                  dry_run=0,
                  force=0):
196

197
        CCompiler.__init__ (self, verbose, dry_run, force)
198
        versions = get_devstudio_versions ()
199

200 201
        if versions:
            version = versions[0]  # highest version
202

203 204 205
            self.cc   = find_exe("cl.exe", version)
            self.link = find_exe("link.exe", version)
            self.lib  = find_exe("lib.exe", version)
206 207 208
            set_path_env_var ('lib', version)
            set_path_env_var ('include', version)
            path=get_msvc_paths('path', version)
209 210 211 212 213 214 215 216 217 218
            try:
                for p in string.split(os.environ['path'],';'):
                    path.append(p)
            except KeyError:
                pass
            os.environ['path'] = string.join(path,';')
        else:
            # devstudio not found in the registry
            self.cc = "cl.exe"
            self.link = "link.exe"
219
            self.lib = "lib.exe"
220

221
        self.preprocess_options = None
222 223 224
        self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' ]
        self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX',
                                      '/Z7', '/D_DEBUG']
225

226
        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
Greg Ward's avatar
Greg Ward committed
227 228 229
        self.ldflags_shared_debug = [
            '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
            ]
230 231 232 233 234 235 236
        self.ldflags_static = [ '/nologo']


    # -- Worker methods ------------------------------------------------

    def compile (self,
                 sources,
237
                 output_dir=None,
238
                 macros=None,
239
                 include_dirs=None,
240
                 debug=0,
241 242
                 extra_preargs=None,
                 extra_postargs=None):
243

244 245 246
        (output_dir, macros, include_dirs) = \
            self._fix_compile_args (output_dir, macros, include_dirs)
        (objects, skip_sources) = self._prep_compile (sources, output_dir)
247

248 249
        if extra_postargs is None:
            extra_postargs = []
Greg Ward's avatar
Greg Ward committed
250

251 252 253
        pp_opts = gen_preprocess_options (macros, include_dirs)
        compile_opts = extra_preargs or []
        compile_opts.append ('/c')
Greg Ward's avatar
Greg Ward committed
254
        if debug:
255
            compile_opts.extend (self.compile_options_debug)
Greg Ward's avatar
Greg Ward committed
256
        else:
257
            compile_opts.extend (self.compile_options)
258
        
259 260 261
        for i in range (len (sources)):
            src = sources[i] ; obj = objects[i]
            ext = (os.path.splitext (src))[1]
262

263 264 265 266 267 268 269
            if skip_sources[src]:
                self.announce ("skipping %s (%s up-to-date)" % (src, obj))
            else:
                if ext in self._c_extensions:
                    input_opt = "/Tc" + src
                elif ext in self._cpp_extensions:
                    input_opt = "/Tp" + src
270

271
                output_opt = "/Fo" + obj
272

273
                self.mkpath (os.path.dirname (obj))
274 275 276 277 278 279
                try:
                    self.spawn ([self.cc] + compile_opts + pp_opts +
                                [input_opt, output_opt] +
                                extra_postargs)
                except DistutilsExecError, msg:
                    raise CompileError, msg
Greg Ward's avatar
Greg Ward committed
280

281
        return objects
282

283
    # compile ()
284 285


286 287 288 289 290 291 292
    def create_static_lib (self,
                           objects,
                           output_libname,
                           output_dir=None,
                           debug=0,
                           extra_preargs=None,
                           extra_postargs=None):
293

294
        (objects, output_dir) = self._fix_object_args (objects, output_dir)
295 296 297 298
        output_filename = \
            self.library_filename (output_libname, output_dir=output_dir)

        if self._need_link (objects, output_filename):
299
            lib_args = objects + ['/OUT:' + output_filename]
300 301 302
            if debug:
                pass                    # XXX what goes here?
            if extra_preargs:
303
                lib_args[:0] = extra_preargs
304
            if extra_postargs:
305
                lib_args.extend (extra_postargs)
306
            try:
307
                self.spawn ([self.lib] + lib_args)
308 309 310
            except DistutilsExecError, msg:
                raise LibError, msg
                
311 312
        else:
            self.announce ("skipping %s (up-to-date)" % output_filename)
313

314
    # create_static_lib ()
315 316 317 318 319
    

    def link_shared_lib (self,
                         objects,
                         output_libname,
320
                         output_dir=None,
321 322
                         libraries=None,
                         library_dirs=None,
323
                         runtime_library_dirs=None,
324
                         export_symbols=None,
325
                         debug=0,
326
                         extra_preargs=None,
327 328
                         extra_postargs=None,
                         build_temp=None):
329 330

        self.link_shared_object (objects,
Greg Ward's avatar
Greg Ward committed
331 332 333 334
                                 self.shared_library_name(output_libname),
                                 output_dir=output_dir,
                                 libraries=libraries,
                                 library_dirs=library_dirs,
335 336
                                 runtime_library_dirs=runtime_library_dirs,
                                 export_symbols=export_symbols,
Greg Ward's avatar
Greg Ward committed
337 338
                                 debug=debug,
                                 extra_preargs=extra_preargs,
339 340
                                 extra_postargs=extra_postargs,
                                 build_temp=build_temp)
Greg Ward's avatar
Greg Ward committed
341
                    
342 343 344 345
    
    def link_shared_object (self,
                            objects,
                            output_filename,
346
                            output_dir=None,
347 348
                            libraries=None,
                            library_dirs=None,
349
                            runtime_library_dirs=None,
350
                            export_symbols=None,
Greg Ward's avatar
Greg Ward committed
351
                            debug=0,
352
                            extra_preargs=None,
353 354
                            extra_postargs=None,
                            build_temp=None):
355

356 357 358 359
        (objects, output_dir) = self._fix_object_args (objects, output_dir)
        (libraries, library_dirs, runtime_library_dirs) = \
            self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)

360
        if runtime_library_dirs:
361 362
            self.warn ("I don't know what to do with 'runtime_library_dirs': "
                       + str (runtime_library_dirs))
363
        
364
        lib_opts = gen_lib_options (self,
365
                                    library_dirs, runtime_library_dirs,
366
                                    libraries)
367 368 369 370 371 372 373 374 375 376
        if output_dir is not None:
            output_filename = os.path.join (output_dir, output_filename)

        if self._need_link (objects, output_filename):

            if debug:
                ldflags = self.ldflags_shared_debug
            else:
                ldflags = self.ldflags_shared

377 378 379 380 381 382
            export_opts = []
            for sym in (export_symbols or []):
                export_opts.append("/EXPORT:" + sym)

            ld_args = (ldflags + lib_opts + export_opts + 
                       objects + ['/OUT:' + output_filename])
383

384 385 386 387 388 389 390 391 392 393 394 395
            # The MSVC linker generates .lib and .exp files, which cannot be
            # suppressed by any linker switches. The .lib files may even be
            # needed! Make sure they are generated in the temporary build
            # directory. Since they have different names for debug and release
            # builds, they can go into the same directory.
            (dll_name, dll_ext) = os.path.splitext(
                os.path.basename(output_filename))
            implib_file = os.path.join(
                os.path.dirname(objects[0]),
                self.library_filename(dll_name))
            ld_args.append ('/IMPLIB:' + implib_file)

396 397 398
            if extra_preargs:
                ld_args[:0] = extra_preargs
            if extra_postargs:
399
                ld_args.extend(extra_postargs)
400

401
            self.mkpath (os.path.dirname (output_filename))
402 403 404 405
            try:
                self.spawn ([self.link] + ld_args)
            except DistutilsExecError, msg:
                raise LinkError, msg
406

407 408
        else:
            self.announce ("skipping %s (up-to-date)" % output_filename)
409

410
    # link_shared_object ()
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454


    def link_executable (self,
                         objects,
                         output_progname,
                         output_dir=None,
                         libraries=None,
                         library_dirs=None,
                         runtime_library_dirs=None,
                         debug=0,
                         extra_preargs=None,
                         extra_postargs=None):

        (objects, output_dir) = self._fix_object_args (objects, output_dir)
        (libraries, library_dirs, runtime_library_dirs) = \
            self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)

        if runtime_library_dirs:
            self.warn ("I don't know what to do with 'runtime_library_dirs': "
                       + str (runtime_library_dirs))
        
        lib_opts = gen_lib_options (self,
                                    library_dirs, runtime_library_dirs,
                                    libraries)
        output_filename = output_progname + self.exe_extension
        if output_dir is not None:
            output_filename = os.path.join (output_dir, output_filename)

        if self._need_link (objects, output_filename):

            if debug:
                ldflags = self.ldflags_shared_debug[1:]
            else:
                ldflags = self.ldflags_shared[1:]

            ld_args = ldflags + lib_opts + \
                      objects + ['/OUT:' + output_filename]

            if extra_preargs:
                ld_args[:0] = extra_preargs
            if extra_postargs:
                ld_args.extend (extra_postargs)

            self.mkpath (os.path.dirname (output_filename))
455 456 457 458
            try:
                self.spawn ([self.link] + ld_args)
            except DistutilsExecError, msg:
                raise LinkError, msg
459 460
        else:
            self.announce ("skipping %s (up-to-date)" % output_filename)   
461
    
462

463 464 465
    # -- Miscellaneous methods -----------------------------------------
    # These are all used by the 'gen_lib_options() function, in
    # ccompiler.py.
466 467 468 469

    def library_dir_option (self, dir):
        return "/LIBPATH:" + dir

470 471 472 473
    def runtime_library_dir_option (self, dir):
        raise DistutilsPlatformError, \
              "don't know how to set runtime library search path for MSVC++"

474 475 476 477
    def library_option (self, lib):
        return self.library_filename (lib)


478 479 480 481 482 483 484
    def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
485
        for dir in dirs:
486 487 488 489
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
490 491 492 493 494 495
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

496
# class MSVCCompiler