jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1175 lines
39KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Carlos Rafael Giani, 2006 (dv)
  4. # Tamas Pal, 2007 (folti)
  5. # Nicolas Mercier, 2009
  6. # Matt Clarkson, 2012
  7. """
  8. Microsoft Visual C++/Intel C++ compiler support
  9. Usage::
  10. $ waf configure --msvc_version="msvc 10.0,msvc 9.0" --msvc_target="x64"
  11. or::
  12. def configure(conf):
  13. conf.env['MSVC_VERSIONS'] = ['msvc 10.0', 'msvc 9.0', 'msvc 8.0', 'msvc 7.1', 'msvc 7.0', 'msvc 6.0', 'wsdk 7.0', 'intel 11', 'PocketPC 9.0', 'Smartphone 8.0']
  14. conf.env['MSVC_TARGETS'] = ['x64']
  15. conf.load('msvc')
  16. or::
  17. def configure(conf):
  18. conf.load('msvc', funs='no_autodetect')
  19. conf.check_lib_msvc('gdi32')
  20. conf.check_libs_msvc('kernel32 user32')
  21. def build(bld):
  22. tg = bld.program(source='main.c', target='app', use='KERNEL32 USER32 GDI32')
  23. Platforms and targets will be tested in the order they appear;
  24. the first good configuration will be used.
  25. To skip testing all the configurations that are not used, use the ``--msvc_lazy_autodetect`` option
  26. or set ``conf.env['MSVC_LAZY_AUTODETECT']=True``.
  27. Supported platforms: ia64, x64, x86, x86_amd64, x86_ia64, x86_arm, amd64_x86, amd64_arm
  28. Compilers supported:
  29. * msvc => Visual Studio, versions 6.0 (VC 98, VC .NET 2002) to 12.0 (Visual Studio 2013)
  30. * wsdk => Windows SDK, versions 6.0, 6.1, 7.0, 7.1, 8.0
  31. * icl => Intel compiler, versions 9, 10, 11, 13
  32. * winphone => Visual Studio to target Windows Phone 8 native (version 8.0 for now)
  33. * Smartphone => Compiler/SDK for Smartphone devices (armv4/v4i)
  34. * PocketPC => Compiler/SDK for PocketPC devices (armv4/v4i)
  35. To use WAF in a VS2008 Make file project (see http://code.google.com/p/waf/issues/detail?id=894)
  36. You may consider to set the environment variable "VS_UNICODE_OUTPUT" to nothing before calling waf.
  37. So in your project settings use something like 'cmd.exe /C "set VS_UNICODE_OUTPUT=& set PYTHONUNBUFFERED=true & waf build"'.
  38. cmd.exe /C "chcp 1252 & set PYTHONUNBUFFERED=true && set && waf configure"
  39. Setting PYTHONUNBUFFERED gives the unbuffered output.
  40. """
  41. import os, sys, re, tempfile
  42. from waflib import Utils, Task, Logs, Options, Errors
  43. from waflib.Logs import debug, warn
  44. from waflib.TaskGen import after_method, feature
  45. from waflib.Configure import conf
  46. from waflib.Tools import ccroot, c, cxx, ar, winres
  47. g_msvc_systemlibs = '''
  48. aclui activeds ad1 adptif adsiid advapi32 asycfilt authz bhsupp bits bufferoverflowu cabinet
  49. cap certadm certidl ciuuid clusapi comctl32 comdlg32 comsupp comsuppd comsuppw comsuppwd comsvcs
  50. credui crypt32 cryptnet cryptui d3d8thk daouuid dbgeng dbghelp dciman32 ddao35 ddao35d
  51. ddao35u ddao35ud delayimp dhcpcsvc dhcpsapi dlcapi dnsapi dsprop dsuiext dtchelp
  52. faultrep fcachdll fci fdi framedyd framedyn gdi32 gdiplus glauxglu32 gpedit gpmuuid
  53. gtrts32w gtrtst32hlink htmlhelp httpapi icm32 icmui imagehlp imm32 iphlpapi iprop
  54. kernel32 ksguid ksproxy ksuser libcmt libcmtd libcpmt libcpmtd loadperf lz32 mapi
  55. mapi32 mgmtapi minidump mmc mobsync mpr mprapi mqoa mqrt msacm32 mscms mscoree
  56. msdasc msimg32 msrating mstask msvcmrt msvcurt msvcurtd mswsock msxml2 mtx mtxdm
  57. netapi32 nmapinmsupp npptools ntdsapi ntdsbcli ntmsapi ntquery odbc32 odbcbcp
  58. odbccp32 oldnames ole32 oleacc oleaut32 oledb oledlgolepro32 opends60 opengl32
  59. osptk parser pdh penter pgobootrun pgort powrprof psapi ptrustm ptrustmd ptrustu
  60. ptrustud qosname rasapi32 rasdlg rassapi resutils riched20 rpcndr rpcns4 rpcrt4 rtm
  61. rtutils runtmchk scarddlg scrnsave scrnsavw secur32 sensapi setupapi sfc shell32
  62. shfolder shlwapi sisbkup snmpapi sporder srclient sti strsafe svcguid tapi32 thunk32
  63. traffic unicows url urlmon user32 userenv usp10 uuid uxtheme vcomp vcompd vdmdbg
  64. version vfw32 wbemuuid webpost wiaguid wininet winmm winscard winspool winstrm
  65. wintrust wldap32 wmiutils wow32 ws2_32 wsnmp32 wsock32 wst wtsapi32 xaswitch xolehlp
  66. '''.split()
  67. """importlibs provided by MSVC/Platform SDK. Do NOT search them"""
  68. all_msvc_platforms = [ ('x64', 'amd64'), ('x86', 'x86'), ('ia64', 'ia64'), ('x86_amd64', 'amd64'), ('x86_ia64', 'ia64'), ('x86_arm', 'arm'), ('amd64_x86', 'x86'), ('amd64_arm', 'arm') ]
  69. """List of msvc platforms"""
  70. all_wince_platforms = [ ('armv4', 'arm'), ('armv4i', 'arm'), ('mipsii', 'mips'), ('mipsii_fp', 'mips'), ('mipsiv', 'mips'), ('mipsiv_fp', 'mips'), ('sh4', 'sh'), ('x86', 'cex86') ]
  71. """List of wince platforms"""
  72. all_icl_platforms = [ ('intel64', 'amd64'), ('em64t', 'amd64'), ('ia32', 'x86'), ('Itanium', 'ia64')]
  73. """List of icl platforms"""
  74. def options(opt):
  75. opt.add_option('--msvc_version', type='string', help = 'msvc version, eg: "msvc 10.0,msvc 9.0"', default='')
  76. opt.add_option('--msvc_targets', type='string', help = 'msvc targets, eg: "x64,arm"', default='')
  77. opt.add_option('--msvc_lazy_autodetect', action='store_true', help = 'lazily check msvc target environments')
  78. def setup_msvc(conf, versions, arch = False):
  79. """
  80. Checks installed compilers and targets and returns the first combination from the user's
  81. options, env, or the global supported lists that checks.
  82. :param versions: A list of tuples of all installed compilers and available targets.
  83. :param arch: Whether to return the target architecture.
  84. :return: the compiler, revision, path, include dirs, library paths, and (optionally) target architecture
  85. :rtype: tuple of strings
  86. """
  87. platforms = getattr(Options.options, 'msvc_targets', '').split(',')
  88. if platforms == ['']:
  89. platforms=Utils.to_list(conf.env['MSVC_TARGETS']) or [i for i,j in all_msvc_platforms+all_icl_platforms+all_wince_platforms]
  90. desired_versions = getattr(Options.options, 'msvc_version', '').split(',')
  91. if desired_versions == ['']:
  92. desired_versions = conf.env['MSVC_VERSIONS'] or [v for v,_ in versions][::-1]
  93. versiondict = dict(versions)
  94. for version in desired_versions:
  95. try:
  96. targets = dict(versiondict[version])
  97. for target in platforms:
  98. try:
  99. try:
  100. realtarget,(p1,p2,p3) = targets[target]
  101. except conf.errors.ConfigurationError:
  102. # lazytup target evaluation errors
  103. del(targets[target])
  104. else:
  105. compiler,revision = version.rsplit(' ', 1)
  106. if arch:
  107. return compiler,revision,p1,p2,p3,realtarget
  108. else:
  109. return compiler,revision,p1,p2,p3
  110. except KeyError: continue
  111. except KeyError: continue
  112. conf.fatal('msvc: Impossible to find a valid architecture for building (in setup_msvc)')
  113. @conf
  114. def get_msvc_version(conf, compiler, version, target, vcvars):
  115. """
  116. Checks that an installed compiler actually runs and uses vcvars to obtain the
  117. environment needed by the compiler.
  118. :param compiler: compiler type, for looking up the executable name
  119. :param version: compiler version, for debugging only
  120. :param target: target architecture
  121. :param vcvars: batch file to run to check the environment
  122. :return: the location of the compiler executable, the location of include dirs, and the library paths
  123. :rtype: tuple of strings
  124. """
  125. debug('msvc: get_msvc_version: %r %r %r', compiler, version, target)
  126. try:
  127. conf.msvc_cnt += 1
  128. except AttributeError:
  129. conf.msvc_cnt = 1
  130. batfile = conf.bldnode.make_node('waf-print-msvc-%d.bat' % conf.msvc_cnt)
  131. batfile.write("""@echo off
  132. set INCLUDE=
  133. set LIB=
  134. call "%s" %s
  135. echo PATH=%%PATH%%
  136. echo INCLUDE=%%INCLUDE%%
  137. echo LIB=%%LIB%%;%%LIBPATH%%
  138. """ % (vcvars,target))
  139. sout = conf.cmd_and_log(['cmd.exe', '/E:on', '/V:on', '/C', batfile.abspath()])
  140. lines = sout.splitlines()
  141. if not lines[0]:
  142. lines.pop(0)
  143. MSVC_PATH = MSVC_INCDIR = MSVC_LIBDIR = None
  144. for line in lines:
  145. if line.startswith('PATH='):
  146. path = line[5:]
  147. MSVC_PATH = path.split(';')
  148. elif line.startswith('INCLUDE='):
  149. MSVC_INCDIR = [i for i in line[8:].split(';') if i]
  150. elif line.startswith('LIB='):
  151. MSVC_LIBDIR = [i for i in line[4:].split(';') if i]
  152. if None in (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR):
  153. conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_3)')
  154. # Check if the compiler is usable at all.
  155. # The detection may return 64-bit versions even on 32-bit systems, and these would fail to run.
  156. env = dict(os.environ)
  157. env.update(PATH = path)
  158. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  159. cxx = conf.find_program(compiler_name, path_list=MSVC_PATH)
  160. # delete CL if exists. because it could contain parameters wich can change cl's behaviour rather catastrophically.
  161. if 'CL' in env:
  162. del(env['CL'])
  163. try:
  164. try:
  165. conf.cmd_and_log(cxx + ['/help'], env=env)
  166. except Exception as e:
  167. debug('msvc: get_msvc_version: %r %r %r -> failure' % (compiler, version, target))
  168. debug(str(e))
  169. conf.fatal('msvc: cannot run the compiler (in get_msvc_version)')
  170. else:
  171. debug('msvc: get_msvc_version: %r %r %r -> OK', compiler, version, target)
  172. finally:
  173. conf.env[compiler_name] = ''
  174. return (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR)
  175. @conf
  176. def gather_wsdk_versions(conf, versions):
  177. """
  178. Use winreg to add the msvc versions to the input list
  179. :param versions: list to modify
  180. :type versions: list
  181. """
  182. version_pattern = re.compile('^v..?.?\...?.?')
  183. try:
  184. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Microsoft SDKs\\Windows')
  185. except WindowsError:
  186. try:
  187. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows')
  188. except WindowsError:
  189. return
  190. index = 0
  191. while 1:
  192. try:
  193. version = Utils.winreg.EnumKey(all_versions, index)
  194. except WindowsError:
  195. break
  196. index = index + 1
  197. if not version_pattern.match(version):
  198. continue
  199. try:
  200. msvc_version = Utils.winreg.OpenKey(all_versions, version)
  201. path,type = Utils.winreg.QueryValueEx(msvc_version,'InstallationFolder')
  202. except WindowsError:
  203. continue
  204. if os.path.isfile(os.path.join(path, 'bin', 'SetEnv.cmd')):
  205. targets = []
  206. for target,arch in all_msvc_platforms:
  207. try:
  208. targets.append((target, (arch, get_compiler_env(conf, 'wsdk', version, '/'+target, os.path.join(path, 'bin', 'SetEnv.cmd')))))
  209. except conf.errors.ConfigurationError:
  210. pass
  211. versions.append(('wsdk ' + version[1:], targets))
  212. def gather_wince_supported_platforms():
  213. """
  214. Checks SmartPhones SDKs
  215. :param versions: list to modify
  216. :type versions: list
  217. """
  218. supported_wince_platforms = []
  219. try:
  220. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Windows CE Tools\\SDKs')
  221. except WindowsError:
  222. try:
  223. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows CE Tools\\SDKs')
  224. except WindowsError:
  225. ce_sdk = ''
  226. if not ce_sdk:
  227. return supported_wince_platforms
  228. ce_index = 0
  229. while 1:
  230. try:
  231. sdk_device = Utils.winreg.EnumKey(ce_sdk, ce_index)
  232. except WindowsError:
  233. break
  234. ce_index = ce_index + 1
  235. sdk = Utils.winreg.OpenKey(ce_sdk, sdk_device)
  236. try:
  237. path,type = Utils.winreg.QueryValueEx(sdk, 'SDKRootDir')
  238. except WindowsError:
  239. try:
  240. path,type = Utils.winreg.QueryValueEx(sdk,'SDKInformation')
  241. path,xml = os.path.split(path)
  242. except WindowsError:
  243. continue
  244. path=str(path)
  245. path,device = os.path.split(path)
  246. if not device:
  247. path,device = os.path.split(path)
  248. platforms = []
  249. for arch,compiler in all_wince_platforms:
  250. if os.path.isdir(os.path.join(path, device, 'Lib', arch)):
  251. platforms.append((arch, compiler, os.path.join(path, device, 'Include', arch), os.path.join(path, device, 'Lib', arch)))
  252. if platforms:
  253. supported_wince_platforms.append((device, platforms))
  254. return supported_wince_platforms
  255. def gather_msvc_detected_versions():
  256. #Detected MSVC versions!
  257. version_pattern = re.compile('^(\d\d?\.\d\d?)(Exp)?$')
  258. detected_versions = []
  259. for vcver,vcvar in (('VCExpress','Exp'), ('VisualStudio','')):
  260. try:
  261. prefix = 'SOFTWARE\\Wow6432node\\Microsoft\\'+vcver
  262. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  263. except WindowsError:
  264. try:
  265. prefix = 'SOFTWARE\\Microsoft\\'+vcver
  266. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  267. except WindowsError:
  268. continue
  269. index = 0
  270. while 1:
  271. try:
  272. version = Utils.winreg.EnumKey(all_versions, index)
  273. except WindowsError:
  274. break
  275. index = index + 1
  276. match = version_pattern.match(version)
  277. if not match:
  278. continue
  279. else:
  280. versionnumber = float(match.group(1))
  281. detected_versions.append((versionnumber, version+vcvar, prefix+"\\"+version))
  282. def fun(tup):
  283. return tup[0]
  284. detected_versions.sort(key = fun)
  285. return detected_versions
  286. def get_compiler_env(conf, compiler, version, bat_target, bat, select=None):
  287. """
  288. Gets the compiler environment variables as a tuple. Evaluation is eager by default.
  289. If set to lazy with ``--msvc_lazy_autodetect`` or ``env.MSVC_LAZY_AUTODETECT``
  290. the environment is evaluated when the tuple is destructured or iterated. This means
  291. destructuring can throw :py:class:`conf.errors.ConfigurationError`.
  292. :param conf: configuration context to use to eventually get the version environment
  293. :param compiler: compiler name
  294. :param version: compiler version number
  295. :param bat: path to the batch file to run
  296. :param select: optional function to take the realized environment variables tup and map it (e.g. to combine other constant paths)
  297. """
  298. lazy = getattr(Options.options, 'msvc_lazy_autodetect', False) or conf.env['MSVC_LAZY_AUTODETECT']
  299. def msvc_thunk():
  300. vs = conf.get_msvc_version(compiler, version, bat_target, bat)
  301. if select:
  302. return select(vs)
  303. else:
  304. return vs
  305. return lazytup(msvc_thunk, lazy, ([], [], []))
  306. class lazytup(object):
  307. """
  308. A tuple that evaluates its elements from a function when iterated or destructured.
  309. :param fn: thunk to evaluate the tuple on demand
  310. :param lazy: whether to delay evaluation or evaluate in the constructor
  311. :param default: optional default for :py:func:`repr` if it should not evaluate
  312. """
  313. def __init__(self, fn, lazy=True, default=None):
  314. self.fn = fn
  315. self.default = default
  316. if not lazy:
  317. self.evaluate()
  318. def __len__(self):
  319. self.evaluate()
  320. return len(self.value)
  321. def __iter__(self):
  322. self.evaluate()
  323. for i, v in enumerate(self.value):
  324. yield v
  325. def __getitem__(self, i):
  326. self.evaluate()
  327. return self.value[i]
  328. def __repr__(self):
  329. if hasattr(self, 'value'):
  330. return repr(self.value)
  331. elif self.default:
  332. return repr(self.default)
  333. else:
  334. self.evaluate()
  335. return repr(self.value)
  336. def evaluate(self):
  337. if hasattr(self, 'value'):
  338. return
  339. self.value = self.fn()
  340. @conf
  341. def gather_msvc_targets(conf, versions, version, vc_path):
  342. #Looking for normal MSVC compilers!
  343. targets = []
  344. if os.path.isfile(os.path.join(vc_path, 'vcvarsall.bat')):
  345. for target,realtarget in all_msvc_platforms[::-1]:
  346. try:
  347. targets.append((target, (realtarget, get_compiler_env(conf, 'msvc', version, target, os.path.join(vc_path, 'vcvarsall.bat')))))
  348. except conf.errors.ConfigurationError:
  349. pass
  350. elif os.path.isfile(os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')):
  351. try:
  352. targets.append(('x86', ('x86', get_compiler_env(conf, 'msvc', version, 'x86', os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')))))
  353. except conf.errors.ConfigurationError:
  354. pass
  355. elif os.path.isfile(os.path.join(vc_path, 'Bin', 'vcvars32.bat')):
  356. try:
  357. targets.append(('x86', ('x86', get_compiler_env(conf, 'msvc', version, '', os.path.join(vc_path, 'Bin', 'vcvars32.bat')))))
  358. except conf.errors.ConfigurationError:
  359. pass
  360. if targets:
  361. versions.append(('msvc '+ version, targets))
  362. @conf
  363. def gather_wince_targets(conf, versions, version, vc_path, vsvars, supported_platforms):
  364. #Looking for Win CE compilers!
  365. for device,platforms in supported_platforms:
  366. cetargets = []
  367. for platform,compiler,include,lib in platforms:
  368. winCEpath = os.path.join(vc_path, 'ce')
  369. if not os.path.isdir(winCEpath):
  370. continue
  371. if os.path.isdir(os.path.join(winCEpath, 'lib', platform)):
  372. bindirs = [os.path.join(winCEpath, 'bin', compiler), os.path.join(winCEpath, 'bin', 'x86_'+compiler)]
  373. incdirs = [os.path.join(winCEpath, 'include'), os.path.join(winCEpath, 'atlmfc', 'include'), include]
  374. libdirs = [os.path.join(winCEpath, 'lib', platform), os.path.join(winCEpath, 'atlmfc', 'lib', platform), lib]
  375. def combine_common(compiler_env):
  376. (common_bindirs,_1,_2) = compiler_env
  377. return (bindirs + common_bindirs, incdirs, libdirs)
  378. try:
  379. cetargets.append((platform, (platform, get_compiler_env(conf, 'msvc', version, 'x86', vsvars, combine_common))))
  380. except conf.errors.ConfigurationError:
  381. continue
  382. if cetargets:
  383. versions.append((device + ' ' + version, cetargets))
  384. @conf
  385. def gather_winphone_targets(conf, versions, version, vc_path, vsvars):
  386. #Looking for WinPhone compilers
  387. targets = []
  388. for target,realtarget in all_msvc_platforms[::-1]:
  389. try:
  390. targets.append((target, (realtarget, get_compiler_env(conf, 'winphone', version, target, vsvars))))
  391. except conf.errors.ConfigurationError:
  392. pass
  393. if targets:
  394. versions.append(('winphone '+ version, targets))
  395. @conf
  396. def gather_msvc_versions(conf, versions):
  397. vc_paths = []
  398. for (v,version,reg) in gather_msvc_detected_versions():
  399. try:
  400. try:
  401. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\VC")
  402. except WindowsError:
  403. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\Microsoft Visual C++")
  404. path,type = Utils.winreg.QueryValueEx(msvc_version, 'ProductDir')
  405. vc_paths.append((version, os.path.abspath(str(path))))
  406. except WindowsError:
  407. continue
  408. wince_supported_platforms = gather_wince_supported_platforms()
  409. for version,vc_path in vc_paths:
  410. vs_path = os.path.dirname(vc_path)
  411. vsvars = os.path.join(vs_path, 'Common7', 'Tools', 'vsvars32.bat')
  412. if wince_supported_platforms and os.path.isfile(vsvars):
  413. conf.gather_wince_targets(versions, version, vc_path, vsvars, wince_supported_platforms)
  414. # WP80 works with 11.0Exp and 11.0, both of which resolve to the same vc_path.
  415. # Stop after one is found.
  416. for version,vc_path in vc_paths:
  417. vs_path = os.path.dirname(vc_path)
  418. vsvars = os.path.join(vs_path, 'VC', 'WPSDK', 'WP80', 'vcvarsphoneall.bat')
  419. if os.path.isfile(vsvars):
  420. conf.gather_winphone_targets(versions, '8.0', vc_path, vsvars)
  421. break
  422. for version,vc_path in vc_paths:
  423. vs_path = os.path.dirname(vc_path)
  424. conf.gather_msvc_targets(versions, version, vc_path)
  425. @conf
  426. def gather_icl_versions(conf, versions):
  427. """
  428. Checks ICL compilers
  429. :param versions: list to modify
  430. :type versions: list
  431. """
  432. version_pattern = re.compile('^...?.?\....?.?')
  433. try:
  434. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Compilers\\C++')
  435. except WindowsError:
  436. try:
  437. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Compilers\\C++')
  438. except WindowsError:
  439. return
  440. index = 0
  441. while 1:
  442. try:
  443. version = Utils.winreg.EnumKey(all_versions, index)
  444. except WindowsError:
  445. break
  446. index = index + 1
  447. if not version_pattern.match(version):
  448. continue
  449. targets = []
  450. for target,arch in all_icl_platforms:
  451. try:
  452. if target=='intel64': targetDir='EM64T_NATIVE'
  453. else: targetDir=target
  454. Utils.winreg.OpenKey(all_versions,version+'\\'+targetDir)
  455. icl_version=Utils.winreg.OpenKey(all_versions,version)
  456. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  457. batch_file=os.path.join(path,'bin','iclvars.bat')
  458. if os.path.isfile(batch_file):
  459. try:
  460. targets.append((target,(arch,get_compiler_env(conf,'intel',version,target,batch_file))))
  461. except conf.errors.ConfigurationError:
  462. pass
  463. except WindowsError:
  464. pass
  465. for target,arch in all_icl_platforms:
  466. try:
  467. icl_version = Utils.winreg.OpenKey(all_versions, version+'\\'+target)
  468. path,type = Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  469. batch_file=os.path.join(path,'bin','iclvars.bat')
  470. if os.path.isfile(batch_file):
  471. try:
  472. targets.append((target, (arch, get_compiler_env(conf, 'intel', version, target, batch_file))))
  473. except conf.errors.ConfigurationError:
  474. pass
  475. except WindowsError:
  476. continue
  477. major = version[0:2]
  478. versions.append(('intel ' + major, targets))
  479. @conf
  480. def gather_intel_composer_versions(conf, versions):
  481. """
  482. Checks ICL compilers that are part of Intel Composer Suites
  483. :param versions: list to modify
  484. :type versions: list
  485. """
  486. version_pattern = re.compile('^...?.?\...?.?.?')
  487. try:
  488. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Suites')
  489. except WindowsError:
  490. try:
  491. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Suites')
  492. except WindowsError:
  493. return
  494. index = 0
  495. while 1:
  496. try:
  497. version = Utils.winreg.EnumKey(all_versions, index)
  498. except WindowsError:
  499. break
  500. index = index + 1
  501. if not version_pattern.match(version):
  502. continue
  503. targets = []
  504. for target,arch in all_icl_platforms:
  505. try:
  506. if target=='intel64': targetDir='EM64T_NATIVE'
  507. else: targetDir=target
  508. try:
  509. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\'+targetDir)
  510. except WindowsError:
  511. if targetDir=='EM64T_NATIVE':
  512. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\EM64T')
  513. else:
  514. raise WindowsError
  515. uid,type = Utils.winreg.QueryValueEx(defaults, 'SubKey')
  516. Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++\\'+targetDir)
  517. icl_version=Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++')
  518. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  519. batch_file=os.path.join(path,'bin','iclvars.bat')
  520. if os.path.isfile(batch_file):
  521. try:
  522. targets.append((target,(arch,get_compiler_env(conf,'intel',version,target,batch_file))))
  523. except conf.errors.ConfigurationError:
  524. pass
  525. # The intel compilervar_arch.bat is broken when used with Visual Studio Express 2012
  526. # http://software.intel.com/en-us/forums/topic/328487
  527. compilervars_warning_attr = '_compilervars_warning_key'
  528. if version[0:2] == '13' and getattr(conf, compilervars_warning_attr, True):
  529. setattr(conf, compilervars_warning_attr, False)
  530. patch_url = 'http://software.intel.com/en-us/forums/topic/328487'
  531. compilervars_arch = os.path.join(path, 'bin', 'compilervars_arch.bat')
  532. for vscomntool in ('VS110COMNTOOLS', 'VS100COMNTOOLS'):
  533. if vscomntool in os.environ:
  534. vs_express_path = os.environ[vscomntool] + r'..\IDE\VSWinExpress.exe'
  535. dev_env_path = os.environ[vscomntool] + r'..\IDE\devenv.exe'
  536. if (r'if exist "%VS110COMNTOOLS%..\IDE\VSWinExpress.exe"' in Utils.readf(compilervars_arch) and
  537. not os.path.exists(vs_express_path) and not os.path.exists(dev_env_path)):
  538. Logs.warn(('The Intel compilervar_arch.bat only checks for one Visual Studio SKU '
  539. '(VSWinExpress.exe) but it does not seem to be installed at %r. '
  540. 'The intel command line set up will fail to configure unless the file %r'
  541. 'is patched. See: %s') % (vs_express_path, compilervars_arch, patch_url))
  542. except WindowsError:
  543. pass
  544. major = version[0:2]
  545. versions.append(('intel ' + major, targets))
  546. @conf
  547. def get_msvc_versions(conf, eval_and_save=True):
  548. """
  549. :return: list of compilers installed
  550. :rtype: list of string
  551. """
  552. if conf.env['MSVC_INSTALLED_VERSIONS']:
  553. return conf.env['MSVC_INSTALLED_VERSIONS']
  554. # Gather all the compiler versions and targets. This phase can be lazy
  555. # per lazy detection settings.
  556. lst = []
  557. conf.gather_icl_versions(lst)
  558. conf.gather_intel_composer_versions(lst)
  559. conf.gather_wsdk_versions(lst)
  560. conf.gather_msvc_versions(lst)
  561. # Override lazy detection by evaluating after the fact.
  562. if eval_and_save:
  563. def checked_target(t):
  564. target,(arch,paths) = t
  565. try:
  566. paths.evaluate()
  567. except conf.errors.ConfigurationError:
  568. return None
  569. else:
  570. return t
  571. lst = [(version, list(filter(checked_target, targets))) for version, targets in lst]
  572. conf.env['MSVC_INSTALLED_VERSIONS'] = lst
  573. return lst
  574. @conf
  575. def print_all_msvc_detected(conf):
  576. """
  577. Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS*
  578. """
  579. for version,targets in conf.env['MSVC_INSTALLED_VERSIONS']:
  580. Logs.info(version)
  581. for target,l in targets:
  582. Logs.info("\t"+target)
  583. @conf
  584. def detect_msvc(conf, arch = False):
  585. # Save installed versions only if lazy detection is disabled.
  586. lazy_detect = getattr(Options.options, 'msvc_lazy_autodetect', False) or conf.env['MSVC_LAZY_AUTODETECT']
  587. versions = get_msvc_versions(conf, not lazy_detect)
  588. return setup_msvc(conf, versions, arch)
  589. @conf
  590. def find_lt_names_msvc(self, libname, is_static=False):
  591. """
  592. Win32/MSVC specific code to glean out information from libtool la files.
  593. this function is not attached to the task_gen class
  594. """
  595. lt_names=[
  596. 'lib%s.la' % libname,
  597. '%s.la' % libname,
  598. ]
  599. for path in self.env['LIBPATH']:
  600. for la in lt_names:
  601. laf=os.path.join(path,la)
  602. dll=None
  603. if os.path.exists(laf):
  604. ltdict = Utils.read_la_file(laf)
  605. lt_libdir=None
  606. if ltdict.get('libdir', ''):
  607. lt_libdir = ltdict['libdir']
  608. if not is_static and ltdict.get('library_names', ''):
  609. dllnames=ltdict['library_names'].split()
  610. dll=dllnames[0].lower()
  611. dll=re.sub('\.dll$', '', dll)
  612. return (lt_libdir, dll, False)
  613. elif ltdict.get('old_library', ''):
  614. olib=ltdict['old_library']
  615. if os.path.exists(os.path.join(path,olib)):
  616. return (path, olib, True)
  617. elif lt_libdir != '' and os.path.exists(os.path.join(lt_libdir,olib)):
  618. return (lt_libdir, olib, True)
  619. else:
  620. return (None, olib, True)
  621. else:
  622. raise self.errors.WafError('invalid libtool object file: %s' % laf)
  623. return (None, None, None)
  624. @conf
  625. def libname_msvc(self, libname, is_static=False):
  626. lib = libname.lower()
  627. lib = re.sub('\.lib$','',lib)
  628. if lib in g_msvc_systemlibs:
  629. return lib
  630. lib=re.sub('^lib','',lib)
  631. if lib == 'm':
  632. return None
  633. (lt_path, lt_libname, lt_static) = self.find_lt_names_msvc(lib, is_static)
  634. if lt_path != None and lt_libname != None:
  635. if lt_static == True:
  636. # file existance check has been made by find_lt_names
  637. return os.path.join(lt_path,lt_libname)
  638. if lt_path != None:
  639. _libpaths=[lt_path] + self.env['LIBPATH']
  640. else:
  641. _libpaths=self.env['LIBPATH']
  642. static_libs=[
  643. 'lib%ss.lib' % lib,
  644. 'lib%s.lib' % lib,
  645. '%ss.lib' % lib,
  646. '%s.lib' %lib,
  647. ]
  648. dynamic_libs=[
  649. 'lib%s.dll.lib' % lib,
  650. 'lib%s.dll.a' % lib,
  651. '%s.dll.lib' % lib,
  652. '%s.dll.a' % lib,
  653. 'lib%s_d.lib' % lib,
  654. '%s_d.lib' % lib,
  655. '%s.lib' %lib,
  656. ]
  657. libnames=static_libs
  658. if not is_static:
  659. libnames=dynamic_libs + static_libs
  660. for path in _libpaths:
  661. for libn in libnames:
  662. if os.path.exists(os.path.join(path, libn)):
  663. debug('msvc: lib found: %s' % os.path.join(path,libn))
  664. return re.sub('\.lib$', '',libn)
  665. #if no lib can be found, just return the libname as msvc expects it
  666. self.fatal("The library %r could not be found" % libname)
  667. return re.sub('\.lib$', '', libname)
  668. @conf
  669. def check_lib_msvc(self, libname, is_static=False, uselib_store=None):
  670. """
  671. Ideally we should be able to place the lib in the right env var, either STLIB or LIB,
  672. but we don't distinguish static libs from shared libs.
  673. This is ok since msvc doesn't have any special linker flag to select static libs (no env['STLIB_MARKER'])
  674. """
  675. libn = self.libname_msvc(libname, is_static)
  676. if not uselib_store:
  677. uselib_store = libname.upper()
  678. if False and is_static: # disabled
  679. self.env['STLIB_' + uselib_store] = [libn]
  680. else:
  681. self.env['LIB_' + uselib_store] = [libn]
  682. @conf
  683. def check_libs_msvc(self, libnames, is_static=False):
  684. for libname in Utils.to_list(libnames):
  685. self.check_lib_msvc(libname, is_static)
  686. def configure(conf):
  687. """
  688. Configuration methods to call for detecting msvc
  689. """
  690. conf.autodetect(True)
  691. conf.find_msvc()
  692. conf.msvc_common_flags()
  693. conf.cc_load_tools()
  694. conf.cxx_load_tools()
  695. conf.cc_add_flags()
  696. conf.cxx_add_flags()
  697. conf.link_add_flags()
  698. conf.visual_studio_add_flags()
  699. @conf
  700. def no_autodetect(conf):
  701. conf.env.NO_MSVC_DETECT = 1
  702. configure(conf)
  703. @conf
  704. def autodetect(conf, arch = False):
  705. v = conf.env
  706. if v.NO_MSVC_DETECT:
  707. return
  708. if arch:
  709. compiler, version, path, includes, libdirs, arch = conf.detect_msvc(True)
  710. v['DEST_CPU'] = arch
  711. else:
  712. compiler, version, path, includes, libdirs = conf.detect_msvc()
  713. v['PATH'] = path
  714. v['INCLUDES'] = includes
  715. v['LIBPATH'] = libdirs
  716. v['MSVC_COMPILER'] = compiler
  717. try:
  718. v['MSVC_VERSION'] = float(version)
  719. except Exception:
  720. v['MSVC_VERSION'] = float(version[:-3])
  721. def _get_prog_names(conf, compiler):
  722. if compiler=='intel':
  723. compiler_name = 'ICL'
  724. linker_name = 'XILINK'
  725. lib_name = 'XILIB'
  726. else:
  727. # assumes CL.exe
  728. compiler_name = 'CL'
  729. linker_name = 'LINK'
  730. lib_name = 'LIB'
  731. return compiler_name, linker_name, lib_name
  732. @conf
  733. def find_msvc(conf):
  734. """Due to path format limitations, limit operation only to native Win32. Yeah it sucks."""
  735. if sys.platform == 'cygwin':
  736. conf.fatal('MSVC module does not work under cygwin Python!')
  737. # the autodetection is supposed to be performed before entering in this method
  738. v = conf.env
  739. path = v['PATH']
  740. compiler = v['MSVC_COMPILER']
  741. version = v['MSVC_VERSION']
  742. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  743. v.MSVC_MANIFEST = (compiler == 'msvc' and version >= 8) or (compiler == 'wsdk' and version >= 6) or (compiler == 'intel' and version >= 11)
  744. # compiler
  745. cxx = None
  746. if v['CXX']: cxx = v['CXX']
  747. elif 'CXX' in conf.environ: cxx = conf.environ['CXX']
  748. cxx = conf.find_program(compiler_name, var='CXX', path_list=path)
  749. # before setting anything, check if the compiler is really msvc
  750. env = dict(conf.environ)
  751. if path: env.update(PATH = ';'.join(path))
  752. if not conf.cmd_and_log(cxx + ['/nologo', '/help'], env=env):
  753. conf.fatal('the msvc compiler could not be identified')
  754. # c/c++ compiler
  755. v['CC'] = v['CXX'] = cxx
  756. v['CC_NAME'] = v['CXX_NAME'] = 'msvc'
  757. # linker
  758. if not v['LINK_CXX']:
  759. link = conf.find_program(linker_name, path_list=path)
  760. if link: v['LINK_CXX'] = link
  761. else: conf.fatal('%s was not found (linker)' % linker_name)
  762. v['LINK'] = link
  763. if not v['LINK_CC']:
  764. v['LINK_CC'] = v['LINK_CXX']
  765. # staticlib linker
  766. if not v['AR']:
  767. stliblink = conf.find_program(lib_name, path_list=path, var='AR')
  768. if not stliblink: return
  769. v['ARFLAGS'] = ['/NOLOGO']
  770. # manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later
  771. if v.MSVC_MANIFEST:
  772. conf.find_program('MT', path_list=path, var='MT')
  773. v['MTFLAGS'] = ['/NOLOGO']
  774. try:
  775. conf.load('winres')
  776. except Errors.WafError:
  777. warn('Resource compiler not found. Compiling resource file is disabled')
  778. @conf
  779. def visual_studio_add_flags(self):
  780. """visual studio flags found in the system environment"""
  781. v = self.env
  782. try: v.prepend_value('INCLUDES', [x for x in self.environ['INCLUDE'].split(';') if x]) # notice the 'S'
  783. except Exception: pass
  784. try: v.prepend_value('LIBPATH', [x for x in self.environ['LIB'].split(';') if x])
  785. except Exception: pass
  786. @conf
  787. def msvc_common_flags(conf):
  788. """
  789. Setup the flags required for executing the msvc compiler
  790. """
  791. v = conf.env
  792. v['DEST_BINFMT'] = 'pe'
  793. v.append_value('CFLAGS', ['/nologo'])
  794. v.append_value('CXXFLAGS', ['/nologo'])
  795. v['DEFINES_ST'] = '/D%s'
  796. v['CC_SRC_F'] = ''
  797. v['CC_TGT_F'] = ['/c', '/Fo']
  798. v['CXX_SRC_F'] = ''
  799. v['CXX_TGT_F'] = ['/c', '/Fo']
  800. if (v.MSVC_COMPILER == 'msvc' and v.MSVC_VERSION >= 8) or (v.MSVC_COMPILER == 'wsdk' and v.MSVC_VERSION >= 6):
  801. v['CC_TGT_F']= ['/FC'] + v['CC_TGT_F']
  802. v['CXX_TGT_F']= ['/FC'] + v['CXX_TGT_F']
  803. v['CPPPATH_ST'] = '/I%s' # template for adding include paths
  804. v['AR_TGT_F'] = v['CCLNK_TGT_F'] = v['CXXLNK_TGT_F'] = '/OUT:'
  805. # Subsystem specific flags
  806. v['CFLAGS_CONSOLE'] = v['CXXFLAGS_CONSOLE'] = ['/SUBSYSTEM:CONSOLE']
  807. v['CFLAGS_NATIVE'] = v['CXXFLAGS_NATIVE'] = ['/SUBSYSTEM:NATIVE']
  808. v['CFLAGS_POSIX'] = v['CXXFLAGS_POSIX'] = ['/SUBSYSTEM:POSIX']
  809. v['CFLAGS_WINDOWS'] = v['CXXFLAGS_WINDOWS'] = ['/SUBSYSTEM:WINDOWS']
  810. v['CFLAGS_WINDOWSCE'] = v['CXXFLAGS_WINDOWSCE'] = ['/SUBSYSTEM:WINDOWSCE']
  811. # CRT specific flags
  812. v['CFLAGS_CRT_MULTITHREADED'] = v['CXXFLAGS_CRT_MULTITHREADED'] = ['/MT']
  813. v['CFLAGS_CRT_MULTITHREADED_DLL'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL'] = ['/MD']
  814. v['CFLAGS_CRT_MULTITHREADED_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DBG'] = ['/MTd']
  815. v['CFLAGS_CRT_MULTITHREADED_DLL_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL_DBG'] = ['/MDd']
  816. # linker
  817. v['LIB_ST'] = '%s.lib' # template for adding shared libs
  818. v['LIBPATH_ST'] = '/LIBPATH:%s' # template for adding libpaths
  819. v['STLIB_ST'] = '%s.lib'
  820. v['STLIBPATH_ST'] = '/LIBPATH:%s'
  821. v.append_value('LINKFLAGS', ['/NOLOGO'])
  822. if v['MSVC_MANIFEST']:
  823. v.append_value('LINKFLAGS', ['/MANIFEST'])
  824. # shared library
  825. v['CFLAGS_cshlib'] = []
  826. v['CXXFLAGS_cxxshlib'] = []
  827. v['LINKFLAGS_cshlib'] = v['LINKFLAGS_cxxshlib'] = ['/DLL']
  828. v['cshlib_PATTERN'] = v['cxxshlib_PATTERN'] = '%s.dll'
  829. v['implib_PATTERN'] = '%s.lib'
  830. v['IMPLIB_ST'] = '/IMPLIB:%s'
  831. # static library
  832. v['LINKFLAGS_cstlib'] = []
  833. v['cstlib_PATTERN'] = v['cxxstlib_PATTERN'] = '%s.lib'
  834. # program
  835. v['cprogram_PATTERN'] = v['cxxprogram_PATTERN'] = '%s.exe'
  836. #######################################################################################################
  837. ##### conf above, build below
  838. @after_method('apply_link')
  839. @feature('c', 'cxx')
  840. def apply_flags_msvc(self):
  841. """
  842. Add additional flags implied by msvc, such as subsystems and pdb files::
  843. def build(bld):
  844. bld.stlib(source='main.c', target='bar', subsystem='gruik')
  845. """
  846. if self.env.CC_NAME != 'msvc' or not getattr(self, 'link_task', None):
  847. return
  848. is_static = isinstance(self.link_task, ccroot.stlink_task)
  849. subsystem = getattr(self, 'subsystem', '')
  850. if subsystem:
  851. subsystem = '/subsystem:%s' % subsystem
  852. flags = is_static and 'ARFLAGS' or 'LINKFLAGS'
  853. self.env.append_value(flags, subsystem)
  854. if not is_static:
  855. for f in self.env.LINKFLAGS:
  856. d = f.lower()
  857. if d[1:] == 'debug':
  858. pdbnode = self.link_task.outputs[0].change_ext('.pdb')
  859. self.link_task.outputs.append(pdbnode)
  860. if getattr(self, 'install_task', None):
  861. self.pdb_install_task = self.bld.install_files(self.install_task.dest, pdbnode, env=self.env)
  862. break
  863. # split the manifest file processing from the link task, like for the rc processing
  864. @feature('cprogram', 'cshlib', 'cxxprogram', 'cxxshlib')
  865. @after_method('apply_link')
  866. def apply_manifest(self):
  867. """
  868. Special linker for MSVC with support for embedding manifests into DLL's
  869. and executables compiled by Visual Studio 2005 or probably later. Without
  870. the manifest file, the binaries are unusable.
  871. See: http://msdn2.microsoft.com/en-us/library/ms235542(VS.80).aspx
  872. """
  873. if self.env.CC_NAME == 'msvc' and self.env.MSVC_MANIFEST and getattr(self, 'link_task', None):
  874. out_node = self.link_task.outputs[0]
  875. man_node = out_node.parent.find_or_declare(out_node.name + '.manifest')
  876. self.link_task.outputs.append(man_node)
  877. self.link_task.do_manifest = True
  878. def exec_mf(self):
  879. """
  880. Create the manifest file
  881. """
  882. env = self.env
  883. mtool = env['MT']
  884. if not mtool:
  885. return 0
  886. self.do_manifest = False
  887. outfile = self.outputs[0].abspath()
  888. manifest = None
  889. for out_node in self.outputs:
  890. if out_node.name.endswith('.manifest'):
  891. manifest = out_node.abspath()
  892. break
  893. if manifest is None:
  894. # Should never get here. If we do, it means the manifest file was
  895. # never added to the outputs list, thus we don't have a manifest file
  896. # to embed, so we just return.
  897. return 0
  898. # embedding mode. Different for EXE's and DLL's.
  899. # see: http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx
  900. mode = ''
  901. if 'cprogram' in self.generator.features or 'cxxprogram' in self.generator.features:
  902. mode = '1'
  903. elif 'cshlib' in self.generator.features or 'cxxshlib' in self.generator.features:
  904. mode = '2'
  905. debug('msvc: embedding manifest in mode %r' % mode)
  906. lst = [] + mtool
  907. lst.extend(Utils.to_list(env['MTFLAGS']))
  908. lst.extend(['-manifest', manifest])
  909. lst.append('-outputresource:%s;%s' % (outfile, mode))
  910. return self.exec_command(lst)
  911. def quote_response_command(self, flag):
  912. if flag.find(' ') > -1:
  913. for x in ('/LIBPATH:', '/IMPLIB:', '/OUT:', '/I'):
  914. if flag.startswith(x):
  915. flag = '%s"%s"' % (x, flag[len(x):])
  916. break
  917. else:
  918. flag = '"%s"' % flag
  919. return flag
  920. def exec_response_command(self, cmd, **kw):
  921. # not public yet
  922. try:
  923. tmp = None
  924. if sys.platform.startswith('win') and isinstance(cmd, list) and len(' '.join(cmd)) >= 8192:
  925. program = cmd[0] #unquoted program name, otherwise exec_command will fail
  926. cmd = [self.quote_response_command(x) for x in cmd]
  927. (fd, tmp) = tempfile.mkstemp()
  928. os.write(fd, '\r\n'.join(i.replace('\\', '\\\\') for i in cmd[1:]).encode())
  929. os.close(fd)
  930. cmd = [program, '@' + tmp]
  931. # no return here, that's on purpose
  932. ret = self.generator.bld.exec_command(cmd, **kw)
  933. finally:
  934. if tmp:
  935. try:
  936. os.remove(tmp)
  937. except OSError:
  938. pass # anti-virus and indexers can keep the files open -_-
  939. return ret
  940. ########## stupid evil command modification: concatenate the tokens /Fx, /doc, and /x: with the next token
  941. def exec_command_msvc(self, *k, **kw):
  942. """
  943. Change the command-line execution for msvc programs.
  944. Instead of quoting all the paths and keep using the shell, we can just join the options msvc is interested in
  945. """
  946. if isinstance(k[0], list):
  947. lst = []
  948. carry = ''
  949. for a in k[0]:
  950. if a == '/Fo' or a == '/doc' or a[-1] == ':':
  951. carry = a
  952. else:
  953. lst.append(carry + a)
  954. carry = ''
  955. k = [lst]
  956. if self.env['PATH']:
  957. env = dict(self.env.env or os.environ)
  958. env.update(PATH = ';'.join(self.env['PATH']))
  959. kw['env'] = env
  960. bld = self.generator.bld
  961. try:
  962. if not kw.get('cwd', None):
  963. kw['cwd'] = bld.cwd
  964. except AttributeError:
  965. bld.cwd = kw['cwd'] = bld.variant_dir
  966. ret = self.exec_response_command(k[0], **kw)
  967. if not ret and getattr(self, 'do_manifest', None):
  968. ret = self.exec_mf()
  969. return ret
  970. def wrap_class(class_name):
  971. """
  972. Manifest file processing and @response file workaround for command-line length limits on Windows systems
  973. The indicated task class is replaced by a subclass to prevent conflicts in case the class is wrapped more than once
  974. """
  975. cls = Task.classes.get(class_name, None)
  976. if not cls:
  977. return None
  978. derived_class = type(class_name, (cls,), {})
  979. def exec_command(self, *k, **kw):
  980. if self.env['CC_NAME'] == 'msvc':
  981. return self.exec_command_msvc(*k, **kw)
  982. else:
  983. return super(derived_class, self).exec_command(*k, **kw)
  984. # Chain-up monkeypatch needed since exec_command() is in base class API
  985. derived_class.exec_command = exec_command
  986. # No chain-up behavior needed since the following methods aren't in
  987. # base class API
  988. derived_class.exec_response_command = exec_response_command
  989. derived_class.quote_response_command = quote_response_command
  990. derived_class.exec_command_msvc = exec_command_msvc
  991. derived_class.exec_mf = exec_mf
  992. if hasattr(cls, 'hcode'):
  993. derived_class.hcode = cls.hcode
  994. return derived_class
  995. for k in 'c cxx cprogram cxxprogram cshlib cxxshlib cstlib cxxstlib'.split():
  996. wrap_class(k)
  997. def make_winapp(self, family):
  998. append = self.env.append_unique
  999. append('DEFINES', 'WINAPI_FAMILY=%s' % family)
  1000. append('CXXFLAGS', '/ZW')
  1001. append('CXXFLAGS', '/TP')
  1002. for lib_path in self.env.LIBPATH:
  1003. append('CXXFLAGS','/AI%s'%lib_path)
  1004. @feature('winphoneapp')
  1005. @after_method('process_use')
  1006. @after_method('propagate_uselib_vars')
  1007. def make_winphone_app(self):
  1008. """
  1009. Insert configuration flags for windows phone applications (adds /ZW, /TP...)
  1010. """
  1011. make_winapp(self, 'WINAPI_FAMILY_PHONE_APP')
  1012. conf.env.append_unique('LINKFLAGS', '/NODEFAULTLIB:ole32.lib')
  1013. conf.env.append_unique('LINKFLAGS', 'PhoneAppModelHost.lib')
  1014. @feature('winapp')
  1015. @after_method('process_use')
  1016. @after_method('propagate_uselib_vars')
  1017. def make_windows_app(self):
  1018. """
  1019. Insert configuration flags for windows applications (adds /ZW, /TP...)
  1020. """
  1021. make_winapp(self, 'WINAPI_FAMILY_DESKTOP_APP')