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.

1042 lines
35KB

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