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.

1176 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 UnicodeError:
  167. st = Utils.ex_stack()
  168. if conf.logger:
  169. conf.logger.error(st)
  170. conf.fatal('msvc: Unicode error - check the code page?')
  171. except Exception as e:
  172. debug('msvc: get_msvc_version: %r %r %r -> failure %s' % (compiler, version, target, str(e)))
  173. conf.fatal('msvc: cannot run the compiler in get_msvc_version (run with -v to display errors)')
  174. else:
  175. debug('msvc: get_msvc_version: %r %r %r -> OK', compiler, version, target)
  176. finally:
  177. conf.env[compiler_name] = ''
  178. return (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR)
  179. @conf
  180. def gather_wsdk_versions(conf, versions):
  181. """
  182. Use winreg to add the msvc versions to the input list
  183. :param versions: list to modify
  184. :type versions: list
  185. """
  186. version_pattern = re.compile('^v..?.?\...?.?')
  187. try:
  188. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Microsoft SDKs\\Windows')
  189. except WindowsError:
  190. try:
  191. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows')
  192. except WindowsError:
  193. return
  194. index = 0
  195. while 1:
  196. try:
  197. version = Utils.winreg.EnumKey(all_versions, index)
  198. except WindowsError:
  199. break
  200. index = index + 1
  201. if not version_pattern.match(version):
  202. continue
  203. try:
  204. msvc_version = Utils.winreg.OpenKey(all_versions, version)
  205. path,type = Utils.winreg.QueryValueEx(msvc_version,'InstallationFolder')
  206. except WindowsError:
  207. continue
  208. if path and os.path.isfile(os.path.join(path, 'bin', 'SetEnv.cmd')):
  209. targets = []
  210. for target,arch in all_msvc_platforms:
  211. try:
  212. targets.append((target, (arch, get_compiler_env(conf, 'wsdk', version, '/'+target, os.path.join(path, 'bin', 'SetEnv.cmd')))))
  213. except conf.errors.ConfigurationError:
  214. pass
  215. versions.append(('wsdk ' + version[1:], targets))
  216. def gather_wince_supported_platforms():
  217. """
  218. Checks SmartPhones SDKs
  219. :param versions: list to modify
  220. :type versions: list
  221. """
  222. supported_wince_platforms = []
  223. try:
  224. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Windows CE Tools\\SDKs')
  225. except WindowsError:
  226. try:
  227. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows CE Tools\\SDKs')
  228. except WindowsError:
  229. ce_sdk = ''
  230. if not ce_sdk:
  231. return supported_wince_platforms
  232. ce_index = 0
  233. while 1:
  234. try:
  235. sdk_device = Utils.winreg.EnumKey(ce_sdk, ce_index)
  236. except WindowsError:
  237. break
  238. ce_index = ce_index + 1
  239. sdk = Utils.winreg.OpenKey(ce_sdk, sdk_device)
  240. try:
  241. path,type = Utils.winreg.QueryValueEx(sdk, 'SDKRootDir')
  242. except WindowsError:
  243. try:
  244. path,type = Utils.winreg.QueryValueEx(sdk,'SDKInformation')
  245. path,xml = os.path.split(path)
  246. except WindowsError:
  247. continue
  248. path=str(path)
  249. path,device = os.path.split(path)
  250. if not device:
  251. path,device = os.path.split(path)
  252. platforms = []
  253. for arch,compiler in all_wince_platforms:
  254. if os.path.isdir(os.path.join(path, device, 'Lib', arch)):
  255. platforms.append((arch, compiler, os.path.join(path, device, 'Include', arch), os.path.join(path, device, 'Lib', arch)))
  256. if platforms:
  257. supported_wince_platforms.append((device, platforms))
  258. return supported_wince_platforms
  259. def gather_msvc_detected_versions():
  260. #Detected MSVC versions!
  261. version_pattern = re.compile('^(\d\d?\.\d\d?)(Exp)?$')
  262. detected_versions = []
  263. for vcver,vcvar in (('VCExpress','Exp'), ('VisualStudio','')):
  264. try:
  265. prefix = 'SOFTWARE\\Wow6432node\\Microsoft\\'+vcver
  266. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  267. except WindowsError:
  268. try:
  269. prefix = 'SOFTWARE\\Microsoft\\'+vcver
  270. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  271. except WindowsError:
  272. continue
  273. index = 0
  274. while 1:
  275. try:
  276. version = Utils.winreg.EnumKey(all_versions, index)
  277. except WindowsError:
  278. break
  279. index = index + 1
  280. match = version_pattern.match(version)
  281. if not match:
  282. continue
  283. else:
  284. versionnumber = float(match.group(1))
  285. detected_versions.append((versionnumber, version+vcvar, prefix+"\\"+version))
  286. def fun(tup):
  287. return tup[0]
  288. detected_versions.sort(key = fun)
  289. return detected_versions
  290. def get_compiler_env(conf, compiler, version, bat_target, bat, select=None):
  291. """
  292. Gets the compiler environment variables as a tuple. Evaluation is eager by default.
  293. If set to lazy with ``--msvc_lazy_autodetect`` or ``env.MSVC_LAZY_AUTODETECT``
  294. the environment is evaluated when the tuple is destructured or iterated. This means
  295. destructuring can throw :py:class:`conf.errors.ConfigurationError`.
  296. :param conf: configuration context to use to eventually get the version environment
  297. :param compiler: compiler name
  298. :param version: compiler version number
  299. :param bat: path to the batch file to run
  300. :param select: optional function to take the realized environment variables tup and map it (e.g. to combine other constant paths)
  301. """
  302. lazy = getattr(Options.options, 'msvc_lazy_autodetect', False) or conf.env['MSVC_LAZY_AUTODETECT']
  303. def msvc_thunk():
  304. vs = conf.get_msvc_version(compiler, version, bat_target, bat)
  305. if select:
  306. return select(vs)
  307. else:
  308. return vs
  309. return lazytup(msvc_thunk, lazy, ([], [], []))
  310. class lazytup(object):
  311. """
  312. A tuple that evaluates its elements from a function when iterated or destructured.
  313. :param fn: thunk to evaluate the tuple on demand
  314. :param lazy: whether to delay evaluation or evaluate in the constructor
  315. :param default: optional default for :py:func:`repr` if it should not evaluate
  316. """
  317. def __init__(self, fn, lazy=True, default=None):
  318. self.fn = fn
  319. self.default = default
  320. if not lazy:
  321. self.evaluate()
  322. def __len__(self):
  323. self.evaluate()
  324. return len(self.value)
  325. def __iter__(self):
  326. self.evaluate()
  327. for i, v in enumerate(self.value):
  328. yield v
  329. def __getitem__(self, i):
  330. self.evaluate()
  331. return self.value[i]
  332. def __repr__(self):
  333. if hasattr(self, 'value'):
  334. return repr(self.value)
  335. elif self.default:
  336. return repr(self.default)
  337. else:
  338. self.evaluate()
  339. return repr(self.value)
  340. def evaluate(self):
  341. if hasattr(self, 'value'):
  342. return
  343. self.value = self.fn()
  344. @conf
  345. def gather_msvc_targets(conf, versions, version, vc_path):
  346. #Looking for normal MSVC compilers!
  347. targets = []
  348. if os.path.isfile(os.path.join(vc_path, 'vcvarsall.bat')):
  349. for target,realtarget in all_msvc_platforms[::-1]:
  350. try:
  351. targets.append((target, (realtarget, get_compiler_env(conf, 'msvc', version, target, os.path.join(vc_path, 'vcvarsall.bat')))))
  352. except conf.errors.ConfigurationError:
  353. pass
  354. elif os.path.isfile(os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')):
  355. try:
  356. targets.append(('x86', ('x86', get_compiler_env(conf, 'msvc', version, 'x86', os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')))))
  357. except conf.errors.ConfigurationError:
  358. pass
  359. elif os.path.isfile(os.path.join(vc_path, 'Bin', 'vcvars32.bat')):
  360. try:
  361. targets.append(('x86', ('x86', get_compiler_env(conf, 'msvc', version, '', os.path.join(vc_path, 'Bin', 'vcvars32.bat')))))
  362. except conf.errors.ConfigurationError:
  363. pass
  364. if targets:
  365. versions.append(('msvc '+ version, targets))
  366. @conf
  367. def gather_wince_targets(conf, versions, version, vc_path, vsvars, supported_platforms):
  368. #Looking for Win CE compilers!
  369. for device,platforms in supported_platforms:
  370. cetargets = []
  371. for platform,compiler,include,lib in platforms:
  372. winCEpath = os.path.join(vc_path, 'ce')
  373. if not os.path.isdir(winCEpath):
  374. continue
  375. if os.path.isdir(os.path.join(winCEpath, 'lib', platform)):
  376. bindirs = [os.path.join(winCEpath, 'bin', compiler), os.path.join(winCEpath, 'bin', 'x86_'+compiler)]
  377. incdirs = [os.path.join(winCEpath, 'include'), os.path.join(winCEpath, 'atlmfc', 'include'), include]
  378. libdirs = [os.path.join(winCEpath, 'lib', platform), os.path.join(winCEpath, 'atlmfc', 'lib', platform), lib]
  379. def combine_common(compiler_env):
  380. (common_bindirs,_1,_2) = compiler_env
  381. return (bindirs + common_bindirs, incdirs, libdirs)
  382. try:
  383. cetargets.append((platform, (platform, get_compiler_env(conf, 'msvc', version, 'x86', vsvars, combine_common))))
  384. except conf.errors.ConfigurationError:
  385. continue
  386. if cetargets:
  387. versions.append((device + ' ' + version, cetargets))
  388. @conf
  389. def gather_winphone_targets(conf, versions, version, vc_path, vsvars):
  390. #Looking for WinPhone compilers
  391. targets = []
  392. for target,realtarget in all_msvc_platforms[::-1]:
  393. try:
  394. targets.append((target, (realtarget, get_compiler_env(conf, 'winphone', version, target, vsvars))))
  395. except conf.errors.ConfigurationError:
  396. pass
  397. if targets:
  398. versions.append(('winphone '+ version, targets))
  399. @conf
  400. def gather_msvc_versions(conf, versions):
  401. vc_paths = []
  402. for (v,version,reg) in gather_msvc_detected_versions():
  403. try:
  404. try:
  405. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\VC")
  406. except WindowsError:
  407. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\Microsoft Visual C++")
  408. path,type = Utils.winreg.QueryValueEx(msvc_version, 'ProductDir')
  409. vc_paths.append((version, os.path.abspath(str(path))))
  410. except WindowsError:
  411. continue
  412. wince_supported_platforms = gather_wince_supported_platforms()
  413. for version,vc_path in vc_paths:
  414. vs_path = os.path.dirname(vc_path)
  415. vsvars = os.path.join(vs_path, 'Common7', 'Tools', 'vsvars32.bat')
  416. if wince_supported_platforms and os.path.isfile(vsvars):
  417. conf.gather_wince_targets(versions, version, vc_path, vsvars, wince_supported_platforms)
  418. # WP80 works with 11.0Exp and 11.0, both of which resolve to the same vc_path.
  419. # Stop after one is found.
  420. for version,vc_path in vc_paths:
  421. vs_path = os.path.dirname(vc_path)
  422. vsvars = os.path.join(vs_path, 'VC', 'WPSDK', 'WP80', 'vcvarsphoneall.bat')
  423. if os.path.isfile(vsvars):
  424. conf.gather_winphone_targets(versions, '8.0', vc_path, vsvars)
  425. break
  426. for version,vc_path in vc_paths:
  427. vs_path = os.path.dirname(vc_path)
  428. conf.gather_msvc_targets(versions, version, vc_path)
  429. @conf
  430. def gather_icl_versions(conf, versions):
  431. """
  432. Checks ICL compilers
  433. :param versions: list to modify
  434. :type versions: list
  435. """
  436. version_pattern = re.compile('^...?.?\....?.?')
  437. try:
  438. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Compilers\\C++')
  439. except WindowsError:
  440. try:
  441. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Compilers\\C++')
  442. except WindowsError:
  443. return
  444. index = 0
  445. while 1:
  446. try:
  447. version = Utils.winreg.EnumKey(all_versions, index)
  448. except WindowsError:
  449. break
  450. index = index + 1
  451. if not version_pattern.match(version):
  452. continue
  453. targets = []
  454. for target,arch in all_icl_platforms:
  455. try:
  456. if target=='intel64': targetDir='EM64T_NATIVE'
  457. else: targetDir=target
  458. Utils.winreg.OpenKey(all_versions,version+'\\'+targetDir)
  459. icl_version=Utils.winreg.OpenKey(all_versions,version)
  460. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  461. batch_file=os.path.join(path,'bin','iclvars.bat')
  462. if os.path.isfile(batch_file):
  463. try:
  464. targets.append((target,(arch,get_compiler_env(conf,'intel',version,target,batch_file))))
  465. except conf.errors.ConfigurationError:
  466. pass
  467. except WindowsError:
  468. pass
  469. for target,arch in all_icl_platforms:
  470. try:
  471. icl_version = Utils.winreg.OpenKey(all_versions, version+'\\'+target)
  472. path,type = Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  473. batch_file=os.path.join(path,'bin','iclvars.bat')
  474. if os.path.isfile(batch_file):
  475. try:
  476. targets.append((target, (arch, get_compiler_env(conf, 'intel', version, target, batch_file))))
  477. except conf.errors.ConfigurationError:
  478. pass
  479. except WindowsError:
  480. continue
  481. major = version[0:2]
  482. versions.append(('intel ' + major, targets))
  483. @conf
  484. def gather_intel_composer_versions(conf, versions):
  485. """
  486. Checks ICL compilers that are part of Intel Composer Suites
  487. :param versions: list to modify
  488. :type versions: list
  489. """
  490. version_pattern = re.compile('^...?.?\...?.?.?')
  491. try:
  492. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Suites')
  493. except WindowsError:
  494. try:
  495. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Suites')
  496. except WindowsError:
  497. return
  498. index = 0
  499. while 1:
  500. try:
  501. version = Utils.winreg.EnumKey(all_versions, index)
  502. except WindowsError:
  503. break
  504. index = index + 1
  505. if not version_pattern.match(version):
  506. continue
  507. targets = []
  508. for target,arch in all_icl_platforms:
  509. try:
  510. if target=='intel64': targetDir='EM64T_NATIVE'
  511. else: targetDir=target
  512. try:
  513. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\'+targetDir)
  514. except WindowsError:
  515. if targetDir=='EM64T_NATIVE':
  516. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\EM64T')
  517. else:
  518. raise WindowsError
  519. uid,type = Utils.winreg.QueryValueEx(defaults, 'SubKey')
  520. Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++\\'+targetDir)
  521. icl_version=Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++')
  522. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  523. batch_file=os.path.join(path,'bin','iclvars.bat')
  524. if os.path.isfile(batch_file):
  525. try:
  526. targets.append((target,(arch,get_compiler_env(conf,'intel',version,target,batch_file))))
  527. except conf.errors.ConfigurationError:
  528. pass
  529. # The intel compilervar_arch.bat is broken when used with Visual Studio Express 2012
  530. # http://software.intel.com/en-us/forums/topic/328487
  531. compilervars_warning_attr = '_compilervars_warning_key'
  532. if version[0:2] == '13' and getattr(conf, compilervars_warning_attr, True):
  533. setattr(conf, compilervars_warning_attr, False)
  534. patch_url = 'http://software.intel.com/en-us/forums/topic/328487'
  535. compilervars_arch = os.path.join(path, 'bin', 'compilervars_arch.bat')
  536. for vscomntool in ('VS110COMNTOOLS', 'VS100COMNTOOLS'):
  537. if vscomntool in os.environ:
  538. vs_express_path = os.environ[vscomntool] + r'..\IDE\VSWinExpress.exe'
  539. dev_env_path = os.environ[vscomntool] + r'..\IDE\devenv.exe'
  540. if (r'if exist "%VS110COMNTOOLS%..\IDE\VSWinExpress.exe"' in Utils.readf(compilervars_arch) and
  541. not os.path.exists(vs_express_path) and not os.path.exists(dev_env_path)):
  542. Logs.warn(('The Intel compilervar_arch.bat only checks for one Visual Studio SKU '
  543. '(VSWinExpress.exe) but it does not seem to be installed at %r. '
  544. 'The intel command line set up will fail to configure unless the file %r'
  545. 'is patched. See: %s') % (vs_express_path, compilervars_arch, patch_url))
  546. except WindowsError:
  547. pass
  548. major = version[0:2]
  549. versions.append(('intel ' + major, targets))
  550. @conf
  551. def get_msvc_versions(conf, eval_and_save=True):
  552. """
  553. :return: list of compilers installed
  554. :rtype: list of string
  555. """
  556. if conf.env['MSVC_INSTALLED_VERSIONS']:
  557. return conf.env['MSVC_INSTALLED_VERSIONS']
  558. # Gather all the compiler versions and targets. This phase can be lazy
  559. # per lazy detection settings.
  560. lst = []
  561. conf.gather_icl_versions(lst)
  562. conf.gather_intel_composer_versions(lst)
  563. conf.gather_wsdk_versions(lst)
  564. conf.gather_msvc_versions(lst)
  565. # Override lazy detection by evaluating after the fact.
  566. if eval_and_save:
  567. def checked_target(t):
  568. target,(arch,paths) = t
  569. try:
  570. paths.evaluate()
  571. except conf.errors.ConfigurationError:
  572. return None
  573. else:
  574. return t
  575. lst = [(version, list(filter(checked_target, targets))) for version, targets in lst]
  576. conf.env['MSVC_INSTALLED_VERSIONS'] = lst
  577. return lst
  578. @conf
  579. def print_all_msvc_detected(conf):
  580. """
  581. Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS*
  582. """
  583. for version,targets in conf.env['MSVC_INSTALLED_VERSIONS']:
  584. Logs.info(version)
  585. for target,l in targets:
  586. Logs.info("\t"+target)
  587. @conf
  588. def detect_msvc(conf, arch = False):
  589. # Save installed versions only if lazy detection is disabled.
  590. lazy_detect = getattr(Options.options, 'msvc_lazy_autodetect', False) or conf.env['MSVC_LAZY_AUTODETECT']
  591. versions = get_msvc_versions(conf, not lazy_detect)
  592. return setup_msvc(conf, versions, arch)
  593. @conf
  594. def find_lt_names_msvc(self, libname, is_static=False):
  595. """
  596. Win32/MSVC specific code to glean out information from libtool la files.
  597. this function is not attached to the task_gen class
  598. """
  599. lt_names=[
  600. 'lib%s.la' % libname,
  601. '%s.la' % libname,
  602. ]
  603. for path in self.env['LIBPATH']:
  604. for la in lt_names:
  605. laf=os.path.join(path,la)
  606. dll=None
  607. if os.path.exists(laf):
  608. ltdict = Utils.read_la_file(laf)
  609. lt_libdir=None
  610. if ltdict.get('libdir', ''):
  611. lt_libdir = ltdict['libdir']
  612. if not is_static and ltdict.get('library_names', ''):
  613. dllnames=ltdict['library_names'].split()
  614. dll=dllnames[0].lower()
  615. dll=re.sub('\.dll$', '', dll)
  616. return (lt_libdir, dll, False)
  617. elif ltdict.get('old_library', ''):
  618. olib=ltdict['old_library']
  619. if os.path.exists(os.path.join(path,olib)):
  620. return (path, olib, True)
  621. elif lt_libdir != '' and os.path.exists(os.path.join(lt_libdir,olib)):
  622. return (lt_libdir, olib, True)
  623. else:
  624. return (None, olib, True)
  625. else:
  626. raise self.errors.WafError('invalid libtool object file: %s' % laf)
  627. return (None, None, None)
  628. @conf
  629. def libname_msvc(self, libname, is_static=False):
  630. lib = libname.lower()
  631. lib = re.sub('\.lib$','',lib)
  632. if lib in g_msvc_systemlibs:
  633. return lib
  634. lib=re.sub('^lib','',lib)
  635. if lib == 'm':
  636. return None
  637. (lt_path, lt_libname, lt_static) = self.find_lt_names_msvc(lib, is_static)
  638. if lt_path != None and lt_libname != None:
  639. if lt_static == True:
  640. # file existance check has been made by find_lt_names
  641. return os.path.join(lt_path,lt_libname)
  642. if lt_path != None:
  643. _libpaths=[lt_path] + self.env['LIBPATH']
  644. else:
  645. _libpaths=self.env['LIBPATH']
  646. static_libs=[
  647. 'lib%ss.lib' % lib,
  648. 'lib%s.lib' % lib,
  649. '%ss.lib' % lib,
  650. '%s.lib' %lib,
  651. ]
  652. dynamic_libs=[
  653. 'lib%s.dll.lib' % lib,
  654. 'lib%s.dll.a' % lib,
  655. '%s.dll.lib' % lib,
  656. '%s.dll.a' % lib,
  657. 'lib%s_d.lib' % lib,
  658. '%s_d.lib' % lib,
  659. '%s.lib' %lib,
  660. ]
  661. libnames=static_libs
  662. if not is_static:
  663. libnames=dynamic_libs + static_libs
  664. for path in _libpaths:
  665. for libn in libnames:
  666. if os.path.exists(os.path.join(path, libn)):
  667. debug('msvc: lib found: %s' % os.path.join(path,libn))
  668. return re.sub('\.lib$', '',libn)
  669. #if no lib can be found, just return the libname as msvc expects it
  670. self.fatal("The library %r could not be found" % libname)
  671. return re.sub('\.lib$', '', libname)
  672. @conf
  673. def check_lib_msvc(self, libname, is_static=False, uselib_store=None):
  674. """
  675. Ideally we should be able to place the lib in the right env var, either STLIB or LIB,
  676. but we don't distinguish static libs from shared libs.
  677. This is ok since msvc doesn't have any special linker flag to select static libs (no env['STLIB_MARKER'])
  678. """
  679. libn = self.libname_msvc(libname, is_static)
  680. if not uselib_store:
  681. uselib_store = libname.upper()
  682. if False and is_static: # disabled
  683. self.env['STLIB_' + uselib_store] = [libn]
  684. else:
  685. self.env['LIB_' + uselib_store] = [libn]
  686. @conf
  687. def check_libs_msvc(self, libnames, is_static=False):
  688. for libname in Utils.to_list(libnames):
  689. self.check_lib_msvc(libname, is_static)
  690. def configure(conf):
  691. """
  692. Configuration methods to call for detecting msvc
  693. """
  694. conf.autodetect(True)
  695. conf.find_msvc()
  696. conf.msvc_common_flags()
  697. conf.cc_load_tools()
  698. conf.cxx_load_tools()
  699. conf.cc_add_flags()
  700. conf.cxx_add_flags()
  701. conf.link_add_flags()
  702. conf.visual_studio_add_flags()
  703. @conf
  704. def no_autodetect(conf):
  705. conf.env.NO_MSVC_DETECT = 1
  706. configure(conf)
  707. @conf
  708. def autodetect(conf, arch = False):
  709. v = conf.env
  710. if v.NO_MSVC_DETECT:
  711. return
  712. if arch:
  713. compiler, version, path, includes, libdirs, arch = conf.detect_msvc(True)
  714. v['DEST_CPU'] = arch
  715. else:
  716. compiler, version, path, includes, libdirs = conf.detect_msvc()
  717. v['PATH'] = path
  718. v['INCLUDES'] = includes
  719. v['LIBPATH'] = libdirs
  720. v['MSVC_COMPILER'] = compiler
  721. try:
  722. v['MSVC_VERSION'] = float(version)
  723. except Exception:
  724. v['MSVC_VERSION'] = float(version[:-3])
  725. def _get_prog_names(conf, compiler):
  726. if compiler=='intel':
  727. compiler_name = 'ICL'
  728. linker_name = 'XILINK'
  729. lib_name = 'XILIB'
  730. else:
  731. # assumes CL.exe
  732. compiler_name = 'CL'
  733. linker_name = 'LINK'
  734. lib_name = 'LIB'
  735. return compiler_name, linker_name, lib_name
  736. @conf
  737. def find_msvc(conf):
  738. """Due to path format limitations, limit operation only to native Win32. Yeah it sucks."""
  739. if sys.platform == 'cygwin':
  740. conf.fatal('MSVC module does not work under cygwin Python!')
  741. # the autodetection is supposed to be performed before entering in this method
  742. v = conf.env
  743. path = v['PATH']
  744. compiler = v['MSVC_COMPILER']
  745. version = v['MSVC_VERSION']
  746. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  747. v.MSVC_MANIFEST = (compiler == 'msvc' and version >= 8) or (compiler == 'wsdk' and version >= 6) or (compiler == 'intel' and version >= 11)
  748. # compiler
  749. cxx = conf.find_program(compiler_name, var='CXX', path_list=path)
  750. # before setting anything, check if the compiler is really msvc
  751. env = dict(conf.environ)
  752. if path: env.update(PATH = ';'.join(path))
  753. if not conf.cmd_and_log(cxx + ['/nologo', '/help'], env=env):
  754. conf.fatal('the msvc compiler could not be identified')
  755. # c/c++ compiler
  756. v['CC'] = v['CXX'] = cxx
  757. v['CC_NAME'] = v['CXX_NAME'] = 'msvc'
  758. # linker
  759. if not v['LINK_CXX']:
  760. link = conf.find_program(linker_name, path_list=path)
  761. if link: v['LINK_CXX'] = link
  762. else: conf.fatal('%s was not found (linker)' % linker_name)
  763. v['LINK'] = link
  764. if not v['LINK_CC']:
  765. v['LINK_CC'] = v['LINK_CXX']
  766. # staticlib linker
  767. if not v['AR']:
  768. stliblink = conf.find_program(lib_name, path_list=path, var='AR')
  769. if not stliblink: return
  770. v['ARFLAGS'] = ['/NOLOGO']
  771. # manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later
  772. if v.MSVC_MANIFEST:
  773. conf.find_program('MT', path_list=path, var='MT')
  774. v['MTFLAGS'] = ['/NOLOGO']
  775. try:
  776. conf.load('winres')
  777. except Errors.WafError:
  778. warn('Resource compiler not found. Compiling resource file is disabled')
  779. @conf
  780. def visual_studio_add_flags(self):
  781. """visual studio flags found in the system environment"""
  782. v = self.env
  783. try: v.prepend_value('INCLUDES', [x for x in self.environ['INCLUDE'].split(';') if x]) # notice the 'S'
  784. except Exception: pass
  785. try: v.prepend_value('LIBPATH', [x for x in self.environ['LIB'].split(';') if x])
  786. except Exception: pass
  787. @conf
  788. def msvc_common_flags(conf):
  789. """
  790. Setup the flags required for executing the msvc compiler
  791. """
  792. v = conf.env
  793. v['DEST_BINFMT'] = 'pe'
  794. v.append_value('CFLAGS', ['/nologo'])
  795. v.append_value('CXXFLAGS', ['/nologo'])
  796. v['DEFINES_ST'] = '/D%s'
  797. v['CC_SRC_F'] = ''
  798. v['CC_TGT_F'] = ['/c', '/Fo']
  799. v['CXX_SRC_F'] = ''
  800. v['CXX_TGT_F'] = ['/c', '/Fo']
  801. if (v.MSVC_COMPILER == 'msvc' and v.MSVC_VERSION >= 8) or (v.MSVC_COMPILER == 'wsdk' and v.MSVC_VERSION >= 6):
  802. v['CC_TGT_F']= ['/FC'] + v['CC_TGT_F']
  803. v['CXX_TGT_F']= ['/FC'] + v['CXX_TGT_F']
  804. v['CPPPATH_ST'] = '/I%s' # template for adding include paths
  805. v['AR_TGT_F'] = v['CCLNK_TGT_F'] = v['CXXLNK_TGT_F'] = '/OUT:'
  806. # Subsystem specific flags
  807. v['CFLAGS_CONSOLE'] = v['CXXFLAGS_CONSOLE'] = ['/SUBSYSTEM:CONSOLE']
  808. v['CFLAGS_NATIVE'] = v['CXXFLAGS_NATIVE'] = ['/SUBSYSTEM:NATIVE']
  809. v['CFLAGS_POSIX'] = v['CXXFLAGS_POSIX'] = ['/SUBSYSTEM:POSIX']
  810. v['CFLAGS_WINDOWS'] = v['CXXFLAGS_WINDOWS'] = ['/SUBSYSTEM:WINDOWS']
  811. v['CFLAGS_WINDOWSCE'] = v['CXXFLAGS_WINDOWSCE'] = ['/SUBSYSTEM:WINDOWSCE']
  812. # CRT specific flags
  813. v['CFLAGS_CRT_MULTITHREADED'] = v['CXXFLAGS_CRT_MULTITHREADED'] = ['/MT']
  814. v['CFLAGS_CRT_MULTITHREADED_DLL'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL'] = ['/MD']
  815. v['CFLAGS_CRT_MULTITHREADED_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DBG'] = ['/MTd']
  816. v['CFLAGS_CRT_MULTITHREADED_DLL_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL_DBG'] = ['/MDd']
  817. # linker
  818. v['LIB_ST'] = '%s.lib' # template for adding shared libs
  819. v['LIBPATH_ST'] = '/LIBPATH:%s' # template for adding libpaths
  820. v['STLIB_ST'] = '%s.lib'
  821. v['STLIBPATH_ST'] = '/LIBPATH:%s'
  822. v.append_value('LINKFLAGS', ['/NOLOGO'])
  823. if v['MSVC_MANIFEST']:
  824. v.append_value('LINKFLAGS', ['/MANIFEST'])
  825. # shared library
  826. v['CFLAGS_cshlib'] = []
  827. v['CXXFLAGS_cxxshlib'] = []
  828. v['LINKFLAGS_cshlib'] = v['LINKFLAGS_cxxshlib'] = ['/DLL']
  829. v['cshlib_PATTERN'] = v['cxxshlib_PATTERN'] = '%s.dll'
  830. v['implib_PATTERN'] = '%s.lib'
  831. v['IMPLIB_ST'] = '/IMPLIB:%s'
  832. # static library
  833. v['LINKFLAGS_cstlib'] = []
  834. v['cstlib_PATTERN'] = v['cxxstlib_PATTERN'] = '%s.lib'
  835. # program
  836. v['cprogram_PATTERN'] = v['cxxprogram_PATTERN'] = '%s.exe'
  837. #######################################################################################################
  838. ##### conf above, build below
  839. @after_method('apply_link')
  840. @feature('c', 'cxx')
  841. def apply_flags_msvc(self):
  842. """
  843. Add additional flags implied by msvc, such as subsystems and pdb files::
  844. def build(bld):
  845. bld.stlib(source='main.c', target='bar', subsystem='gruik')
  846. """
  847. if self.env.CC_NAME != 'msvc' or not getattr(self, 'link_task', None):
  848. return
  849. is_static = isinstance(self.link_task, ccroot.stlink_task)
  850. subsystem = getattr(self, 'subsystem', '')
  851. if subsystem:
  852. subsystem = '/subsystem:%s' % subsystem
  853. flags = is_static and 'ARFLAGS' or 'LINKFLAGS'
  854. self.env.append_value(flags, subsystem)
  855. if not is_static:
  856. for f in self.env.LINKFLAGS:
  857. d = f.lower()
  858. if d[1:] == 'debug':
  859. pdbnode = self.link_task.outputs[0].change_ext('.pdb')
  860. self.link_task.outputs.append(pdbnode)
  861. if getattr(self, 'install_task', None):
  862. self.pdb_install_task = self.bld.install_files(self.install_task.dest, pdbnode, env=self.env)
  863. break
  864. # split the manifest file processing from the link task, like for the rc processing
  865. @feature('cprogram', 'cshlib', 'cxxprogram', 'cxxshlib')
  866. @after_method('apply_link')
  867. def apply_manifest(self):
  868. """
  869. Special linker for MSVC with support for embedding manifests into DLL's
  870. and executables compiled by Visual Studio 2005 or probably later. Without
  871. the manifest file, the binaries are unusable.
  872. See: http://msdn2.microsoft.com/en-us/library/ms235542(VS.80).aspx
  873. """
  874. if self.env.CC_NAME == 'msvc' and self.env.MSVC_MANIFEST and getattr(self, 'link_task', None):
  875. out_node = self.link_task.outputs[0]
  876. man_node = out_node.parent.find_or_declare(out_node.name + '.manifest')
  877. self.link_task.outputs.append(man_node)
  878. self.link_task.do_manifest = True
  879. def exec_mf(self):
  880. """
  881. Create the manifest file
  882. """
  883. env = self.env
  884. mtool = env['MT']
  885. if not mtool:
  886. return 0
  887. self.do_manifest = False
  888. outfile = self.outputs[0].abspath()
  889. manifest = None
  890. for out_node in self.outputs:
  891. if out_node.name.endswith('.manifest'):
  892. manifest = out_node.abspath()
  893. break
  894. if manifest is None:
  895. # Should never get here. If we do, it means the manifest file was
  896. # never added to the outputs list, thus we don't have a manifest file
  897. # to embed, so we just return.
  898. return 0
  899. # embedding mode. Different for EXE's and DLL's.
  900. # see: http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx
  901. mode = ''
  902. if 'cprogram' in self.generator.features or 'cxxprogram' in self.generator.features:
  903. mode = '1'
  904. elif 'cshlib' in self.generator.features or 'cxxshlib' in self.generator.features:
  905. mode = '2'
  906. debug('msvc: embedding manifest in mode %r' % mode)
  907. lst = [] + mtool
  908. lst.extend(Utils.to_list(env['MTFLAGS']))
  909. lst.extend(['-manifest', manifest])
  910. lst.append('-outputresource:%s;%s' % (outfile, mode))
  911. return self.exec_command(lst)
  912. def quote_response_command(self, flag):
  913. if flag.find(' ') > -1:
  914. for x in ('/LIBPATH:', '/IMPLIB:', '/OUT:', '/I'):
  915. if flag.startswith(x):
  916. flag = '%s"%s"' % (x, flag[len(x):])
  917. break
  918. else:
  919. flag = '"%s"' % flag
  920. return flag
  921. def exec_response_command(self, cmd, **kw):
  922. # not public yet
  923. try:
  924. tmp = None
  925. if sys.platform.startswith('win') and isinstance(cmd, list) and len(' '.join(cmd)) >= 8192:
  926. program = cmd[0] #unquoted program name, otherwise exec_command will fail
  927. cmd = [self.quote_response_command(x) for x in cmd]
  928. (fd, tmp) = tempfile.mkstemp()
  929. os.write(fd, '\r\n'.join(i.replace('\\', '\\\\') for i in cmd[1:]).encode())
  930. os.close(fd)
  931. cmd = [program, '@' + tmp]
  932. # no return here, that's on purpose
  933. ret = self.generator.bld.exec_command(cmd, **kw)
  934. finally:
  935. if tmp:
  936. try:
  937. os.remove(tmp)
  938. except OSError:
  939. pass # anti-virus and indexers can keep the files open -_-
  940. return ret
  941. ########## stupid evil command modification: concatenate the tokens /Fx, /doc, and /x: with the next token
  942. def exec_command_msvc(self, *k, **kw):
  943. """
  944. Change the command-line execution for msvc programs.
  945. Instead of quoting all the paths and keep using the shell, we can just join the options msvc is interested in
  946. """
  947. if isinstance(k[0], list):
  948. lst = []
  949. carry = ''
  950. for a in k[0]:
  951. if a == '/Fo' or a == '/doc' or a[-1] == ':':
  952. carry = a
  953. else:
  954. lst.append(carry + a)
  955. carry = ''
  956. k = [lst]
  957. if self.env['PATH']:
  958. env = dict(self.env.env or os.environ)
  959. env.update(PATH = ';'.join(self.env['PATH']))
  960. kw['env'] = env
  961. bld = self.generator.bld
  962. try:
  963. if not kw.get('cwd', None):
  964. kw['cwd'] = bld.cwd
  965. except AttributeError:
  966. bld.cwd = kw['cwd'] = bld.variant_dir
  967. ret = self.exec_response_command(k[0], **kw)
  968. if not ret and getattr(self, 'do_manifest', None):
  969. ret = self.exec_mf()
  970. return ret
  971. def wrap_class(class_name):
  972. """
  973. Manifest file processing and @response file workaround for command-line length limits on Windows systems
  974. The indicated task class is replaced by a subclass to prevent conflicts in case the class is wrapped more than once
  975. """
  976. cls = Task.classes.get(class_name, None)
  977. if not cls:
  978. return None
  979. derived_class = type(class_name, (cls,), {})
  980. def exec_command(self, *k, **kw):
  981. if self.env['CC_NAME'] == 'msvc':
  982. return self.exec_command_msvc(*k, **kw)
  983. else:
  984. return super(derived_class, self).exec_command(*k, **kw)
  985. # Chain-up monkeypatch needed since exec_command() is in base class API
  986. derived_class.exec_command = exec_command
  987. # No chain-up behavior needed since the following methods aren't in
  988. # base class API
  989. derived_class.exec_response_command = exec_response_command
  990. derived_class.quote_response_command = quote_response_command
  991. derived_class.exec_command_msvc = exec_command_msvc
  992. derived_class.exec_mf = exec_mf
  993. if hasattr(cls, 'hcode'):
  994. derived_class.hcode = cls.hcode
  995. return derived_class
  996. for k in 'c cxx cprogram cxxprogram cshlib cxxshlib cstlib cxxstlib'.split():
  997. wrap_class(k)
  998. def make_winapp(self, family):
  999. append = self.env.append_unique
  1000. append('DEFINES', 'WINAPI_FAMILY=%s' % family)
  1001. append('CXXFLAGS', '/ZW')
  1002. append('CXXFLAGS', '/TP')
  1003. for lib_path in self.env.LIBPATH:
  1004. append('CXXFLAGS','/AI%s'%lib_path)
  1005. @feature('winphoneapp')
  1006. @after_method('process_use')
  1007. @after_method('propagate_uselib_vars')
  1008. def make_winphone_app(self):
  1009. """
  1010. Insert configuration flags for windows phone applications (adds /ZW, /TP...)
  1011. """
  1012. make_winapp(self, 'WINAPI_FAMILY_PHONE_APP')
  1013. conf.env.append_unique('LINKFLAGS', '/NODEFAULTLIB:ole32.lib')
  1014. conf.env.append_unique('LINKFLAGS', 'PhoneAppModelHost.lib')
  1015. @feature('winapp')
  1016. @after_method('process_use')
  1017. @after_method('propagate_uselib_vars')
  1018. def make_windows_app(self):
  1019. """
  1020. Insert configuration flags for windows applications (adds /ZW, /TP...)
  1021. """
  1022. make_winapp(self, 'WINAPI_FAMILY_DESKTOP_APP')