msvc.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. opt.add_option('--msvc_version', type='string', help = 'msvc version, eg: "msvc 10.0,msvc 9.0"', default='')
  81. opt.add_option('--msvc_targets', type='string', help = 'msvc targets, eg: "x64,arm"', default='')
  82. opt.add_option('--no-msvc-lazy', action='store_false', help = 'lazily check msvc target environments', default=True, dest='msvc_lazy')
  83. @conf
  84. def setup_msvc(conf, versiondict):
  85. """
  86. Checks installed compilers and targets and returns the first combination from the user's
  87. options, env, or the global supported lists that checks.
  88. :param versiondict: dict(platform -> dict(architecture -> configuration))
  89. :type versiondict: dict(string -> dict(string -> target_compiler)
  90. :return: the compiler, revision, path, include dirs, library paths and target architecture
  91. :rtype: tuple of strings
  92. """
  93. platforms = getattr(Options.options, 'msvc_targets', '').split(',')
  94. if platforms == ['']:
  95. platforms=Utils.to_list(conf.env.MSVC_TARGETS) or [i for i,j in all_msvc_platforms+all_icl_platforms+all_wince_platforms]
  96. desired_versions = getattr(Options.options, 'msvc_version', '').split(',')
  97. if desired_versions == ['']:
  98. desired_versions = conf.env.MSVC_VERSIONS or list(reversed(sorted(versiondict.keys())))
  99. # Override lazy detection by evaluating after the fact.
  100. lazy_detect = getattr(Options.options, 'msvc_lazy', True)
  101. if conf.env.MSVC_LAZY_AUTODETECT is False:
  102. lazy_detect = False
  103. if not lazy_detect:
  104. for val in versiondict.values():
  105. for arch in list(val.keys()):
  106. cfg = val[arch]
  107. cfg.evaluate()
  108. if not cfg.is_valid:
  109. del val[arch]
  110. conf.env.MSVC_INSTALLED_VERSIONS = versiondict
  111. for version in desired_versions:
  112. Logs.debug('msvc: detecting %r - %r', version, desired_versions)
  113. try:
  114. targets = versiondict[version]
  115. except KeyError:
  116. continue
  117. seen = set()
  118. for arch in platforms:
  119. if arch in seen:
  120. continue
  121. else:
  122. seen.add(arch)
  123. try:
  124. cfg = targets[arch]
  125. except KeyError:
  126. continue
  127. cfg.evaluate()
  128. if cfg.is_valid:
  129. compiler,revision = version.rsplit(' ', 1)
  130. return compiler,revision,cfg.bindirs,cfg.incdirs,cfg.libdirs,cfg.cpu
  131. conf.fatal('msvc: Impossible to find a valid architecture for building %r - %r' % (desired_versions, list(versiondict.keys())))
  132. @conf
  133. def get_msvc_version(conf, compiler, version, target, vcvars):
  134. """
  135. Checks that an installed compiler actually runs and uses vcvars to obtain the
  136. environment needed by the compiler.
  137. :param compiler: compiler type, for looking up the executable name
  138. :param version: compiler version, for debugging only
  139. :param target: target architecture
  140. :param vcvars: batch file to run to check the environment
  141. :return: the location of the compiler executable, the location of include dirs, and the library paths
  142. :rtype: tuple of strings
  143. """
  144. Logs.debug('msvc: get_msvc_version: %r %r %r', compiler, version, target)
  145. try:
  146. conf.msvc_cnt += 1
  147. except AttributeError:
  148. conf.msvc_cnt = 1
  149. batfile = conf.bldnode.make_node('waf-print-msvc-%d.bat' % conf.msvc_cnt)
  150. batfile.write("""@echo off
  151. set INCLUDE=
  152. set LIB=
  153. call "%s" %s
  154. echo PATH=%%PATH%%
  155. echo INCLUDE=%%INCLUDE%%
  156. echo LIB=%%LIB%%;%%LIBPATH%%
  157. """ % (vcvars,target))
  158. sout = conf.cmd_and_log(['cmd.exe', '/E:on', '/V:on', '/C', batfile.abspath()])
  159. lines = sout.splitlines()
  160. if not lines[0]:
  161. lines.pop(0)
  162. MSVC_PATH = MSVC_INCDIR = MSVC_LIBDIR = None
  163. for line in lines:
  164. if line.startswith('PATH='):
  165. path = line[5:]
  166. MSVC_PATH = path.split(';')
  167. elif line.startswith('INCLUDE='):
  168. MSVC_INCDIR = [i for i in line[8:].split(';') if i]
  169. elif line.startswith('LIB='):
  170. MSVC_LIBDIR = [i for i in line[4:].split(';') if i]
  171. if None in (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR):
  172. conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_3)')
  173. # Check if the compiler is usable at all.
  174. # The detection may return 64-bit versions even on 32-bit systems, and these would fail to run.
  175. env = dict(os.environ)
  176. env.update(PATH = path)
  177. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  178. cxx = conf.find_program(compiler_name, path_list=MSVC_PATH)
  179. # delete CL if exists. because it could contain parameters which can change cl's behaviour rather catastrophically.
  180. if 'CL' in env:
  181. del(env['CL'])
  182. try:
  183. conf.cmd_and_log(cxx + ['/help'], env=env)
  184. except UnicodeError:
  185. st = traceback.format_exc()
  186. if conf.logger:
  187. conf.logger.error(st)
  188. conf.fatal('msvc: Unicode error - check the code page?')
  189. except Exception as e:
  190. Logs.debug('msvc: get_msvc_version: %r %r %r -> failure %s', compiler, version, target, str(e))
  191. conf.fatal('msvc: cannot run the compiler in get_msvc_version (run with -v to display errors)')
  192. else:
  193. Logs.debug('msvc: get_msvc_version: %r %r %r -> OK', compiler, version, target)
  194. finally:
  195. conf.env[compiler_name] = ''
  196. return (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR)
  197. def gather_wince_supported_platforms():
  198. """
  199. Checks SmartPhones SDKs
  200. :param versions: list to modify
  201. :type versions: list
  202. """
  203. supported_wince_platforms = []
  204. try:
  205. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Windows CE Tools\\SDKs')
  206. except OSError:
  207. try:
  208. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows CE Tools\\SDKs')
  209. except OSError:
  210. ce_sdk = ''
  211. if not ce_sdk:
  212. return supported_wince_platforms
  213. index = 0
  214. while 1:
  215. try:
  216. sdk_device = Utils.winreg.EnumKey(ce_sdk, index)
  217. sdk = Utils.winreg.OpenKey(ce_sdk, sdk_device)
  218. except OSError:
  219. break
  220. index += 1
  221. try:
  222. path,type = Utils.winreg.QueryValueEx(sdk, 'SDKRootDir')
  223. except OSError:
  224. try:
  225. path,type = Utils.winreg.QueryValueEx(sdk,'SDKInformation')
  226. except OSError:
  227. continue
  228. path,xml = os.path.split(path)
  229. path = str(path)
  230. path,device = os.path.split(path)
  231. if not device:
  232. path,device = os.path.split(path)
  233. platforms = []
  234. for arch,compiler in all_wince_platforms:
  235. if os.path.isdir(os.path.join(path, device, 'Lib', arch)):
  236. platforms.append((arch, compiler, os.path.join(path, device, 'Include', arch), os.path.join(path, device, 'Lib', arch)))
  237. if platforms:
  238. supported_wince_platforms.append((device, platforms))
  239. return supported_wince_platforms
  240. def gather_msvc_detected_versions():
  241. #Detected MSVC versions!
  242. version_pattern = re.compile('^(\d\d?\.\d\d?)(Exp)?$')
  243. detected_versions = []
  244. for vcver,vcvar in (('VCExpress','Exp'), ('VisualStudio','')):
  245. prefix = 'SOFTWARE\\Wow6432node\\Microsoft\\' + vcver
  246. try:
  247. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  248. except OSError:
  249. prefix = 'SOFTWARE\\Microsoft\\' + vcver
  250. try:
  251. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  252. except OSError:
  253. continue
  254. index = 0
  255. while 1:
  256. try:
  257. version = Utils.winreg.EnumKey(all_versions, index)
  258. except OSError:
  259. break
  260. index += 1
  261. match = version_pattern.match(version)
  262. if match:
  263. versionnumber = float(match.group(1))
  264. else:
  265. continue
  266. detected_versions.append((versionnumber, version+vcvar, prefix+'\\'+version))
  267. def fun(tup):
  268. return tup[0]
  269. detected_versions.sort(key = fun)
  270. return detected_versions
  271. class target_compiler(object):
  272. """
  273. Wrap a compiler configuration; call evaluate() to determine
  274. whether the configuration is usable.
  275. """
  276. def __init__(self, ctx, compiler, cpu, version, bat_target, bat, callback=None):
  277. """
  278. :param ctx: configuration context to use to eventually get the version environment
  279. :param compiler: compiler name
  280. :param cpu: target cpu
  281. :param version: compiler version number
  282. :param bat_target: ?
  283. :param bat: path to the batch file to run
  284. """
  285. self.conf = ctx
  286. self.name = None
  287. self.is_valid = False
  288. self.is_done = False
  289. self.compiler = compiler
  290. self.cpu = cpu
  291. self.version = version
  292. self.bat_target = bat_target
  293. self.bat = bat
  294. self.callback = callback
  295. def evaluate(self):
  296. if self.is_done:
  297. return
  298. self.is_done = True
  299. try:
  300. vs = self.conf.get_msvc_version(self.compiler, self.version, self.bat_target, self.bat)
  301. except Errors.ConfigurationError:
  302. self.is_valid = False
  303. return
  304. if self.callback:
  305. vs = self.callback(self, vs)
  306. self.is_valid = True
  307. (self.bindirs, self.incdirs, self.libdirs) = vs
  308. def __str__(self):
  309. return str((self.compiler, self.cpu, self.version, self.bat_target, self.bat))
  310. def __repr__(self):
  311. return repr((self.compiler, self.cpu, self.version, self.bat_target, self.bat))
  312. @conf
  313. def gather_wsdk_versions(conf, versions):
  314. """
  315. Use winreg to add the msvc versions to the input list
  316. :param versions: list to modify
  317. :type versions: list
  318. """
  319. version_pattern = re.compile('^v..?.?\...?.?')
  320. try:
  321. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Microsoft SDKs\\Windows')
  322. except OSError:
  323. try:
  324. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows')
  325. except OSError:
  326. return
  327. index = 0
  328. while 1:
  329. try:
  330. version = Utils.winreg.EnumKey(all_versions, index)
  331. except OSError:
  332. break
  333. index += 1
  334. if not version_pattern.match(version):
  335. continue
  336. try:
  337. msvc_version = Utils.winreg.OpenKey(all_versions, version)
  338. path,type = Utils.winreg.QueryValueEx(msvc_version,'InstallationFolder')
  339. except OSError:
  340. continue
  341. if path and os.path.isfile(os.path.join(path, 'bin', 'SetEnv.cmd')):
  342. targets = {}
  343. for target,arch in all_msvc_platforms:
  344. targets[target] = target_compiler(conf, 'wsdk', arch, version, '/'+target, os.path.join(path, 'bin', 'SetEnv.cmd'))
  345. versions['wsdk ' + version[1:]] = targets
  346. @conf
  347. def gather_msvc_targets(conf, versions, version, vc_path):
  348. #Looking for normal MSVC compilers!
  349. targets = {}
  350. if os.path.isfile(os.path.join(vc_path, 'VC', 'Auxiliary', 'Build', 'vcvarsall.bat')):
  351. for target,realtarget in all_msvc_platforms[::-1]:
  352. targets[target] = target_compiler(conf, 'msvc', realtarget, version, target, os.path.join(vc_path, 'VC', 'Auxiliary', 'Build', 'vcvarsall.bat'))
  353. elif os.path.isfile(os.path.join(vc_path, 'vcvarsall.bat')):
  354. for target,realtarget in all_msvc_platforms[::-1]:
  355. targets[target] = target_compiler(conf, 'msvc', realtarget, version, target, os.path.join(vc_path, 'vcvarsall.bat'))
  356. elif os.path.isfile(os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')):
  357. targets['x86'] = target_compiler(conf, 'msvc', 'x86', version, 'x86', os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat'))
  358. elif os.path.isfile(os.path.join(vc_path, 'Bin', 'vcvars32.bat')):
  359. targets['x86'] = target_compiler(conf, 'msvc', 'x86', version, '', os.path.join(vc_path, 'Bin', 'vcvars32.bat'))
  360. if targets:
  361. versions['msvc %s' % 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. targets = {}
  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(obj, compiler_env):
  376. # TODO this is likely broken, remove in waf 2.1
  377. (common_bindirs,_1,_2) = compiler_env
  378. return (bindirs + common_bindirs, incdirs, libdirs)
  379. targets[platform] = target_compiler(conf, 'msvc', platform, version, 'x86', vsvars, combine_common)
  380. if targets:
  381. versions[device + ' ' + version] = targets
  382. @conf
  383. def gather_winphone_targets(conf, versions, version, vc_path, vsvars):
  384. #Looking for WinPhone compilers
  385. targets = {}
  386. for target,realtarget in all_msvc_platforms[::-1]:
  387. targets[target] = target_compiler(conf, 'winphone', realtarget, version, target, vsvars)
  388. if targets:
  389. versions['winphone ' + version] = targets
  390. @conf
  391. def gather_vswhere_versions(conf, versions):
  392. try:
  393. import json
  394. except ImportError:
  395. Logs.error('Visual Studio 2017 detection requires Python 2.6')
  396. return
  397. prg_path = os.environ.get('ProgramFiles(x86)', os.environ.get('ProgramFiles', 'C:\\Program Files (x86)'))
  398. vswhere = os.path.join(prg_path, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe')
  399. args = [vswhere, '-products', '*', '-legacy', '-format', 'json']
  400. try:
  401. txt = conf.cmd_and_log(args)
  402. except Errors.WafError as e:
  403. Logs.debug('msvc: vswhere.exe failed %s', e)
  404. return
  405. if sys.version_info[0] < 3:
  406. txt = txt.decode(Utils.console_encoding())
  407. arr = json.loads(txt)
  408. arr.sort(key=lambda x: x['installationVersion'])
  409. for entry in arr:
  410. ver = entry['installationVersion']
  411. ver = str('.'.join(ver.split('.')[:2]))
  412. path = str(os.path.abspath(entry['installationPath']))
  413. if os.path.exists(path) and ('msvc %s' % ver) not in versions:
  414. conf.gather_msvc_targets(versions, ver, path)
  415. @conf
  416. def gather_msvc_versions(conf, versions):
  417. vc_paths = []
  418. for (v,version,reg) in gather_msvc_detected_versions():
  419. try:
  420. try:
  421. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\VC")
  422. except OSError:
  423. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\Microsoft Visual C++")
  424. path,type = Utils.winreg.QueryValueEx(msvc_version, 'ProductDir')
  425. except OSError:
  426. try:
  427. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Wow6432node\\Microsoft\\VisualStudio\\SxS\\VS7")
  428. path,type = Utils.winreg.QueryValueEx(msvc_version, version)
  429. except OSError:
  430. continue
  431. else:
  432. vc_paths.append((version, os.path.abspath(str(path))))
  433. continue
  434. else:
  435. vc_paths.append((version, os.path.abspath(str(path))))
  436. wince_supported_platforms = gather_wince_supported_platforms()
  437. for version,vc_path in vc_paths:
  438. vs_path = os.path.dirname(vc_path)
  439. vsvars = os.path.join(vs_path, 'Common7', 'Tools', 'vsvars32.bat')
  440. if wince_supported_platforms and os.path.isfile(vsvars):
  441. conf.gather_wince_targets(versions, version, vc_path, vsvars, wince_supported_platforms)
  442. # WP80 works with 11.0Exp and 11.0, both of which resolve to the same vc_path.
  443. # Stop after one is found.
  444. for version,vc_path in vc_paths:
  445. vs_path = os.path.dirname(vc_path)
  446. vsvars = os.path.join(vs_path, 'VC', 'WPSDK', 'WP80', 'vcvarsphoneall.bat')
  447. if os.path.isfile(vsvars):
  448. conf.gather_winphone_targets(versions, '8.0', vc_path, vsvars)
  449. break
  450. for version,vc_path in vc_paths:
  451. vs_path = os.path.dirname(vc_path)
  452. conf.gather_msvc_targets(versions, version, vc_path)
  453. @conf
  454. def gather_icl_versions(conf, versions):
  455. """
  456. Checks ICL compilers
  457. :param versions: list to modify
  458. :type versions: list
  459. """
  460. version_pattern = re.compile('^...?.?\....?.?')
  461. try:
  462. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Compilers\\C++')
  463. except OSError:
  464. try:
  465. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Compilers\\C++')
  466. except OSError:
  467. return
  468. index = 0
  469. while 1:
  470. try:
  471. version = Utils.winreg.EnumKey(all_versions, index)
  472. except OSError:
  473. break
  474. index += 1
  475. if not version_pattern.match(version):
  476. continue
  477. targets = {}
  478. for target,arch in all_icl_platforms:
  479. if target=='intel64':
  480. targetDir='EM64T_NATIVE'
  481. else:
  482. targetDir=target
  483. try:
  484. Utils.winreg.OpenKey(all_versions,version+'\\'+targetDir)
  485. icl_version=Utils.winreg.OpenKey(all_versions,version)
  486. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  487. except OSError:
  488. pass
  489. else:
  490. batch_file=os.path.join(path,'bin','iclvars.bat')
  491. if os.path.isfile(batch_file):
  492. targets[target] = target_compiler(conf, 'intel', arch, version, target, batch_file)
  493. for target,arch in all_icl_platforms:
  494. try:
  495. icl_version = Utils.winreg.OpenKey(all_versions, version+'\\'+target)
  496. path,type = Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  497. except OSError:
  498. continue
  499. else:
  500. batch_file=os.path.join(path,'bin','iclvars.bat')
  501. if os.path.isfile(batch_file):
  502. targets[target] = target_compiler(conf, 'intel', arch, version, target, batch_file)
  503. major = version[0:2]
  504. versions['intel ' + major] = targets
  505. @conf
  506. def gather_intel_composer_versions(conf, versions):
  507. """
  508. Checks ICL compilers that are part of Intel Composer Suites
  509. :param versions: list to modify
  510. :type versions: list
  511. """
  512. version_pattern = re.compile('^...?.?\...?.?.?')
  513. try:
  514. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Suites')
  515. except OSError:
  516. try:
  517. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Suites')
  518. except OSError:
  519. return
  520. index = 0
  521. while 1:
  522. try:
  523. version = Utils.winreg.EnumKey(all_versions, index)
  524. except OSError:
  525. break
  526. index += 1
  527. if not version_pattern.match(version):
  528. continue
  529. targets = {}
  530. for target,arch in all_icl_platforms:
  531. if target=='intel64':
  532. targetDir='EM64T_NATIVE'
  533. else:
  534. targetDir=target
  535. try:
  536. try:
  537. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\'+targetDir)
  538. except OSError:
  539. if targetDir == 'EM64T_NATIVE':
  540. defaults = Utils.winreg.OpenKey(all_versions,version+'\\Defaults\\C++\\EM64T')
  541. else:
  542. raise
  543. uid,type = Utils.winreg.QueryValueEx(defaults, 'SubKey')
  544. Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++\\'+targetDir)
  545. icl_version=Utils.winreg.OpenKey(all_versions,version+'\\'+uid+'\\C++')
  546. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  547. except OSError:
  548. pass
  549. else:
  550. batch_file=os.path.join(path,'bin','iclvars.bat')
  551. if os.path.isfile(batch_file):
  552. targets[target] = target_compiler(conf, 'intel', arch, version, target, batch_file)
  553. # The intel compilervar_arch.bat is broken when used with Visual Studio Express 2012
  554. # http://software.intel.com/en-us/forums/topic/328487
  555. compilervars_warning_attr = '_compilervars_warning_key'
  556. if version[0:2] == '13' and getattr(conf, compilervars_warning_attr, True):
  557. setattr(conf, compilervars_warning_attr, False)
  558. patch_url = 'http://software.intel.com/en-us/forums/topic/328487'
  559. compilervars_arch = os.path.join(path, 'bin', 'compilervars_arch.bat')
  560. for vscomntool in ('VS110COMNTOOLS', 'VS100COMNTOOLS'):
  561. if vscomntool in os.environ:
  562. vs_express_path = os.environ[vscomntool] + r'..\IDE\VSWinExpress.exe'
  563. dev_env_path = os.environ[vscomntool] + r'..\IDE\devenv.exe'
  564. if (r'if exist "%VS110COMNTOOLS%..\IDE\VSWinExpress.exe"' in Utils.readf(compilervars_arch) and
  565. not os.path.exists(vs_express_path) and not os.path.exists(dev_env_path)):
  566. Logs.warn(('The Intel compilervar_arch.bat only checks for one Visual Studio SKU '
  567. '(VSWinExpress.exe) but it does not seem to be installed at %r. '
  568. 'The intel command line set up will fail to configure unless the file %r'
  569. 'is patched. See: %s') % (vs_express_path, compilervars_arch, patch_url))
  570. major = version[0:2]
  571. versions['intel ' + major] = targets
  572. @conf
  573. def detect_msvc(self):
  574. return self.setup_msvc(self.get_msvc_versions())
  575. @conf
  576. def get_msvc_versions(self):
  577. """
  578. :return: platform to compiler configurations
  579. :rtype: dict
  580. """
  581. dct = Utils.ordered_iter_dict()
  582. self.gather_icl_versions(dct)
  583. self.gather_intel_composer_versions(dct)
  584. self.gather_wsdk_versions(dct)
  585. self.gather_msvc_versions(dct)
  586. self.gather_vswhere_versions(dct)
  587. Logs.debug('msvc: detected versions %r', list(dct.keys()))
  588. return dct
  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. Returns a triplet:
  594. (library absolute path, library name without extension, whether the library is static)
  595. """
  596. lt_names=[
  597. 'lib%s.la' % libname,
  598. '%s.la' % libname,
  599. ]
  600. for path in self.env.LIBPATH:
  601. for la in lt_names:
  602. laf=os.path.join(path,la)
  603. dll=None
  604. if os.path.exists(laf):
  605. ltdict = Utils.read_la_file(laf)
  606. lt_libdir=None
  607. if ltdict.get('libdir', ''):
  608. lt_libdir = ltdict['libdir']
  609. if not is_static and ltdict.get('library_names', ''):
  610. dllnames=ltdict['library_names'].split()
  611. dll=dllnames[0].lower()
  612. dll=re.sub('\.dll$', '', dll)
  613. return (lt_libdir, dll, False)
  614. elif ltdict.get('old_library', ''):
  615. olib=ltdict['old_library']
  616. if os.path.exists(os.path.join(path,olib)):
  617. return (path, olib, True)
  618. elif lt_libdir != '' and os.path.exists(os.path.join(lt_libdir,olib)):
  619. return (lt_libdir, olib, True)
  620. else:
  621. return (None, olib, True)
  622. else:
  623. raise self.errors.WafError('invalid libtool object file: %s' % laf)
  624. return (None, None, None)
  625. @conf
  626. def libname_msvc(self, libname, is_static=False):
  627. lib = libname.lower()
  628. lib = re.sub('\.lib$','',lib)
  629. if lib in g_msvc_systemlibs:
  630. return lib
  631. lib=re.sub('^lib','',lib)
  632. if lib == 'm':
  633. return None
  634. (lt_path, lt_libname, lt_static) = self.find_lt_names_msvc(lib, is_static)
  635. if lt_path != None and lt_libname != None:
  636. if lt_static:
  637. # file existence check has been made by find_lt_names
  638. return os.path.join(lt_path,lt_libname)
  639. if lt_path != None:
  640. _libpaths = [lt_path] + self.env.LIBPATH
  641. else:
  642. _libpaths = self.env.LIBPATH
  643. static_libs=[
  644. 'lib%ss.lib' % lib,
  645. 'lib%s.lib' % lib,
  646. '%ss.lib' % lib,
  647. '%s.lib' %lib,
  648. ]
  649. dynamic_libs=[
  650. 'lib%s.dll.lib' % lib,
  651. 'lib%s.dll.a' % lib,
  652. '%s.dll.lib' % lib,
  653. '%s.dll.a' % lib,
  654. 'lib%s_d.lib' % lib,
  655. '%s_d.lib' % lib,
  656. '%s.lib' %lib,
  657. ]
  658. libnames=static_libs
  659. if not is_static:
  660. libnames=dynamic_libs + static_libs
  661. for path in _libpaths:
  662. for libn in libnames:
  663. if os.path.exists(os.path.join(path, libn)):
  664. Logs.debug('msvc: lib found: %s', os.path.join(path,libn))
  665. return re.sub('\.lib$', '',libn)
  666. #if no lib can be found, just return the libname as msvc expects it
  667. self.fatal('The library %r could not be found' % libname)
  668. return re.sub('\.lib$', '', libname)
  669. @conf
  670. def check_lib_msvc(self, libname, is_static=False, uselib_store=None):
  671. """
  672. Ideally we should be able to place the lib in the right env var, either STLIB or LIB,
  673. but we don't distinguish static libs from shared libs.
  674. This is ok since msvc doesn't have any special linker flag to select static libs (no env.STLIB_MARKER)
  675. """
  676. libn = self.libname_msvc(libname, is_static)
  677. if not uselib_store:
  678. uselib_store = libname.upper()
  679. if False and is_static: # disabled
  680. self.env['STLIB_' + uselib_store] = [libn]
  681. else:
  682. self.env['LIB_' + uselib_store] = [libn]
  683. @conf
  684. def check_libs_msvc(self, libnames, is_static=False):
  685. for libname in Utils.to_list(libnames):
  686. self.check_lib_msvc(libname, is_static)
  687. def configure(conf):
  688. """
  689. Configuration methods to call for detecting msvc
  690. """
  691. conf.autodetect(True)
  692. conf.find_msvc()
  693. conf.msvc_common_flags()
  694. conf.cc_load_tools()
  695. conf.cxx_load_tools()
  696. conf.cc_add_flags()
  697. conf.cxx_add_flags()
  698. conf.link_add_flags()
  699. conf.visual_studio_add_flags()
  700. @conf
  701. def no_autodetect(conf):
  702. conf.env.NO_MSVC_DETECT = 1
  703. configure(conf)
  704. @conf
  705. def autodetect(conf, arch=False):
  706. v = conf.env
  707. if v.NO_MSVC_DETECT:
  708. return
  709. compiler, version, path, includes, libdirs, cpu = conf.detect_msvc()
  710. if arch:
  711. v.DEST_CPU = cpu
  712. v.PATH = path
  713. v.INCLUDES = includes
  714. v.LIBPATH = libdirs
  715. v.MSVC_COMPILER = compiler
  716. try:
  717. v.MSVC_VERSION = float(version)
  718. except ValueError:
  719. v.MSVC_VERSION = float(version[:-3])
  720. def _get_prog_names(conf, compiler):
  721. if compiler == 'intel':
  722. compiler_name = 'ICL'
  723. linker_name = 'XILINK'
  724. lib_name = 'XILIB'
  725. else:
  726. # assumes CL.exe
  727. compiler_name = 'CL'
  728. linker_name = 'LINK'
  729. lib_name = 'LIB'
  730. return compiler_name, linker_name, lib_name
  731. @conf
  732. def find_msvc(conf):
  733. """Due to path format limitations, limit operation only to native Win32. Yeah it sucks."""
  734. if sys.platform == 'cygwin':
  735. conf.fatal('MSVC module does not work under cygwin Python!')
  736. # the autodetection is supposed to be performed before entering in this method
  737. v = conf.env
  738. path = v.PATH
  739. compiler = v.MSVC_COMPILER
  740. version = v.MSVC_VERSION
  741. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  742. v.MSVC_MANIFEST = (compiler == 'msvc' and version >= 8) or (compiler == 'wsdk' and version >= 6) or (compiler == 'intel' and version >= 11)
  743. # compiler
  744. cxx = conf.find_program(compiler_name, var='CXX', path_list=path)
  745. # before setting anything, check if the compiler is really msvc
  746. env = dict(conf.environ)
  747. if path:
  748. env.update(PATH = ';'.join(path))
  749. if not conf.cmd_and_log(cxx + ['/nologo', '/help'], env=env):
  750. conf.fatal('the msvc compiler could not be identified')
  751. # c/c++ compiler
  752. v.CC = v.CXX = cxx
  753. v.CC_NAME = v.CXX_NAME = 'msvc'
  754. # linker
  755. if not v.LINK_CXX:
  756. conf.find_program(linker_name, path_list=path, errmsg='%s was not found (linker)' % linker_name, var='LINK_CXX')
  757. if not v.LINK_CC:
  758. v.LINK_CC = v.LINK_CXX
  759. # staticlib linker
  760. if not v.AR:
  761. stliblink = conf.find_program(lib_name, path_list=path, var='AR')
  762. if not stliblink:
  763. return
  764. v.ARFLAGS = ['/nologo']
  765. # manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later
  766. if v.MSVC_MANIFEST:
  767. conf.find_program('MT', path_list=path, var='MT')
  768. v.MTFLAGS = ['/nologo']
  769. try:
  770. conf.load('winres')
  771. except Errors.ConfigurationError:
  772. Logs.warn('Resource compiler not found. Compiling resource file is disabled')
  773. @conf
  774. def visual_studio_add_flags(self):
  775. """visual studio flags found in the system environment"""
  776. v = self.env
  777. if self.environ.get('INCLUDE'):
  778. v.prepend_value('INCLUDES', [x for x in self.environ['INCLUDE'].split(';') if x]) # notice the 'S'
  779. if self.environ.get('LIB'):
  780. v.prepend_value('LIBPATH', [x for x in self.environ['LIB'].split(';') if x])
  781. @conf
  782. def msvc_common_flags(conf):
  783. """
  784. Setup the flags required for executing the msvc compiler
  785. """
  786. v = conf.env
  787. v.DEST_BINFMT = 'pe'
  788. v.append_value('CFLAGS', ['/nologo'])
  789. v.append_value('CXXFLAGS', ['/nologo'])
  790. v.append_value('LINKFLAGS', ['/nologo'])
  791. v.DEFINES_ST = '/D%s'
  792. v.CC_SRC_F = ''
  793. v.CC_TGT_F = ['/c', '/Fo']
  794. v.CXX_SRC_F = ''
  795. v.CXX_TGT_F = ['/c', '/Fo']
  796. if (v.MSVC_COMPILER == 'msvc' and v.MSVC_VERSION >= 8) or (v.MSVC_COMPILER == 'wsdk' and v.MSVC_VERSION >= 6):
  797. v.CC_TGT_F = ['/FC'] + v.CC_TGT_F
  798. v.CXX_TGT_F = ['/FC'] + v.CXX_TGT_F
  799. v.CPPPATH_ST = '/I%s' # template for adding include paths
  800. v.AR_TGT_F = v.CCLNK_TGT_F = v.CXXLNK_TGT_F = '/OUT:'
  801. # CRT specific flags
  802. v.CFLAGS_CRT_MULTITHREADED = v.CXXFLAGS_CRT_MULTITHREADED = ['/MT']
  803. v.CFLAGS_CRT_MULTITHREADED_DLL = v.CXXFLAGS_CRT_MULTITHREADED_DLL = ['/MD']
  804. v.CFLAGS_CRT_MULTITHREADED_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DBG = ['/MTd']
  805. v.CFLAGS_CRT_MULTITHREADED_DLL_DBG = v.CXXFLAGS_CRT_MULTITHREADED_DLL_DBG = ['/MDd']
  806. v.LIB_ST = '%s.lib'
  807. v.LIBPATH_ST = '/LIBPATH:%s'
  808. v.STLIB_ST = '%s.lib'
  809. v.STLIBPATH_ST = '/LIBPATH:%s'
  810. if v.MSVC_MANIFEST:
  811. v.append_value('LINKFLAGS', ['/MANIFEST'])
  812. v.CFLAGS_cshlib = []
  813. v.CXXFLAGS_cxxshlib = []
  814. v.LINKFLAGS_cshlib = v.LINKFLAGS_cxxshlib = ['/DLL']
  815. v.cshlib_PATTERN = v.cxxshlib_PATTERN = '%s.dll'
  816. v.implib_PATTERN = '%s.lib'
  817. v.IMPLIB_ST = '/IMPLIB:%s'
  818. v.LINKFLAGS_cstlib = []
  819. v.cstlib_PATTERN = v.cxxstlib_PATTERN = '%s.lib'
  820. v.cprogram_PATTERN = v.cxxprogram_PATTERN = '%s.exe'
  821. v.def_PATTERN = '/def:%s'
  822. #######################################################################################################
  823. ##### conf above, build below
  824. @after_method('apply_link')
  825. @feature('c', 'cxx')
  826. def apply_flags_msvc(self):
  827. """
  828. Add additional flags implied by msvc, such as subsystems and pdb files::
  829. def build(bld):
  830. bld.stlib(source='main.c', target='bar', subsystem='gruik')
  831. """
  832. if self.env.CC_NAME != 'msvc' or not getattr(self, 'link_task', None):
  833. return
  834. is_static = isinstance(self.link_task, ccroot.stlink_task)
  835. subsystem = getattr(self, 'subsystem', '')
  836. if subsystem:
  837. subsystem = '/subsystem:%s' % subsystem
  838. flags = is_static and 'ARFLAGS' or 'LINKFLAGS'
  839. self.env.append_value(flags, subsystem)
  840. if not is_static:
  841. for f in self.env.LINKFLAGS:
  842. d = f.lower()
  843. if d[1:] == 'debug':
  844. pdbnode = self.link_task.outputs[0].change_ext('.pdb')
  845. self.link_task.outputs.append(pdbnode)
  846. if getattr(self, 'install_task', None):
  847. self.pdb_install_task = self.add_install_files(
  848. install_to=self.install_task.install_to, install_from=pdbnode)
  849. break
  850. @feature('cprogram', 'cshlib', 'cxxprogram', 'cxxshlib')
  851. @after_method('apply_link')
  852. def apply_manifest(self):
  853. """
  854. Special linker for MSVC with support for embedding manifests into DLL's
  855. and executables compiled by Visual Studio 2005 or probably later. Without
  856. the manifest file, the binaries are unusable.
  857. See: http://msdn2.microsoft.com/en-us/library/ms235542(VS.80).aspx
  858. """
  859. if self.env.CC_NAME == 'msvc' and self.env.MSVC_MANIFEST and getattr(self, 'link_task', None):
  860. out_node = self.link_task.outputs[0]
  861. man_node = out_node.parent.find_or_declare(out_node.name + '.manifest')
  862. self.link_task.outputs.append(man_node)
  863. self.env.DO_MANIFEST = True
  864. def make_winapp(self, family):
  865. append = self.env.append_unique
  866. append('DEFINES', 'WINAPI_FAMILY=%s' % family)
  867. append('CXXFLAGS', ['/ZW', '/TP'])
  868. for lib_path in self.env.LIBPATH:
  869. append('CXXFLAGS','/AI%s'%lib_path)
  870. @feature('winphoneapp')
  871. @after_method('process_use')
  872. @after_method('propagate_uselib_vars')
  873. def make_winphone_app(self):
  874. """
  875. Insert configuration flags for windows phone applications (adds /ZW, /TP...)
  876. """
  877. make_winapp(self, 'WINAPI_FAMILY_PHONE_APP')
  878. self.env.append_unique('LINKFLAGS', ['/NODEFAULTLIB:ole32.lib', 'PhoneAppModelHost.lib'])
  879. @feature('winapp')
  880. @after_method('process_use')
  881. @after_method('propagate_uselib_vars')
  882. def make_windows_app(self):
  883. """
  884. Insert configuration flags for windows applications (adds /ZW, /TP...)
  885. """
  886. make_winapp(self, 'WINAPI_FAMILY_DESKTOP_APP')