summaryrefslogtreecommitdiffstats
path: root/Lib/distutils/msvccompiler.py
blob: 90ebae0a5887bf9491d1108d4ff0d583ff89c241 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""distutils.ccompiler

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


# created 1999/08/19, Perry Stoll
# 
__rcsid__ = "$Id$"

import os
import sys
import string
from distutils.errors import *
from distutils.ccompiler import \
     CCompiler, gen_preprocess_options, gen_lib_options


def get_devstudio_versions ():

    """Get list of devstudio versions from the Windows registry.  Return a
       list of strings (???) containing version numbers; the list will be
       empty if we were unable to access the registry (eg. couldn't import
       a registry-access module) or the appropriate registry keys weren't
       found.  (XXX is this correct???)"""
    try:
        import win32api
        import win32con
    except ImportError:
        return []

    K = 'Software\\Microsoft\\Devstudio'
    L = []
    for base in (win32con.HKEY_CLASSES_ROOT,
                 win32con.HKEY_LOCAL_MACHINE,
                 win32con.HKEY_CURRENT_USER,
                 win32con.HKEY_USERS):
        try:
            k = win32api.RegOpenKeyEx(base,K)
            i = 0
            while 1:
                try:
                    p = win32api.RegEnumKey(k,i)
                    if p[0] in '123456789' and p not in L:
                        L.append(p)
                except win32api.error:
                    break
                i = i + 1
        except win32api.error:
            pass
    L.sort()
    L.reverse()
    return L

# get_devstudio_versions ()


