ENH: move user info gathering at the top of msvc_setup_env.
[scons.git] / src / engine / SCons / Tool / MSCommon / vc.py
1 #
2 # __COPYRIGHT__
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject to
10 # the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
16 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
17 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 #
23
24 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
25
26 __doc__ = """Module for Visual C/C++ detection and configuration.
27 """
28
29 import os
30
31 import SCons.Warnings
32
33 import common
34
35 debug = common.debug
36
37 class VisualC:
38     """
39     An base class for finding installed versions of Visual C/C++.
40     """
41     def __init__(self, version, **kw):
42         self.version = version
43         self.__dict__.update(kw)
44         self._cache = {}
45
46     def vcbin_arch(self):
47         if common.is_win64():
48             result = {
49                 'x86_64' : ['amd64', r'BIN\x86_amd64'],
50                 'ia64'   : [r'BIN\ia64'],
51             }.get(target_arch, [])
52         else:
53             result = {
54                 'x86_64' : ['x86_amd64'],
55                 'ia64'   : ['x86_ia64'],
56             }.get(target_arch, [])
57         # TODO(1.5)
58         #return ';'.join(result)
59         return string.join(result, ';')
60
61     # Support for searching for an appropriate .bat file.
62     # The map is indexed by (target_architecture, host_architecture).
63     # Entries where the host_architecture is None specify the
64     # cross-platform "default" .bat file if there isn't sn entry
65     # specific to the current host architecture.
66
67     batch_file_map = {
68         ('x86_64', 'x86_64') : [
69             r'bin\amd64\vcvarsamd64.bat',
70             r'bin\x86_amd64\vcvarsx86_amd64.bat',
71             r'bin\vcvarsx86_amd64.bat',
72         ],
73         ('x86_64', 'x86') : [
74             r'bin\x86_amd64\vcvarsx86_amd64.bat',
75         ],
76         ('ia64', 'ia64') : [
77             r'bin\ia64\vcvarsia64.bat',
78             r'bin\x86_ia64\vcvarsx86_ia64.bat',
79         ],
80         ('ia64', None) : [
81             r'bin\x86_ia64\vcvarsx86_ia64.bat',
82         ],
83         ('x86', None) : [
84             r'bin\vcvars32.bat',
85         ],
86     }
87
88     def find_batch_file(self, target_architecture, host_architecture):
89         key = (target_architecture, host_architecture)
90         potential_batch_files = self.batch_file_map.get(key)
91         if not potential_batch_files:
92             key = (target_architecture, None)
93             potential_batch_files = self.batch_file_map.get(key)
94         if potential_batch_files:
95             product_dir = self.get_vc_dir()
96             for batch_file in potential_batch_files:
97                 bf = os.path.join(product_dir, batch_file)
98                 if os.path.isfile(bf):
99                     return bf
100         return None
101
102     def find_vc_dir(self):
103         root = 'Software\\'
104         if common.is_win64():
105             root = root + 'Wow6432Node\\'
106         for key in self.hkeys:
107             key = root + key
108             try:
109                 comps = common.read_reg(key)
110             except WindowsError, e:
111                 debug('find_vc_dir(): no VC registry key %s' % repr(key))
112             else:
113                 debug('find_vc_dir(): found VC in registry: %s' % comps)
114                 if os.path.exists(comps):
115                     return comps
116                 else:
117                     debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
118                               % comps)
119                     return None
120         return None
121
122     #
123
124     def get_batch_file(self, target_architecture, host_architecture):
125         try:
126             return self._cache['batch_file']
127         except KeyError:
128             batch_file = self.find_batch_file(target_architecture, host_architecture)
129             self._cache['batch_file'] = batch_file
130             return batch_file
131
132     def get_vc_dir(self):
133         try:
134             return self._cache['vc_dir']
135         except KeyError:
136             vc_dir = self.find_vc_dir()
137             self._cache['vc_dir'] = vc_dir
138             return vc_dir
139         
140     def reset(self):
141         self._cache={}
142         
143
144 # The list of supported Visual C/C++ versions we know how to detect.
145 #
146 # The first VC found in the list is the one used by default if there
147 # are multiple VC installed.  Barring good reasons to the contrary,
148 # this means we should list VC with from most recent to oldest.
149 #
150 # If you update this list, update the documentation in Tool/vc.xml.
151 SupportedVCList = [
152     VisualC('9.0',
153             hkeys=[
154                 r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir',
155                 r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir',
156             ],
157             default_install=r'Microsoft Visual Studio 9.0\VC',
158             common_tools_var='VS90COMNTOOLS',
159             vc_subdir=r'\VC',
160             batch_file_base='vcvars',
161             supported_arch=['x86', 'x86_64', 'ia64'],
162             atlmc_include_subdir = [r'ATLMFC\INCLUDE'],
163             atlmfc_lib_subdir = {
164                 'x86'       : r'ATLMFC\LIB',
165                 'x86_64'    : r'ATLMFC\LIB\amd64',
166                 'ia64'      : r'ATLMFC\LIB\ia64',
167             },
168             crt_lib_subdir = {
169                 'x86_64'    : r'LIB\amd64',
170                 'ia64'      : r'LIB\ia64',
171             },
172     ),
173     VisualC('8.0',
174             hkeys=[
175                 r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir',
176                 r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir',
177             ],
178             default_install=r'%s\Microsoft Visual Studio 8\VC',
179             common_tools_var='VS80COMNTOOLS',
180             vc_subdir=r'\VC',
181             batch_file_base='vcvars',
182             supported_arch=['x86', 'x86_64', 'ia64'],
183             atlmc_include_subdir = [r'ATLMFC\INCLUDE'],
184             atlmfc_lib_subdir = {
185                 'x86'       : r'ATLMFC\LIB',
186                 'x86_64'    : r'ATLMFC\LIB\amd64',
187                 'ia64'      : r'ATLMFC\LIB\ia64',
188             },
189             crt_lib_subdir = {
190                 'x86_64'    : r'LIB\amd64',
191                 'ia64'      : r'LIB\ia64',
192             },
193     ),
194     VisualC('7.1',
195             hkeys=[
196                 r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir',
197             ],
198             default_install=r'%s\Microsoft Visual Studio 7.1.NET 2003\VC7',
199             common_tools_var='VS71COMNTOOLS',
200             vc_subdir=r'\VC7',
201             batch_file_base='vcvars',
202             supported_arch=['x86'],
203             atlmc_include_subdir = [r'ATLMFC\INCLUDE'],
204             atlmfc_lib_subdir = {
205                 'x86' : r'ATLMFC\LIB',
206             },
207     ),
208     VisualC('7.0',
209             hkeys=[
210                 r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir',
211             ],
212             default_install=r'%s\Microsoft Visual Studio .NET\VC7',
213             common_tools_var='VS70COMNTOOLS',
214             vc_subdir=r'\VC7',
215             batch_file_base='vcvars',
216             supported_arch=['x86'],
217             atlmc_include_subdir = [r'ATLMFC\INCLUDE'],
218             atlmfc_lib_subdir = {
219                 'x86' : r'ATLMFC\LIB',
220             },
221     ),
222     VisualC('6.0',
223             hkeys=[
224                 r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir',
225             ],
226             default_install=r'%s\Microsoft Visual Studio\VC98',
227             common_tools_var='VS60COMNTOOLS',
228             vc_subdir=r'\VC98',
229             batch_file_base='vcvars',
230             supported_arch=['x86'],
231             atlmc_include_subdir = [r'ATL\INCLUDE', r'MFC\INCLUDE'],
232             atlmfc_lib_subdir = {
233                 'x86' : r'MFC\LIB',
234             },
235     ),
236 ]
237
238 SupportedVCMap = {}
239 for vc in SupportedVCList:
240     SupportedVCMap[vc.version] = vc
241
242
243 # Finding installed versions of Visual C/C++ isn't cheap, because it goes
244 # not only to the registry but also to the disk to sanity-check that there
245 # is, in fact, something installed there and that the registry entry isn't
246 # just stale.  Find this information once, when requested, and cache it.
247
248 InstalledVCList = None
249 InstalledVCMap  = None
250
251 def get_installed_vcs():
252     global InstalledVCList
253     global InstalledVCMap
254     if InstalledVCList is None:
255         InstalledVCList = []
256         InstalledVCMap = {}
257         for vc in SupportedVCList:
258             debug('trying to find VC %s' % vc.version)
259             if vc.get_vc_dir():
260                 debug('found VC %s' % vc.version)
261                 InstalledVCList.append(vc)
262                 InstalledVCMap[vc.version] = vc
263     return InstalledVCList
264
265
266 def set_vc_by_version(env, msvc):
267     if not SupportedVCMap.has_key(msvc):
268         msg = "VC version %s is not supported" % repr(msvc)
269         raise SCons.Errors.UserError, msg
270     get_installed_vcs()
271     vc = InstalledVCMap.get(msvc)
272     if not vc:
273         msg = "VC version %s is not installed" % repr(msvc)
274         raise SCons.Errors.UserError, msg
275     set_vc_by_directory(env, vc.get_vc_dir())
276
277 # New stuff
278
279 def script_env(script, args=None):
280     stdout = common.get_output(script, args)
281     return common.parse_output(stdout)
282
283 def get_default_version(env):
284     debug('get_default_version()')
285
286     msvc_version = env.get('MSVC_VERSION')
287     if not msvc_version:
288         installed_vcs = get_installed_vcs()
289         debug('InstalledVCMap:%s'%InstalledVCMap)
290         if not installed_vcs:
291             msg = 'No installed VCs'
292             debug('msv %s\n' % repr(msg))
293             SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
294             return None
295         msvc = installed_vcs[0]
296         msvc_version = msvc.version
297         debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
298
299     return msvc_version
300
301 _TARGET_ARCH_TO_BAT_ARCH = {
302         "x86_64": "amd64",
303         "i386": "x86",
304         "amd64": "amd64"}
305
306 def get_host_target(env):
307     host_platform = env.get('HOST_ARCH')
308     if not host_platform:
309       #host_platform = get_default_host_platform()
310       host_platform = 'x86'
311     target_platform = env.get('TARGET_ARCH')
312     if not target_platform:
313       target_platform = host_platform
314
315     return host_platform, target_platform
316
317 def msvc_setup_env(env):
318     debug('msvc_setup_env()')
319
320     version = get_default_version(env)
321     host_platform, target_platform = get_host_target(env)
322     debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
323     env['MSVC_VERSION'] = version
324
325     msvc = InstalledVCMap.get(version)
326     if not msvc:
327         msg = 'VC version %s not installed' % version
328         debug('msv %s\n' % repr(msg))
329         SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
330         return None
331
332     use_script = env.get('MSVC_USE_SCRIPT', True)
333     if SCons.Util.is_String(use_script):
334         debug('use_script 1 %s\n' % repr(use_script))
335         d = script_env(use_script)
336     elif use_script:
337         # XXX: this is VS 2008 specific, fix this
338         script = os.path.join(msvc.find_vc_dir(), "vcvarsall.bat")
339
340         debug('use_script 2 %s, args:%s\n' % (repr(script), target_platform))
341         d = script_env(script, args=target_platform)
342     else:
343         debug('msvc.get_default_env()\n')
344         d = msvc.get_default_env()
345
346     for k, v in d.items():
347         env.PrependENVPath(k, v, delete_existing=True)
348       
349 def msvc_exists(version=None):
350     vcs = get_installed_vcs()
351     if version is None:
352         return len(vcs) > 0
353     return InstalledVCMap.has_key(version)
354     
355     
356 def reset_installed_vcs():
357     global InstalledVCList
358     global InstalledVCMap
359     InstalledVCList = None
360     InstalledVCMap  = None
361     for vc in SupportedVCList:
362         vc.reset()
363
364 # Local Variables:
365 # tab-width:4
366 # indent-tabs-mode:nil
367 # End:
368 # vim: set expandtab tabstop=4 shiftwidth=4: