PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/waflib/Tools/msvc.py

https://bitbucket.org/kartoch/netkython
Python | 936 lines | 909 code | 6 blank | 21 comment | 23 complexity | 111add73600b01d98724ce3897207aec MD5 | raw file
  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. """
  7. Microsoft Visual C++/Intel C++ compiler support
  8. Usage::
  9. $ waf configure --msvc_version="msvc 10.0,msvc 9.0" --msvc_target="x64"
  10. or::
  11. def configure(conf):
  12. 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']
  13. conf.env['MSVC_TARGETS'] = ['x64']
  14. conf.load('msvc')
  15. or::
  16. def configure(conf):
  17. conf.load('msvc', funs='no_autodetect')
  18. conf.check_lib_msvc('gdi32')
  19. conf.check_libs_msvc('kernel32 user32')
  20. def build(bld):
  21. tg = bld.program(source='main.c', target='app', use='KERNEL32 USER32 GDI32')
  22. Platforms and targets will be tested in the order they appear;
  23. the first good configuration will be used.
  24. Supported platforms: ia64, x64, x86, x86_amd64, x86_ia64
  25. Compilers supported:
  26. * msvc => Visual Studio, versions 6.0 (VC 98, VC .NET 2002) to 10.0 (Visual Studio 2010)
  27. * wsdk => Windows SDK, versions 6.0, 6.1, 7.0
  28. * icl => Intel compiler, versions 9,10,11
  29. * Smartphone => Compiler/SDK for Smartphone devices (armv4/v4i)
  30. * PocketPC => Compiler/SDK for PocketPC devices (armv4/v4i)
  31. To use WAF in a VS2008 Make file project (see http://code.google.com/p/waf/issues/detail?id=894)
  32. You may consider to set the environment variable "VS_UNICODE_OUTPUT" to nothing before calling waf.
  33. So in your project settings use something like 'cmd.exe /C "set VS_UNICODE_OUTPUT=& set PYTHONUNBUFFERED=true & waf build"'.
  34. cmd.exe /C "chcp 1252 & set PYTHONUNBUFFERED=true && set && waf configure"
  35. Setting PYTHONUNBUFFERED gives the unbuffered output.
  36. """
  37. import os, sys, re, tempfile
  38. from waflib import Utils, Task, Logs, Options
  39. from waflib.Logs import debug, warn
  40. from waflib.TaskGen import after_method, feature
  41. from waflib.Configure import conf
  42. from waflib.Tools import ccroot, c, cxx, ar, winres
  43. g_msvc_systemlibs = '''
  44. aclui activeds ad1 adptif adsiid advapi32 asycfilt authz bhsupp bits bufferoverflowu cabinet
  45. cap certadm certidl ciuuid clusapi comctl32 comdlg32 comsupp comsuppd comsuppw comsuppwd comsvcs
  46. credui crypt32 cryptnet cryptui d3d8thk daouuid dbgeng dbghelp dciman32 ddao35 ddao35d
  47. ddao35u ddao35ud delayimp dhcpcsvc dhcpsapi dlcapi dnsapi dsprop dsuiext dtchelp
  48. faultrep fcachdll fci fdi framedyd framedyn gdi32 gdiplus glauxglu32 gpedit gpmuuid
  49. gtrts32w gtrtst32hlink htmlhelp httpapi icm32 icmui imagehlp imm32 iphlpapi iprop
  50. kernel32 ksguid ksproxy ksuser libcmt libcmtd libcpmt libcpmtd loadperf lz32 mapi
  51. mapi32 mgmtapi minidump mmc mobsync mpr mprapi mqoa mqrt msacm32 mscms mscoree
  52. msdasc msimg32 msrating mstask msvcmrt msvcurt msvcurtd mswsock msxml2 mtx mtxdm
  53. netapi32 nmapinmsupp npptools ntdsapi ntdsbcli ntmsapi ntquery odbc32 odbcbcp
  54. odbccp32 oldnames ole32 oleacc oleaut32 oledb oledlgolepro32 opends60 opengl32
  55. osptk parser pdh penter pgobootrun pgort powrprof psapi ptrustm ptrustmd ptrustu
  56. ptrustud qosname rasapi32 rasdlg rassapi resutils riched20 rpcndr rpcns4 rpcrt4 rtm
  57. rtutils runtmchk scarddlg scrnsave scrnsavw secur32 sensapi setupapi sfc shell32
  58. shfolder shlwapi sisbkup snmpapi sporder srclient sti strsafe svcguid tapi32 thunk32
  59. traffic unicows url urlmon user32 userenv usp10 uuid uxtheme vcomp vcompd vdmdbg
  60. version vfw32 wbemuuid webpost wiaguid wininet winmm winscard winspool winstrm
  61. wintrust wldap32 wmiutils wow32 ws2_32 wsnmp32 wsock32 wst wtsapi32 xaswitch xolehlp
  62. '''.split()
  63. """importlibs provided by MSVC/Platform SDK. Do NOT search them"""
  64. all_msvc_platforms = [ ('x64', 'amd64'), ('x86', 'x86'), ('ia64', 'ia64'), ('x86_amd64', 'amd64'), ('x86_ia64', 'ia64') ]
  65. """List of msvc platforms"""
  66. all_wince_platforms = [ ('armv4', 'arm'), ('armv4i', 'arm'), ('mipsii', 'mips'), ('mipsii_fp', 'mips'), ('mipsiv', 'mips'), ('mipsiv_fp', 'mips'), ('sh4', 'sh'), ('x86', 'cex86') ]
  67. """List of wince platforms"""
  68. all_icl_platforms = [ ('intel64', 'amd64'), ('em64t', 'amd64'), ('ia32', 'x86'), ('Itanium', 'ia64')]
  69. """List of icl platforms"""
  70. def options(opt):
  71. opt.add_option('--msvc_version', type='string', help = 'msvc version, eg: "msvc 10.0,msvc 9.0"', default='')
  72. opt.add_option('--msvc_targets', type='string', help = 'msvc targets, eg: "x64,arm"', default='')
  73. def setup_msvc(conf, versions, arch = False):
  74. platforms = getattr(Options.options, 'msvc_targets', '').split(',')
  75. if platforms == ['']:
  76. platforms=Utils.to_list(conf.env['MSVC_TARGETS']) or [i for i,j in all_msvc_platforms+all_icl_platforms+all_wince_platforms]
  77. desired_versions = getattr(Options.options, 'msvc_version', '').split(',')
  78. if desired_versions == ['']:
  79. desired_versions = conf.env['MSVC_VERSIONS'] or [v for v,_ in versions][::-1]
  80. versiondict = dict(versions)
  81. for version in desired_versions:
  82. try:
  83. targets = dict(versiondict [version])
  84. for target in platforms:
  85. try:
  86. arch,(p1,p2,p3) = targets[target]
  87. compiler,revision = version.rsplit(' ', 1)
  88. if arch:
  89. return compiler,revision,p1,p2,p3,arch
  90. else:
  91. return compiler,revision,p1,p2,p3
  92. except KeyError: continue
  93. except KeyError: continue
  94. conf.fatal('msvc: Impossible to find a valid architecture for building (in setup_msvc)')
  95. @conf
  96. def get_msvc_version(conf, compiler, version, target, vcvars):
  97. """
  98. Create a bat file to obtain the location of the libraries
  99. :param compiler: ?
  100. :param version: ?
  101. :target: ?
  102. :vcvars: ?
  103. :return: the location of msvc, the location of include dirs, and the library paths
  104. :rtype: tuple of strings
  105. """
  106. debug('msvc: get_msvc_version: %r %r %r', compiler, version, target)
  107. batfile = conf.bldnode.make_node('waf-print-msvc.bat')
  108. batfile.write("""@echo off
  109. set INCLUDE=
  110. set LIB=
  111. call "%s" %s
  112. echo PATH=%%PATH%%
  113. echo INCLUDE=%%INCLUDE%%
  114. echo LIB=%%LIB%%
  115. """ % (vcvars,target))
  116. sout = conf.cmd_and_log(['cmd', '/E:on', '/V:on', '/C', batfile.abspath()])
  117. lines = sout.splitlines()
  118. if not lines[0]:
  119. lines.pop(0)
  120. if version == '11.0':
  121. if lines[0].startswith('Error'):
  122. conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_1)')
  123. else:
  124. for x in ('Setting environment', 'Setting SDK environment', 'Intel(R) C++ Compiler', 'Intel Parallel Studio'):
  125. if lines[0].find(x) > -1:
  126. lines.pop(0)
  127. break
  128. else:
  129. debug('msvc: get_msvc_version: %r %r %r -> not found', compiler, version, target)
  130. conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_2)')
  131. MSVC_PATH = MSVC_INCDIR = MSVC_LIBDIR = None
  132. for line in lines:
  133. if line.startswith('PATH='):
  134. path = line[5:]
  135. MSVC_PATH = path.split(';')
  136. elif line.startswith('INCLUDE='):
  137. MSVC_INCDIR = [i for i in line[8:].split(';') if i]
  138. elif line.startswith('LIB='):
  139. MSVC_LIBDIR = [i for i in line[4:].split(';') if i]
  140. if None in (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR):
  141. conf.fatal('msvc: Could not find a valid architecture for building (get_msvc_version_3)')
  142. # Check if the compiler is usable at all.
  143. # The detection may return 64-bit versions even on 32-bit systems, and these would fail to run.
  144. env = dict(os.environ)
  145. env.update(PATH = path)
  146. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  147. cxx = conf.find_program(compiler_name, path_list=MSVC_PATH)
  148. cxx = conf.cmd_to_list(cxx)
  149. # delete CL if exists. because it could contain parameters wich can change cl's behaviour rather catastrophically.
  150. if 'CL' in env:
  151. del(env['CL'])
  152. try:
  153. try:
  154. conf.cmd_and_log(cxx + ['/help'], env=env)
  155. except Exception as e:
  156. debug('msvc: get_msvc_version: %r %r %r -> failure' % (compiler, version, target))
  157. debug(str(e))
  158. conf.fatal('msvc: cannot run the compiler (in get_msvc_version)')
  159. else:
  160. debug('msvc: get_msvc_version: %r %r %r -> OK', compiler, version, target)
  161. finally:
  162. conf.env[compiler_name] = ''
  163. return (MSVC_PATH, MSVC_INCDIR, MSVC_LIBDIR)
  164. @conf
  165. def gather_wsdk_versions(conf, versions):
  166. """
  167. Use winreg to add the msvc versions to the input list
  168. :param versions: list to modify
  169. :type versions: list
  170. """
  171. version_pattern = re.compile('^v..?.?\...?.?')
  172. try:
  173. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Microsoft SDKs\\Windows')
  174. except WindowsError:
  175. try:
  176. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows')
  177. except WindowsError:
  178. return
  179. index = 0
  180. while 1:
  181. try:
  182. version = Utils.winreg.EnumKey(all_versions, index)
  183. except WindowsError:
  184. break
  185. index = index + 1
  186. if not version_pattern.match(version):
  187. continue
  188. try:
  189. msvc_version = Utils.winreg.OpenKey(all_versions, version)
  190. path,type = Utils.winreg.QueryValueEx(msvc_version,'InstallationFolder')
  191. except WindowsError:
  192. continue
  193. if os.path.isfile(os.path.join(path, 'bin', 'SetEnv.cmd')):
  194. targets = []
  195. for target,arch in all_msvc_platforms:
  196. try:
  197. targets.append((target, (arch, conf.get_msvc_version('wsdk', version, '/'+target, os.path.join(path, 'bin', 'SetEnv.cmd')))))
  198. except conf.errors.ConfigurationError:
  199. pass
  200. versions.append(('wsdk ' + version[1:], targets))
  201. def gather_wince_supported_platforms():
  202. """
  203. Checks SmartPhones SDKs
  204. :param versions: list to modify
  205. :type versions: list
  206. """
  207. supported_wince_platforms = []
  208. try:
  209. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Windows CE Tools\\SDKs')
  210. except WindowsError:
  211. try:
  212. ce_sdk = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows CE Tools\\SDKs')
  213. except WindowsError:
  214. ce_sdk = ''
  215. if not ce_sdk:
  216. return supported_wince_platforms
  217. ce_index = 0
  218. while 1:
  219. try:
  220. sdk_device = Utils.winreg.EnumKey(ce_sdk, ce_index)
  221. except WindowsError:
  222. break
  223. ce_index = ce_index + 1
  224. sdk = Utils.winreg.OpenKey(ce_sdk, sdk_device)
  225. try:
  226. path,type = Utils.winreg.QueryValueEx(sdk, 'SDKRootDir')
  227. except WindowsError:
  228. try:
  229. path,type = Utils.winreg.QueryValueEx(sdk,'SDKInformation')
  230. path,xml = os.path.split(path)
  231. except WindowsError:
  232. continue
  233. path=str(path)
  234. path,device = os.path.split(path)
  235. if not device:
  236. path,device = os.path.split(path)
  237. for arch,compiler in all_wince_platforms:
  238. platforms = []
  239. if os.path.isdir(os.path.join(path, device, 'Lib', arch)):
  240. platforms.append((arch, compiler, os.path.join(path, device, 'Include', arch), os.path.join(path, device, 'Lib', arch)))
  241. if platforms:
  242. supported_wince_platforms.append((device, platforms))
  243. return supported_wince_platforms
  244. def gather_msvc_detected_versions():
  245. #Detected MSVC versions!
  246. version_pattern = re.compile('^(\d\d?\.\d\d?)(Exp)?$')
  247. detected_versions = []
  248. for vcver,vcvar in [('VCExpress','Exp'), ('VisualStudio','')]:
  249. try:
  250. prefix = 'SOFTWARE\\Wow6432node\\Microsoft\\'+vcver
  251. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  252. except WindowsError:
  253. try:
  254. prefix = 'SOFTWARE\\Microsoft\\'+vcver
  255. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, prefix)
  256. except WindowsError:
  257. continue
  258. index = 0
  259. while 1:
  260. try:
  261. version = Utils.winreg.EnumKey(all_versions, index)
  262. except WindowsError:
  263. break
  264. index = index + 1
  265. match = version_pattern.match(version)
  266. if not match:
  267. continue
  268. else:
  269. versionnumber = float(match.group(1))
  270. detected_versions.append((versionnumber, version+vcvar, prefix+"\\"+version))
  271. def fun(tup):
  272. return tup[0]
  273. detected_versions.sort(key = fun)
  274. return detected_versions
  275. @conf
  276. def gather_msvc_targets(conf, versions, version, vc_path):
  277. #Looking for normal MSVC compilers!
  278. targets = []
  279. if os.path.isfile(os.path.join(vc_path, 'vcvarsall.bat')):
  280. for target,realtarget in all_msvc_platforms[::-1]:
  281. try:
  282. targets.append((target, (realtarget, conf.get_msvc_version('msvc', version, target, os.path.join(vc_path, 'vcvarsall.bat')))))
  283. except conf.errors.ConfigurationError:
  284. pass
  285. elif os.path.isfile(os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')):
  286. try:
  287. targets.append(('x86', ('x86', conf.get_msvc_version('msvc', version, 'x86', os.path.join(vc_path, 'Common7', 'Tools', 'vsvars32.bat')))))
  288. except conf.errors.ConfigurationError:
  289. pass
  290. elif os.path.isfile(os.path.join(vc_path, 'Bin', 'vcvars32.bat')):
  291. try:
  292. targets.append(('x86', ('x86', conf.get_msvc_version('msvc', version, '', os.path.join(vc_path, 'Bin', 'vcvars32.bat')))))
  293. except conf.errors.ConfigurationError:
  294. pass
  295. versions.append(('msvc '+ version, targets))
  296. @conf
  297. def gather_wince_targets(conf, versions, version, vc_path, vsvars, supported_platforms):
  298. #Looking for Win CE compilers!
  299. for device,platforms in supported_platforms:
  300. cetargets = []
  301. for platform,compiler,include,lib in platforms:
  302. winCEpath = os.path.join(vc_path, 'ce')
  303. if not os.path.isdir(winCEpath):
  304. continue
  305. try:
  306. common_bindirs,_1,_2 = conf.get_msvc_version('msvc', version, 'x86', vsvars)
  307. except conf.errors.ConfigurationError:
  308. continue
  309. if os.path.isdir(os.path.join(winCEpath, 'lib', platform)):
  310. bindirs = [os.path.join(winCEpath, 'bin', compiler), os.path.join(winCEpath, 'bin', 'x86_'+compiler)] + common_bindirs
  311. incdirs = [os.path.join(winCEpath, 'include'), os.path.join(winCEpath, 'atlmfc', 'include'), include]
  312. libdirs = [os.path.join(winCEpath, 'lib', platform), os.path.join(winCEpath, 'atlmfc', 'lib', platform), lib]
  313. cetargets.append((platform, (platform, (bindirs,incdirs,libdirs))))
  314. if cetargets:
  315. versions.append((device + ' ' + version, cetargets))
  316. @conf
  317. def gather_msvc_versions(conf, versions):
  318. vc_paths = []
  319. for (v,version,reg) in gather_msvc_detected_versions():
  320. try:
  321. try:
  322. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\VC")
  323. except WindowsError:
  324. msvc_version = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, reg + "\\Setup\\Microsoft Visual C++")
  325. path,type = Utils.winreg.QueryValueEx(msvc_version, 'ProductDir')
  326. vc_paths.append((version, os.path.abspath(str(path))))
  327. except WindowsError:
  328. continue
  329. wince_supported_platforms = gather_wince_supported_platforms()
  330. for version,vc_path in vc_paths:
  331. vs_path = os.path.dirname(vc_path)
  332. vsvars = os.path.join(vs_path, 'Common7', 'Tools', 'vsvars32.bat')
  333. if wince_supported_platforms and os.path.isfile(vsvars):
  334. conf.gather_wince_targets(versions, version, vc_path, vsvars, wince_supported_platforms)
  335. for version,vc_path in vc_paths:
  336. vs_path = os.path.dirname(vc_path)
  337. conf.gather_msvc_targets(versions, version, vc_path)
  338. @conf
  339. def gather_icl_versions(conf, versions):
  340. """
  341. Checks ICL compilers
  342. :param versions: list to modify
  343. :type versions: list
  344. """
  345. version_pattern = re.compile('^...?.?\....?.?')
  346. try:
  347. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Intel\\Compilers\\C++')
  348. except WindowsError:
  349. try:
  350. all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Intel\\Compilers\\C++')
  351. except WindowsError:
  352. return
  353. index = 0
  354. while 1:
  355. try:
  356. version = Utils.winreg.EnumKey(all_versions, index)
  357. except WindowsError:
  358. break
  359. index = index + 1
  360. if not version_pattern.match(version):
  361. continue
  362. targets = []
  363. for target,arch in all_icl_platforms:
  364. try:
  365. if target=='intel64': targetDir='EM64T_NATIVE'
  366. else: targetDir=target
  367. Utils.winreg.OpenKey(all_versions,version+'\\'+targetDir)
  368. icl_version=Utils.winreg.OpenKey(all_versions,version)
  369. path,type=Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  370. if os.path.isfile(os.path.join(path,'bin','iclvars.bat')):
  371. try:
  372. targets.append((target,(arch,conf.get_msvc_version('intel',version,target,os.path.join(path,'bin','iclvars.bat')))))
  373. except conf.errors.ConfigurationError:
  374. pass
  375. except WindowsError:
  376. pass
  377. for target,arch in all_icl_platforms:
  378. try:
  379. icl_version = Utils.winreg.OpenKey(all_versions, version+'\\'+target)
  380. path,type = Utils.winreg.QueryValueEx(icl_version,'ProductDir')
  381. if os.path.isfile(os.path.join(path, 'bin', 'iclvars.bat')):
  382. try:
  383. targets.append((target, (arch, conf.get_msvc_version('intel', version, target, os.path.join(path, 'bin', 'iclvars.bat')))))
  384. except conf.errors.ConfigurationError:
  385. pass
  386. except WindowsError:
  387. continue
  388. major = version[0:2]
  389. versions.append(('intel ' + major, targets))
  390. @conf
  391. def get_msvc_versions(conf):
  392. """
  393. :return: list of compilers installed
  394. :rtype: list of string
  395. """
  396. if not conf.env['MSVC_INSTALLED_VERSIONS']:
  397. lst = []
  398. conf.gather_icl_versions(lst)
  399. conf.gather_wsdk_versions(lst)
  400. conf.gather_msvc_versions(lst)
  401. conf.env['MSVC_INSTALLED_VERSIONS'] = lst
  402. return conf.env['MSVC_INSTALLED_VERSIONS']
  403. @conf
  404. def print_all_msvc_detected(conf):
  405. """
  406. Print the contents of *conf.env.MSVC_INSTALLED_VERSIONS*
  407. """
  408. for version,targets in conf.env['MSVC_INSTALLED_VERSIONS']:
  409. Logs.info(version)
  410. for target,l in targets:
  411. Logs.info("\t"+target)
  412. @conf
  413. def detect_msvc(conf, arch = False):
  414. versions = get_msvc_versions(conf)
  415. return setup_msvc(conf, versions, arch)
  416. @conf
  417. def find_lt_names_msvc(self, libname, is_static=False):
  418. """
  419. Win32/MSVC specific code to glean out information from libtool la files.
  420. this function is not attached to the task_gen class
  421. """
  422. lt_names=[
  423. 'lib%s.la' % libname,
  424. '%s.la' % libname,
  425. ]
  426. for path in self.env['LIBPATH']:
  427. for la in lt_names:
  428. laf=os.path.join(path,la)
  429. dll=None
  430. if os.path.exists(laf):
  431. ltdict = Utils.read_la_file(laf)
  432. lt_libdir=None
  433. if ltdict.get('libdir', ''):
  434. lt_libdir = ltdict['libdir']
  435. if not is_static and ltdict.get('library_names', ''):
  436. dllnames=ltdict['library_names'].split()
  437. dll=dllnames[0].lower()
  438. dll=re.sub('\.dll$', '', dll)
  439. return (lt_libdir, dll, False)
  440. elif ltdict.get('old_library', ''):
  441. olib=ltdict['old_library']
  442. if os.path.exists(os.path.join(path,olib)):
  443. return (path, olib, True)
  444. elif lt_libdir != '' and os.path.exists(os.path.join(lt_libdir,olib)):
  445. return (lt_libdir, olib, True)
  446. else:
  447. return (None, olib, True)
  448. else:
  449. raise self.errors.WafError('invalid libtool object file: %s' % laf)
  450. return (None, None, None)
  451. @conf
  452. def libname_msvc(self, libname, is_static=False):
  453. lib = libname.lower()
  454. lib = re.sub('\.lib$','',lib)
  455. if lib in g_msvc_systemlibs:
  456. return lib
  457. lib=re.sub('^lib','',lib)
  458. if lib == 'm':
  459. return None
  460. (lt_path, lt_libname, lt_static) = self.find_lt_names_msvc(lib, is_static)
  461. if lt_path != None and lt_libname != None:
  462. if lt_static == True:
  463. # file existance check has been made by find_lt_names
  464. return os.path.join(lt_path,lt_libname)
  465. if lt_path != None:
  466. _libpaths=[lt_path] + self.env['LIBPATH']
  467. else:
  468. _libpaths=self.env['LIBPATH']
  469. static_libs=[
  470. 'lib%ss.lib' % lib,
  471. 'lib%s.lib' % lib,
  472. '%ss.lib' % lib,
  473. '%s.lib' %lib,
  474. ]
  475. dynamic_libs=[
  476. 'lib%s.dll.lib' % lib,
  477. 'lib%s.dll.a' % lib,
  478. '%s.dll.lib' % lib,
  479. '%s.dll.a' % lib,
  480. 'lib%s_d.lib' % lib,
  481. '%s_d.lib' % lib,
  482. '%s.lib' %lib,
  483. ]
  484. libnames=static_libs
  485. if not is_static:
  486. libnames=dynamic_libs + static_libs
  487. for path in _libpaths:
  488. for libn in libnames:
  489. if os.path.exists(os.path.join(path, libn)):
  490. debug('msvc: lib found: %s' % os.path.join(path,libn))
  491. return re.sub('\.lib$', '',libn)
  492. #if no lib can be found, just return the libname as msvc expects it
  493. self.fatal("The library %r could not be found" % libname)
  494. return re.sub('\.lib$', '', libname)
  495. @conf
  496. def check_lib_msvc(self, libname, is_static=False, uselib_store=None):
  497. """
  498. Ideally we should be able to place the lib in the right env var, either STLIB or LIB,
  499. but we don't distinguish static libs from shared libs.
  500. This is ok since msvc doesn't have any special linker flag to select static libs (no env['STLIB_MARKER'])
  501. """
  502. libn = self.libname_msvc(libname, is_static)
  503. if not uselib_store:
  504. uselib_store = libname.upper()
  505. if False and is_static: # disabled
  506. self.env['STLIB_' + uselib_store] = [libn]
  507. else:
  508. self.env['LIB_' + uselib_store] = [libn]
  509. @conf
  510. def check_libs_msvc(self, libnames, is_static=False):
  511. for libname in Utils.to_list(libnames):
  512. self.check_lib_msvc(libname, is_static)
  513. def configure(conf):
  514. """
  515. Configuration methods to call for detecting msvc
  516. """
  517. conf.autodetect(True)
  518. conf.find_msvc()
  519. conf.msvc_common_flags()
  520. conf.cc_load_tools()
  521. conf.cxx_load_tools()
  522. conf.cc_add_flags()
  523. conf.cxx_add_flags()
  524. conf.link_add_flags()
  525. conf.visual_studio_add_flags()
  526. @conf
  527. def no_autodetect(conf):
  528. conf.env.NO_MSVC_DETECT = 1
  529. configure(conf)
  530. @conf
  531. def autodetect(conf, arch = False):
  532. v = conf.env
  533. if v.NO_MSVC_DETECT:
  534. return
  535. if arch:
  536. compiler, version, path, includes, libdirs, arch = conf.detect_msvc(True)
  537. v['DEST_CPU'] = arch
  538. else:
  539. compiler, version, path, includes, libdirs = conf.detect_msvc()
  540. v['PATH'] = path
  541. v['INCLUDES'] = includes
  542. v['LIBPATH'] = libdirs
  543. v['MSVC_COMPILER'] = compiler
  544. try:
  545. v['MSVC_VERSION'] = float(version)
  546. except Exception:
  547. v['MSVC_VERSION'] = float(version[:-3])
  548. def _get_prog_names(conf, compiler):
  549. if compiler=='intel':
  550. compiler_name = 'ICL'
  551. linker_name = 'XILINK'
  552. lib_name = 'XILIB'
  553. else:
  554. # assumes CL.exe
  555. compiler_name = 'CL'
  556. linker_name = 'LINK'
  557. lib_name = 'LIB'
  558. return compiler_name, linker_name, lib_name
  559. @conf
  560. def find_msvc(conf):
  561. """Due to path format limitations, limit operation only to native Win32. Yeah it sucks."""
  562. if sys.platform == 'cygwin':
  563. conf.fatal('MSVC module does not work under cygwin Python!')
  564. # the autodetection is supposed to be performed before entering in this method
  565. v = conf.env
  566. path = v['PATH']
  567. compiler = v['MSVC_COMPILER']
  568. version = v['MSVC_VERSION']
  569. compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
  570. v.MSVC_MANIFEST = (compiler == 'msvc' and version >= 8) or (compiler == 'wsdk' and version >= 6) or (compiler == 'intel' and version >= 11)
  571. # compiler
  572. cxx = None
  573. if v['CXX']: cxx = v['CXX']
  574. elif 'CXX' in conf.environ: cxx = conf.environ['CXX']
  575. cxx = conf.find_program(compiler_name, var='CXX', path_list=path)
  576. cxx = conf.cmd_to_list(cxx)
  577. # before setting anything, check if the compiler is really msvc
  578. env = dict(conf.environ)
  579. if path: env.update(PATH = ';'.join(path))
  580. if not conf.cmd_and_log(cxx + ['/nologo', '/help'], env=env):
  581. conf.fatal('the msvc compiler could not be identified')
  582. # c/c++ compiler
  583. v['CC'] = v['CXX'] = cxx
  584. v['CC_NAME'] = v['CXX_NAME'] = 'msvc'
  585. # linker
  586. if not v['LINK_CXX']:
  587. link = conf.find_program(linker_name, path_list=path)
  588. if link: v['LINK_CXX'] = link
  589. else: conf.fatal('%s was not found (linker)' % linker_name)
  590. v['LINK'] = link
  591. if not v['LINK_CC']:
  592. v['LINK_CC'] = v['LINK_CXX']
  593. # staticlib linker
  594. if not v['AR']:
  595. stliblink = conf.find_program(lib_name, path_list=path, var='AR')
  596. if not stliblink: return
  597. v['ARFLAGS'] = ['/NOLOGO']
  598. # manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later
  599. if v.MSVC_MANIFEST:
  600. conf.find_program('MT', path_list=path, var='MT')
  601. v['MTFLAGS'] = ['/NOLOGO']
  602. conf.load('winres')
  603. if not conf.env['WINRC']:
  604. warn('Resource compiler not found. Compiling resource file is disabled')
  605. @conf
  606. def visual_studio_add_flags(self):
  607. """visual studio flags found in the system environment"""
  608. v = self.env
  609. try: v.prepend_value('INCLUDES', [x for x in self.environ['INCLUDE'].split(';') if x]) # notice the 'S'
  610. except Exception: pass
  611. try: v.prepend_value('LIBPATH', [x for x in self.environ['LIB'].split(';') if x])
  612. except Exception: pass
  613. @conf
  614. def msvc_common_flags(conf):
  615. """
  616. Setup the flags required for executing the msvc compiler
  617. """
  618. v = conf.env
  619. v['DEST_BINFMT'] = 'pe'
  620. v.append_value('CFLAGS', ['/nologo'])
  621. v.append_value('CXXFLAGS', ['/nologo'])
  622. v['DEFINES_ST'] = '/D%s'
  623. v['CC_SRC_F'] = ''
  624. v['CC_TGT_F'] = ['/c', '/Fo']
  625. if v['MSVC_VERSION'] >= 8:
  626. v['CC_TGT_F']= ['/FC'] + v['CC_TGT_F']
  627. v['CXX_SRC_F'] = ''
  628. v['CXX_TGT_F'] = ['/c', '/Fo']
  629. if v['MSVC_VERSION'] >= 8:
  630. v['CXX_TGT_F']= ['/FC'] + v['CXX_TGT_F']
  631. v['CPPPATH_ST'] = '/I%s' # template for adding include paths
  632. v['AR_TGT_F'] = v['CCLNK_TGT_F'] = v['CXXLNK_TGT_F'] = '/OUT:'
  633. # Subsystem specific flags
  634. v['CFLAGS_CONSOLE'] = v['CXXFLAGS_CONSOLE'] = ['/SUBSYSTEM:CONSOLE']
  635. v['CFLAGS_NATIVE'] = v['CXXFLAGS_NATIVE'] = ['/SUBSYSTEM:NATIVE']
  636. v['CFLAGS_POSIX'] = v['CXXFLAGS_POSIX'] = ['/SUBSYSTEM:POSIX']
  637. v['CFLAGS_WINDOWS'] = v['CXXFLAGS_WINDOWS'] = ['/SUBSYSTEM:WINDOWS']
  638. v['CFLAGS_WINDOWSCE'] = v['CXXFLAGS_WINDOWSCE'] = ['/SUBSYSTEM:WINDOWSCE']
  639. # CRT specific flags
  640. v['CFLAGS_CRT_MULTITHREADED'] = v['CXXFLAGS_CRT_MULTITHREADED'] = ['/MT']
  641. v['CFLAGS_CRT_MULTITHREADED_DLL'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL'] = ['/MD']
  642. v['CFLAGS_CRT_MULTITHREADED_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DBG'] = ['/MTd']
  643. v['CFLAGS_CRT_MULTITHREADED_DLL_DBG'] = v['CXXFLAGS_CRT_MULTITHREADED_DLL_DBG'] = ['/MDd']
  644. # linker
  645. v['LIB_ST'] = '%s.lib' # template for adding shared libs
  646. v['LIBPATH_ST'] = '/LIBPATH:%s' # template for adding libpaths
  647. v['STLIB_ST'] = '%s.lib'
  648. v['STLIBPATH_ST'] = '/LIBPATH:%s'
  649. v.append_value('LINKFLAGS', ['/NOLOGO'])
  650. if v['MSVC_MANIFEST']:
  651. v.append_value('LINKFLAGS', ['/MANIFEST'])
  652. # shared library
  653. v['CFLAGS_cshlib'] = []
  654. v['CXXFLAGS_cxxshlib'] = []
  655. v['LINKFLAGS_cshlib'] = v['LINKFLAGS_cxxshlib'] = ['/DLL']
  656. v['cshlib_PATTERN'] = v['cxxshlib_PATTERN'] = '%s.dll'
  657. v['implib_PATTERN'] = '%s.lib'
  658. v['IMPLIB_ST'] = '/IMPLIB:%s'
  659. # static library
  660. v['LINKFLAGS_cstlib'] = []
  661. v['cstlib_PATTERN'] = v['cxxstlib_PATTERN'] = '%s.lib'
  662. # program
  663. v['cprogram_PATTERN'] = v['cxxprogram_PATTERN'] = '%s.exe'
  664. #######################################################################################################
  665. ##### conf above, build below
  666. @after_method('apply_link')
  667. @feature('c', 'cxx')
  668. def apply_flags_msvc(self):
  669. """
  670. Add additional flags implied by msvc, such as subsystems and pdb files::
  671. def build(bld):
  672. bld.stlib(source='main.c', target='bar', subsystem='gruik')
  673. """
  674. if self.env.CC_NAME != 'msvc' or not getattr(self, 'link_task', None):
  675. return
  676. is_static = isinstance(self.link_task, ccroot.stlink_task)
  677. subsystem = getattr(self, 'subsystem', '')
  678. if subsystem:
  679. subsystem = '/subsystem:%s' % subsystem
  680. flags = is_static and 'ARFLAGS' or 'LINKFLAGS'
  681. self.env.append_value(flags, subsystem)
  682. if not is_static:
  683. for f in self.env.LINKFLAGS:
  684. d = f.lower()
  685. if d[1:] == 'debug':
  686. pdbnode = self.link_task.outputs[0].change_ext('.pdb')
  687. self.link_task.outputs.append(pdbnode)
  688. try:
  689. self.install_task.source.append(pdbnode)
  690. except AttributeError:
  691. pass
  692. break
  693. # split the manifest file processing from the link task, like for the rc processing
  694. @feature('cprogram', 'cshlib', 'cxxprogram', 'cxxshlib')
  695. @after_method('apply_link')
  696. def apply_manifest(self):
  697. """
  698. Special linker for MSVC with support for embedding manifests into DLL's
  699. and executables compiled by Visual Studio 2005 or probably later. Without
  700. the manifest file, the binaries are unusable.
  701. See: http://msdn2.microsoft.com/en-us/library/ms235542(VS.80).aspx
  702. """
  703. if self.env.CC_NAME == 'msvc' and self.env.MSVC_MANIFEST and getattr(self, 'link_task', None):
  704. out_node = self.link_task.outputs[0]
  705. man_node = out_node.parent.find_or_declare(out_node.name + '.manifest')
  706. self.link_task.outputs.append(man_node)
  707. self.link_task.do_manifest = True
  708. def exec_mf(self):
  709. """
  710. Create the manifest file
  711. """
  712. env = self.env
  713. mtool = env['MT']
  714. if not mtool:
  715. return 0
  716. self.do_manifest = False
  717. outfile = self.outputs[0].abspath()
  718. manifest = None
  719. for out_node in self.outputs:
  720. if out_node.name.endswith('.manifest'):
  721. manifest = out_node.abspath()
  722. break
  723. if manifest is None:
  724. # Should never get here. If we do, it means the manifest file was
  725. # never added to the outputs list, thus we don't have a manifest file
  726. # to embed, so we just return.
  727. return 0
  728. # embedding mode. Different for EXE's and DLL's.
  729. # see: http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx
  730. mode = ''
  731. if 'cprogram' in self.generator.features or 'cxxprogram' in self.generator.features:
  732. mode = '1'
  733. elif 'cshlib' in self.generator.features or 'cxxshlib' in self.generator.features:
  734. mode = '2'
  735. debug('msvc: embedding manifest in mode %r' % mode)
  736. lst = []
  737. lst.append(env['MT'])
  738. lst.extend(Utils.to_list(env['MTFLAGS']))
  739. lst.extend(['-manifest', manifest])
  740. lst.append('-outputresource:%s;%s' % (outfile, mode))
  741. lst = [lst]
  742. return self.exec_command(*lst)
  743. def quote_response_command(self, flag):
  744. if flag.find(' ') > -1:
  745. for x in ('/LIBPATH:', '/IMPLIB:', '/OUT:', '/I'):
  746. if flag.startswith(x):
  747. flag = '%s"%s"' % (x, flag[len(x):])
  748. break
  749. else:
  750. flag = '"%s"' % flag
  751. return flag
  752. def exec_response_command(self, cmd, **kw):
  753. # not public yet
  754. try:
  755. tmp = None
  756. if sys.platform.startswith('win') and isinstance(cmd, list) and len(' '.join(cmd)) >= 8192:
  757. program = cmd[0] #unquoted program name, otherwise exec_command will fail
  758. cmd = [self.quote_response_command(x) for x in cmd]
  759. (fd, tmp) = tempfile.mkstemp()
  760. os.write(fd, '\r\n'.join(i.replace('\\', '\\\\') for i in cmd[1:]).encode())
  761. os.close(fd)
  762. cmd = [program, '@' + tmp]
  763. # no return here, that's on purpose
  764. ret = self.generator.bld.exec_command(cmd, **kw)
  765. finally:
  766. if tmp:
  767. try:
  768. os.remove(tmp)
  769. except OSError:
  770. pass # anti-virus and indexers can keep the files open -_-
  771. return ret
  772. ########## stupid evil command modification: concatenate the tokens /Fx, /doc, and /x: with the next token
  773. def exec_command_msvc(self, *k, **kw):
  774. """
  775. Change the command-line execution for msvc programs.
  776. Instead of quoting all the paths and keep using the shell, we can just join the options msvc is interested in
  777. """
  778. if self.env['CC_NAME'] == 'msvc':
  779. if isinstance(k[0], list):
  780. lst = []
  781. carry = ''
  782. for a in k[0]:
  783. if a == '/Fo' or a == '/doc' or a[-1] == ':':
  784. carry = a
  785. else:
  786. lst.append(carry + a)
  787. carry = ''
  788. k = [lst]
  789. if self.env['PATH']:
  790. env = dict(self.env.env or os.environ)
  791. env.update(PATH = ';'.join(self.env['PATH']))
  792. kw['env'] = env
  793. bld = self.generator.bld
  794. try:
  795. if not kw.get('cwd', None):
  796. kw['cwd'] = bld.cwd
  797. except AttributeError:
  798. bld.cwd = kw['cwd'] = bld.variant_dir
  799. ret = self.exec_response_command(k[0], **kw)
  800. if not ret and getattr(self, 'do_manifest', None):
  801. ret = self.exec_mf()
  802. return ret
  803. for k in 'c cxx cprogram cxxprogram cshlib cxxshlib cstlib cxxstlib'.split():
  804. cls = Task.classes.get(k, None)
  805. if cls:
  806. cls.exec_command = exec_command_msvc
  807. cls.exec_response_command = exec_response_command
  808. cls.quote_response_command = quote_response_command
  809. cls.exec_mf = exec_mf