def get_msvc_paths (path, version='6.0', platform='x86'):
    """Get a devstudio path (include, lib or path)."""
    try:
        import win32api
        import win32con
    except ImportError:
        return None

    L = []
    if path=='lib':
        path= 'Library'
    path = string.upper(path + ' Dirs')
    K = ('Software\\Microsoft\\Devstudio\\%s\\' +
         'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \
        (version,platform)
    for base in (win32con.HKEY_CLASSES_ROOT,
                 win32con.HKEY_LOCAL_MACHINE,
                 win32con.HKEY_CURRENT_USER,
                 win32con.HKEY_USERS):
        try:
            k = win32api.RegOpenKeyEx(base,K)
            i = 0
            while 1:
                try:
                    (p,v,t) = win32api.RegEnumValue(k,i)
                    if string.upper(p) == path:
                        V = string.split(v,';')
                        for v in V:
                            if v == '' or v in L: continue
                            L.append(v)
                        break
                    i = i + 1
                except win32api.error:
                    break
        except win32api.error:
            pass
    return L

# get_msvc_paths()


def _find_exe(exe):
    for v in get_devstudio_versions():
        for p in get_msvc_paths('path',v):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

    #didn't find it; try existing path
    try:
        for p in string.split(os.environ['Path'],';'):
            fn=os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn
    # XXX BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD BAD !!!!!!!!!!!!!!!!
    except:                             # XXX WHAT'S BEING CAUGHT HERE?!?!?
        pass
    return exe  #last desperate hope 


def _find_SET(n):
    for v in get_devstudio_versions():
        p = get_msvc_paths(n,v)
        if p:
            return p
    return []


def _do_SET(n):
    p = _find_SET(n)
    if p:
        os.environ[n] = string.join(p,';')


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

    compiler_type = 'msvc'

    def __init__ (self,
                  verbose=0,
                  dry_run=0,
                  force=0):

        CCompiler.__init__ (self, verbose, dry_run, force)

        self.add_library_dir( os.path.join( sys.exec_prefix, 'libs' ) )
        
        self.cc   = _find_exe("cl.exe")
        self.link = _find_exe("link.exe")
        _do_SET('lib')
        _do_SET('include')
        path=_find_SET('path')
        try:
            for p in string.split(os.environ['path'],';'):
                path.append(p)
        except KeyError:
            pass
        os.environ['path'] = string.join(path,';')
        self.preprocess_options = None
        self.compile_options = [ '/nologo', '/Ox', '/MD' ]
        self.compile_options_debug = [
            '/nologo', '/Od', '/MDd', '/Z7', '/D_DEBUG'
            ]

        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
        self.ldflags_shared_debug = [
            '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
            ]
        self.ldflags_static = [ '/nologo']


    # -- Worker methods ------------------------------------------------
    # (must be implemented by subclasses)

    _c_extensions = [ '.c' ]
    _cpp_extensions = [ '.cc', '.cpp' ]

    _obj_ext = '.obj'
    _exe_ext = '.exe'
    _shared_lib_ext = '.dll'
    _static_lib_ext = '.lib'

    # XXX the 'output_dir' parameter is ignored by the methods in this
    # class!  I just put it in to be consistent with CCompiler and
    # UnixCCompiler, but someone who actually knows Visual C++ will
    # have to make it work...
    
    def compile (self,
                 sources,
                 output_dir=None,
                 macros=None,
                 include_dirs=None,
                 debug=0,
                 extra_preargs=None,
                 extra_postargs=None):

        if macros is None:
            macros = []
        if include_dirs is None:
            include_dirs = []

        objectFiles = []

        base_pp_opts = \
            gen_preprocess_options (self.macros + macros,
                                    self.include_dirs + include_dirs)

        base_pp_opts.append('/c')

        if debug:
            compile_options = self.compile_options_debug
        else:
            compile_options = self.compile_options
        
        for srcFile in sources:
            base,ext = os.path.splitext(srcFile)
            objFile = base + ".obj"

            if ext in self._c_extensions:
                fileOpt = "/Tc"
            elif ext in self._cpp_extensions:
                fileOpt = "/Tp"

            inputOpt  = fileOpt + srcFile
            outputOpt = "/Fo"   + objFile

            cc_args = compile_options + \
                      base_pp_opts + \
                      [outputOpt, inputOpt]

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

            self.spawn ([self.cc] + cc_args)
            objectFiles.append( objFile )
        return objectFiles


    # XXX the signature of this method is different from CCompiler and
    # UnixCCompiler -- but those extra parameters (libraries, library_dirs)
    # are actually used.  So: are they really *needed*, or can they be
    # ditched?  If needed, the CCompiler API will have to change...
    def link_static_lib (self,
                         objects,
                         output_libname,
                         output_dir=None,
                         libraries=None,
                         library_dirs=None,
                         debug=0,
                         extra_preargs=None,
                         extra_postargs=None):

        if libraries is None:
            libraries = []
        if library_dirs is None:
            library_dirs = []
        
        lib_opts = gen_lib_options (self.libraries + libraries,
                                    self.library_dirs + library_dirs,
                                    "%s.lib", "/LIBPATH:%s")

        ld_args = self.ldflags_static + lib_opts + \
                  objects + ['/OUT:' + output_filename]
        if debug:
            pass                        # XXX what goes here?
        if extra_preargs:
            ld_args[:0] = extra_preargs
        if extra_postargs:
            ld_args.extend (extra_postargs)

        self.spawn ( [ self.link ] + ld_args )
    

    def link_shared_lib (self,
                         objects,
                         output_libname,
                         output_dir=None,
                         libraries=None,
                         library_dirs=None,
                         debug=0,
                         extra_preargs=None,
                         extra_postargs=None):

        # XXX should we sanity check the library name? (eg. no
        # slashes)
        self.link_shared_object (objects,
                                 self.shared_library_name(output_libname),
                                 output_dir=output_dir,
                                 libraries=libraries,
                                 library_dirs=library_dirs,
                                 debug=debug,
                                 extra_preargs=extra_preargs,
                                 extra_postargs=extra_postargs)
                    
    
    def link_shared_object (self,
                            objects,
                            output_filename,
                            output_dir=None,
                            libraries=None,
                            library_dirs=None,
                            debug=0,
                            extra_preargs=None,
                            extra_postargs=None):
        """Link a bunch of stuff together to create a shared object
           file.  Much like 'link_shared_lib()', except the output
           filename is explicitly supplied as 'output_filename'."""
        if libraries is None:
            libraries = []
        if library_dirs is None:
            library_dirs = []
        
        lib_opts = gen_lib_options (self,
                                    self.library_dirs + library_dirs,
                                    self.libraries + libraries)

        if debug:
            ldflags = self.ldflags_shared_debug
            basename, ext = os.path.splitext (output_filename)
            #XXX not sure this belongs here
            # extensions in debug_mode are named 'module_d.pyd'
            output_filename = basename + '_d' + ext
        else:
            ldflags = self.ldflags_shared

        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.spawn ( [ self.link ] + ld_args )


    # -- Filename mangling methods -------------------------------------

    def _change_extensions( self, filenames, newExtension ):
        object_filenames = []

        for srcFile in filenames:
            base,ext = os.path.splitext( srcFile )
            # XXX should we strip off any existing path?
            object_filenames.append( base + newExtension )

        return object_filenames

    def object_filenames (self, source_filenames):
        """Return the list of object filenames corresponding to each
           specified source filename."""
        return self._change_extensions( source_filenames, self._obj_ext )

    def shared_object_filename (self, source_filename):
        """Return the shared object filename corresponding to a
           specified source filename."""
        return self._change_extensions( source_filenames, self._shared_lib_ext )

    def library_filename (self, libname):
        """Return the static library filename corresponding to the
           specified library name."""
        return "%s%s" %( libname, self._static_lib_ext )

    def shared_library_filename (self, libname):
        """Return the shared library filename corresponding to the
           specified library name."""
        return "%s%s" %( libname, self._shared_lib_ext )


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

    def library_option (self, lib):
        return self.library_filename (lib)


    def find_library_file (self, dirs, lib):

        for dir in dirs:
            libfile = os.path.join (dir, self.library_filename (lib))
            if os.path.exists (libfile):
                return libfile

        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

# class MSVCCompiler