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.

1352 lines
40KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. C/C++/D configuration helpers
  6. """
  7. from __future__ import with_statement
  8. import os, re, shlex
  9. from waflib import Build, Utils, Task, Options, Logs, Errors, Runner
  10. from waflib.TaskGen import after_method, feature
  11. from waflib.Configure import conf
  12. WAF_CONFIG_H = 'config.h'
  13. """default name for the config.h file"""
  14. DEFKEYS = 'define_key'
  15. INCKEYS = 'include_key'
  16. SNIP_EMPTY_PROGRAM = '''
  17. int main(int argc, char **argv) {
  18. (void)argc; (void)argv;
  19. return 0;
  20. }
  21. '''
  22. MACRO_TO_DESTOS = {
  23. '__linux__' : 'linux',
  24. '__GNU__' : 'gnu', # hurd
  25. '__FreeBSD__' : 'freebsd',
  26. '__NetBSD__' : 'netbsd',
  27. '__OpenBSD__' : 'openbsd',
  28. '__sun' : 'sunos',
  29. '__hpux' : 'hpux',
  30. '__sgi' : 'irix',
  31. '_AIX' : 'aix',
  32. '__CYGWIN__' : 'cygwin',
  33. '__MSYS__' : 'cygwin',
  34. '_UWIN' : 'uwin',
  35. '_WIN64' : 'win32',
  36. '_WIN32' : 'win32',
  37. # Note about darwin: this is also tested with 'defined __APPLE__ && defined __MACH__' somewhere below in this file.
  38. '__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__' : 'darwin',
  39. '__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__' : 'darwin', # iphone
  40. '__QNX__' : 'qnx',
  41. '__native_client__' : 'nacl' # google native client platform
  42. }
  43. MACRO_TO_DEST_CPU = {
  44. '__x86_64__' : 'x86_64',
  45. '__amd64__' : 'x86_64',
  46. '__i386__' : 'x86',
  47. '__ia64__' : 'ia',
  48. '__mips__' : 'mips',
  49. '__sparc__' : 'sparc',
  50. '__alpha__' : 'alpha',
  51. '__aarch64__' : 'aarch64',
  52. '__thumb__' : 'thumb',
  53. '__arm__' : 'arm',
  54. '__hppa__' : 'hppa',
  55. '__powerpc__' : 'powerpc',
  56. '__ppc__' : 'powerpc',
  57. '__convex__' : 'convex',
  58. '__m68k__' : 'm68k',
  59. '__s390x__' : 's390x',
  60. '__s390__' : 's390',
  61. '__sh__' : 'sh',
  62. '__xtensa__' : 'xtensa',
  63. }
  64. @conf
  65. def parse_flags(self, line, uselib_store, env=None, force_static=False, posix=None):
  66. """
  67. Parses flags from the input lines, and adds them to the relevant use variables::
  68. def configure(conf):
  69. conf.parse_flags('-O3', 'FOO')
  70. # conf.env.CXXFLAGS_FOO = ['-O3']
  71. # conf.env.CFLAGS_FOO = ['-O3']
  72. :param line: flags
  73. :type line: string
  74. :param uselib_store: where to add the flags
  75. :type uselib_store: string
  76. :param env: config set or conf.env by default
  77. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  78. """
  79. assert(isinstance(line, str))
  80. env = env or self.env
  81. # Issue 811 and 1371
  82. if posix is None:
  83. posix = True
  84. if '\\' in line:
  85. posix = ('\\ ' in line) or ('\\\\' in line)
  86. lex = shlex.shlex(line, posix=posix)
  87. lex.whitespace_split = True
  88. lex.commenters = ''
  89. lst = list(lex)
  90. # append_unique is not always possible
  91. # for example, apple flags may require both -arch i386 and -arch ppc
  92. uselib = uselib_store
  93. def app(var, val):
  94. env.append_value('%s_%s' % (var, uselib), val)
  95. def appu(var, val):
  96. env.append_unique('%s_%s' % (var, uselib), val)
  97. static = False
  98. while lst:
  99. x = lst.pop(0)
  100. st = x[:2]
  101. ot = x[2:]
  102. if st == '-I' or st == '/I':
  103. if not ot:
  104. ot = lst.pop(0)
  105. appu('INCLUDES', ot)
  106. elif st == '-i':
  107. tmp = [x, lst.pop(0)]
  108. app('CFLAGS', tmp)
  109. app('CXXFLAGS', tmp)
  110. elif st == '-D' or (env.CXX_NAME == 'msvc' and st == '/D'): # not perfect but..
  111. if not ot:
  112. ot = lst.pop(0)
  113. app('DEFINES', ot)
  114. elif st == '-l':
  115. if not ot:
  116. ot = lst.pop(0)
  117. prefix = 'STLIB' if (force_static or static) else 'LIB'
  118. app(prefix, ot)
  119. elif st == '-L':
  120. if not ot:
  121. ot = lst.pop(0)
  122. prefix = 'STLIBPATH' if (force_static or static) else 'LIBPATH'
  123. appu(prefix, ot)
  124. elif x.startswith('/LIBPATH:'):
  125. prefix = 'STLIBPATH' if (force_static or static) else 'LIBPATH'
  126. appu(prefix, x.replace('/LIBPATH:', ''))
  127. elif x.startswith('-std='):
  128. prefix = 'CXXFLAGS' if '++' in x else 'CFLAGS'
  129. app(prefix, x)
  130. elif x.startswith('+') or x in ('-pthread', '-fPIC', '-fpic', '-fPIE', '-fpie'):
  131. app('CFLAGS', x)
  132. app('CXXFLAGS', x)
  133. app('LINKFLAGS', x)
  134. elif x == '-framework':
  135. appu('FRAMEWORK', lst.pop(0))
  136. elif x.startswith('-F'):
  137. appu('FRAMEWORKPATH', x[2:])
  138. elif x == '-Wl,-rpath' or x == '-Wl,-R':
  139. app('RPATH', lst.pop(0).lstrip('-Wl,'))
  140. elif x.startswith('-Wl,-R,'):
  141. app('RPATH', x[7:])
  142. elif x.startswith('-Wl,-R'):
  143. app('RPATH', x[6:])
  144. elif x.startswith('-Wl,-rpath,'):
  145. app('RPATH', x[11:])
  146. elif x == '-Wl,-Bstatic' or x == '-Bstatic':
  147. static = True
  148. elif x == '-Wl,-Bdynamic' or x == '-Bdynamic':
  149. static = False
  150. elif x.startswith('-Wl') or x in ('-rdynamic', '-pie'):
  151. app('LINKFLAGS', x)
  152. elif x.startswith(('-m', '-f', '-dynamic', '-O', '-g')):
  153. # Adding the -W option breaks python builds on Openindiana
  154. app('CFLAGS', x)
  155. app('CXXFLAGS', x)
  156. elif x.startswith('-bundle'):
  157. app('LINKFLAGS', x)
  158. elif x.startswith(('-undefined', '-Xlinker')):
  159. arg = lst.pop(0)
  160. app('LINKFLAGS', [x, arg])
  161. elif x.startswith(('-arch', '-isysroot')):
  162. tmp = [x, lst.pop(0)]
  163. app('CFLAGS', tmp)
  164. app('CXXFLAGS', tmp)
  165. app('LINKFLAGS', tmp)
  166. elif x.endswith(('.a', '.so', '.dylib', '.lib')):
  167. appu('LINKFLAGS', x) # not cool, #762
  168. else:
  169. self.to_log('Unhandled flag %r' % x)
  170. @conf
  171. def validate_cfg(self, kw):
  172. """
  173. Searches for the program *pkg-config* if missing, and validates the
  174. parameters to pass to :py:func:`waflib.Tools.c_config.exec_cfg`.
  175. :param path: the **-config program to use** (default is *pkg-config*)
  176. :type path: list of string
  177. :param msg: message to display to describe the test executed
  178. :type msg: string
  179. :param okmsg: message to display when the test is successful
  180. :type okmsg: string
  181. :param errmsg: message to display in case of error
  182. :type errmsg: string
  183. """
  184. if not 'path' in kw:
  185. if not self.env.PKGCONFIG:
  186. self.find_program('pkg-config', var='PKGCONFIG')
  187. kw['path'] = self.env.PKGCONFIG
  188. # verify that exactly one action is requested
  189. s = ('atleast_pkgconfig_version' in kw) + ('modversion' in kw) + ('package' in kw)
  190. if s != 1:
  191. raise ValueError('exactly one of atleast_pkgconfig_version, modversion and package must be set')
  192. if not 'msg' in kw:
  193. if 'atleast_pkgconfig_version' in kw:
  194. kw['msg'] = 'Checking for pkg-config version >= %r' % kw['atleast_pkgconfig_version']
  195. elif 'modversion' in kw:
  196. kw['msg'] = 'Checking for %r version' % kw['modversion']
  197. else:
  198. kw['msg'] = 'Checking for %r' %(kw['package'])
  199. # let the modversion check set the okmsg to the detected version
  200. if not 'okmsg' in kw and not 'modversion' in kw:
  201. kw['okmsg'] = 'yes'
  202. if not 'errmsg' in kw:
  203. kw['errmsg'] = 'not found'
  204. # pkg-config version
  205. if 'atleast_pkgconfig_version' in kw:
  206. pass
  207. elif 'modversion' in kw:
  208. if not 'uselib_store' in kw:
  209. kw['uselib_store'] = kw['modversion']
  210. if not 'define_name' in kw:
  211. kw['define_name'] = '%s_VERSION' % Utils.quote_define_name(kw['uselib_store'])
  212. else:
  213. if not 'uselib_store' in kw:
  214. kw['uselib_store'] = Utils.to_list(kw['package'])[0].upper()
  215. if not 'define_name' in kw:
  216. kw['define_name'] = self.have_define(kw['uselib_store'])
  217. @conf
  218. def exec_cfg(self, kw):
  219. """
  220. Executes ``pkg-config`` or other ``-config`` applications to collect configuration flags:
  221. * if atleast_pkgconfig_version is given, check that pkg-config has the version n and return
  222. * if modversion is given, then return the module version
  223. * else, execute the *-config* program with the *args* and *variables* given, and set the flags on the *conf.env.FLAGS_name* variable
  224. :param atleast_pkgconfig_version: minimum pkg-config version to use (disable other tests)
  225. :type atleast_pkgconfig_version: string
  226. :param package: package name, for example *gtk+-2.0*
  227. :type package: string
  228. :param uselib_store: if the test is successful, define HAVE\_*name*. It is also used to define *conf.env.FLAGS_name* variables.
  229. :type uselib_store: string
  230. :param modversion: if provided, return the version of the given module and define *name*\_VERSION
  231. :type modversion: string
  232. :param args: arguments to give to *package* when retrieving flags
  233. :type args: list of string
  234. :param variables: return the values of particular variables
  235. :type variables: list of string
  236. :param define_variable: additional variables to define (also in conf.env.PKG_CONFIG_DEFINES)
  237. :type define_variable: dict(string: string)
  238. """
  239. path = Utils.to_list(kw['path'])
  240. env = self.env.env or None
  241. if kw.get('pkg_config_path'):
  242. if not env:
  243. env = dict(self.environ)
  244. env['PKG_CONFIG_PATH'] = kw['pkg_config_path']
  245. def define_it():
  246. define_name = kw['define_name']
  247. # by default, add HAVE_X to the config.h, else provide DEFINES_X for use=X
  248. if kw.get('global_define', 1):
  249. self.define(define_name, 1, False)
  250. else:
  251. self.env.append_unique('DEFINES_%s' % kw['uselib_store'], "%s=1" % define_name)
  252. if kw.get('add_have_to_env', 1):
  253. self.env[define_name] = 1
  254. # pkg-config version
  255. if 'atleast_pkgconfig_version' in kw:
  256. cmd = path + ['--atleast-pkgconfig-version=%s' % kw['atleast_pkgconfig_version']]
  257. self.cmd_and_log(cmd, env=env)
  258. return
  259. # single version for a module
  260. if 'modversion' in kw:
  261. version = self.cmd_and_log(path + ['--modversion', kw['modversion']], env=env).strip()
  262. if not 'okmsg' in kw:
  263. kw['okmsg'] = version
  264. self.define(kw['define_name'], version)
  265. return version
  266. lst = [] + path
  267. defi = kw.get('define_variable')
  268. if not defi:
  269. defi = self.env.PKG_CONFIG_DEFINES or {}
  270. for key, val in defi.items():
  271. lst.append('--define-variable=%s=%s' % (key, val))
  272. static = kw.get('force_static', False)
  273. if 'args' in kw:
  274. args = Utils.to_list(kw['args'])
  275. if '--static' in args or '--static-libs' in args:
  276. static = True
  277. lst += args
  278. # tools like pkgconf expect the package argument after the -- ones -_-
  279. lst.extend(Utils.to_list(kw['package']))
  280. # retrieving variables of a module
  281. if 'variables' in kw:
  282. v_env = kw.get('env', self.env)
  283. vars = Utils.to_list(kw['variables'])
  284. for v in vars:
  285. val = self.cmd_and_log(lst + ['--variable=' + v], env=env).strip()
  286. var = '%s_%s' % (kw['uselib_store'], v)
  287. v_env[var] = val
  288. return
  289. # so we assume the command-line will output flags to be parsed afterwards
  290. ret = self.cmd_and_log(lst, env=env)
  291. define_it()
  292. self.parse_flags(ret, kw['uselib_store'], kw.get('env', self.env), force_static=static, posix=kw.get('posix'))
  293. return ret
  294. @conf
  295. def check_cfg(self, *k, **kw):
  296. """
  297. Checks for configuration flags using a **-config**-like program (pkg-config, sdl-config, etc).
  298. This wraps internal calls to :py:func:`waflib.Tools.c_config.validate_cfg` and :py:func:`waflib.Tools.c_config.exec_cfg`
  299. A few examples::
  300. def configure(conf):
  301. conf.load('compiler_c')
  302. conf.check_cfg(package='glib-2.0', args='--libs --cflags')
  303. conf.check_cfg(package='pango')
  304. conf.check_cfg(package='pango', uselib_store='MYPANGO', args=['--cflags', '--libs'])
  305. conf.check_cfg(package='pango',
  306. args=['pango >= 0.1.0', 'pango < 9.9.9', '--cflags', '--libs'],
  307. msg="Checking for 'pango 0.1.0'")
  308. conf.check_cfg(path='sdl-config', args='--cflags --libs', package='', uselib_store='SDL')
  309. conf.check_cfg(path='mpicc', args='--showme:compile --showme:link',
  310. package='', uselib_store='OPEN_MPI', mandatory=False)
  311. # variables
  312. conf.check_cfg(package='gtk+-2.0', variables=['includedir', 'prefix'], uselib_store='FOO')
  313. print(conf.env.FOO_includedir)
  314. """
  315. self.validate_cfg(kw)
  316. if 'msg' in kw:
  317. self.start_msg(kw['msg'], **kw)
  318. ret = None
  319. try:
  320. ret = self.exec_cfg(kw)
  321. except self.errors.WafError as e:
  322. if 'errmsg' in kw:
  323. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  324. if Logs.verbose > 1:
  325. self.to_log('Command failure: %s' % e)
  326. self.fatal('The configuration failed')
  327. else:
  328. if not ret:
  329. ret = True
  330. kw['success'] = ret
  331. if 'okmsg' in kw:
  332. self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
  333. return ret
  334. def build_fun(bld):
  335. """
  336. Build function that is used for running configuration tests with ``conf.check()``
  337. """
  338. if bld.kw['compile_filename']:
  339. node = bld.srcnode.make_node(bld.kw['compile_filename'])
  340. node.write(bld.kw['code'])
  341. o = bld(features=bld.kw['features'], source=bld.kw['compile_filename'], target='testprog')
  342. for k, v in bld.kw.items():
  343. setattr(o, k, v)
  344. if not bld.kw.get('quiet'):
  345. bld.conf.to_log("==>\n%s\n<==" % bld.kw['code'])
  346. @conf
  347. def validate_c(self, kw):
  348. """
  349. Pre-checks the parameters that will be given to :py:func:`waflib.Configure.run_build`
  350. :param compiler: c or cxx (tries to guess what is best)
  351. :type compiler: string
  352. :param type: cprogram, cshlib, cstlib - not required if *features are given directly*
  353. :type type: binary to create
  354. :param feature: desired features for the task generator that will execute the test, for example ``cxx cxxstlib``
  355. :type feature: list of string
  356. :param fragment: provide a piece of code for the test (default is to let the system create one)
  357. :type fragment: string
  358. :param uselib_store: define variables after the test is executed (IMPORTANT!)
  359. :type uselib_store: string
  360. :param use: parameters to use for building (just like the normal *use* keyword)
  361. :type use: list of string
  362. :param define_name: define to set when the check is over
  363. :type define_name: string
  364. :param execute: execute the resulting binary
  365. :type execute: bool
  366. :param define_ret: if execute is set to True, use the execution output in both the define and the return value
  367. :type define_ret: bool
  368. :param header_name: check for a particular header
  369. :type header_name: string
  370. :param auto_add_header_name: if header_name was set, add the headers in env.INCKEYS so the next tests will include these headers
  371. :type auto_add_header_name: bool
  372. """
  373. for x in ('type_name', 'field_name', 'function_name'):
  374. if x in kw:
  375. Logs.warn('Invalid argument %r in test' % x)
  376. if not 'build_fun' in kw:
  377. kw['build_fun'] = build_fun
  378. if not 'env' in kw:
  379. kw['env'] = self.env.derive()
  380. env = kw['env']
  381. if not 'compiler' in kw and not 'features' in kw:
  382. kw['compiler'] = 'c'
  383. if env.CXX_NAME and Task.classes.get('cxx'):
  384. kw['compiler'] = 'cxx'
  385. if not self.env.CXX:
  386. self.fatal('a c++ compiler is required')
  387. else:
  388. if not self.env.CC:
  389. self.fatal('a c compiler is required')
  390. if not 'compile_mode' in kw:
  391. kw['compile_mode'] = 'c'
  392. if 'cxx' in Utils.to_list(kw.get('features', [])) or kw.get('compiler') == 'cxx':
  393. kw['compile_mode'] = 'cxx'
  394. if not 'type' in kw:
  395. kw['type'] = 'cprogram'
  396. if not 'features' in kw:
  397. if not 'header_name' in kw or kw.get('link_header_test', True):
  398. kw['features'] = [kw['compile_mode'], kw['type']] # "c ccprogram"
  399. else:
  400. kw['features'] = [kw['compile_mode']]
  401. else:
  402. kw['features'] = Utils.to_list(kw['features'])
  403. if not 'compile_filename' in kw:
  404. kw['compile_filename'] = 'test.c' + ((kw['compile_mode'] == 'cxx') and 'pp' or '')
  405. def to_header(dct):
  406. if 'header_name' in dct:
  407. dct = Utils.to_list(dct['header_name'])
  408. return ''.join(['#include <%s>\n' % x for x in dct])
  409. return ''
  410. if 'framework_name' in kw:
  411. # OSX, not sure this is used anywhere
  412. fwkname = kw['framework_name']
  413. if not 'uselib_store' in kw:
  414. kw['uselib_store'] = fwkname.upper()
  415. if not kw.get('no_header'):
  416. fwk = '%s/%s.h' % (fwkname, fwkname)
  417. if kw.get('remove_dot_h'):
  418. fwk = fwk[:-2]
  419. val = kw.get('header_name', [])
  420. kw['header_name'] = Utils.to_list(val) + [fwk]
  421. kw['msg'] = 'Checking for framework %s' % fwkname
  422. kw['framework'] = fwkname
  423. elif 'header_name' in kw:
  424. if not 'msg' in kw:
  425. kw['msg'] = 'Checking for header %s' % kw['header_name']
  426. l = Utils.to_list(kw['header_name'])
  427. assert len(l), 'list of headers in header_name is empty'
  428. kw['code'] = to_header(kw) + SNIP_EMPTY_PROGRAM
  429. if not 'uselib_store' in kw:
  430. kw['uselib_store'] = l[0].upper()
  431. if not 'define_name' in kw:
  432. kw['define_name'] = self.have_define(l[0])
  433. if 'lib' in kw:
  434. if not 'msg' in kw:
  435. kw['msg'] = 'Checking for library %s' % kw['lib']
  436. if not 'uselib_store' in kw:
  437. kw['uselib_store'] = kw['lib'].upper()
  438. if 'stlib' in kw:
  439. if not 'msg' in kw:
  440. kw['msg'] = 'Checking for static library %s' % kw['stlib']
  441. if not 'uselib_store' in kw:
  442. kw['uselib_store'] = kw['stlib'].upper()
  443. if 'fragment' in kw:
  444. # an additional code fragment may be provided to replace the predefined code
  445. # in custom headers
  446. kw['code'] = kw['fragment']
  447. if not 'msg' in kw:
  448. kw['msg'] = 'Checking for code snippet'
  449. if not 'errmsg' in kw:
  450. kw['errmsg'] = 'no'
  451. for (flagsname,flagstype) in (('cxxflags','compiler'), ('cflags','compiler'), ('linkflags','linker')):
  452. if flagsname in kw:
  453. if not 'msg' in kw:
  454. kw['msg'] = 'Checking for %s flags %s' % (flagstype, kw[flagsname])
  455. if not 'errmsg' in kw:
  456. kw['errmsg'] = 'no'
  457. if not 'execute' in kw:
  458. kw['execute'] = False
  459. if kw['execute']:
  460. kw['features'].append('test_exec')
  461. kw['chmod'] = Utils.O755
  462. if not 'errmsg' in kw:
  463. kw['errmsg'] = 'not found'
  464. if not 'okmsg' in kw:
  465. kw['okmsg'] = 'yes'
  466. if not 'code' in kw:
  467. kw['code'] = SNIP_EMPTY_PROGRAM
  468. # if there are headers to append automatically to the next tests
  469. if self.env[INCKEYS]:
  470. kw['code'] = '\n'.join(['#include <%s>' % x for x in self.env[INCKEYS]]) + '\n' + kw['code']
  471. # in case defines lead to very long command-lines
  472. if kw.get('merge_config_header') or env.merge_config_header:
  473. kw['code'] = '%s\n\n%s' % (self.get_config_header(), kw['code'])
  474. env.DEFINES = [] # modify the copy
  475. if not kw.get('success'):
  476. kw['success'] = None
  477. if 'define_name' in kw:
  478. self.undefine(kw['define_name'])
  479. if not 'msg' in kw:
  480. self.fatal('missing "msg" in conf.check(...)')
  481. @conf
  482. def post_check(self, *k, **kw):
  483. """
  484. Sets the variables after a test executed in
  485. :py:func:`waflib.Tools.c_config.check` was run successfully
  486. """
  487. is_success = 0
  488. if kw['execute']:
  489. if kw['success'] is not None:
  490. if kw.get('define_ret'):
  491. is_success = kw['success']
  492. else:
  493. is_success = (kw['success'] == 0)
  494. else:
  495. is_success = (kw['success'] == 0)
  496. if kw.get('define_name'):
  497. comment = kw.get('comment', '')
  498. define_name = kw['define_name']
  499. if kw['execute'] and kw.get('define_ret') and isinstance(is_success, str):
  500. if kw.get('global_define', 1):
  501. self.define(define_name, is_success, quote=kw.get('quote', 1), comment=comment)
  502. else:
  503. if kw.get('quote', 1):
  504. succ = '"%s"' % is_success
  505. else:
  506. succ = int(is_success)
  507. val = '%s=%s' % (define_name, succ)
  508. var = 'DEFINES_%s' % kw['uselib_store']
  509. self.env.append_value(var, val)
  510. else:
  511. if kw.get('global_define', 1):
  512. self.define_cond(define_name, is_success, comment=comment)
  513. else:
  514. var = 'DEFINES_%s' % kw['uselib_store']
  515. self.env.append_value(var, '%s=%s' % (define_name, int(is_success)))
  516. # define conf.env.HAVE_X to 1
  517. if kw.get('add_have_to_env', 1):
  518. if kw.get('uselib_store'):
  519. self.env[self.have_define(kw['uselib_store'])] = 1
  520. elif kw['execute'] and kw.get('define_ret'):
  521. self.env[define_name] = is_success
  522. else:
  523. self.env[define_name] = int(is_success)
  524. if 'header_name' in kw:
  525. if kw.get('auto_add_header_name'):
  526. self.env.append_value(INCKEYS, Utils.to_list(kw['header_name']))
  527. if is_success and 'uselib_store' in kw:
  528. from waflib.Tools import ccroot
  529. # See get_uselib_vars in ccroot.py
  530. _vars = set()
  531. for x in kw['features']:
  532. if x in ccroot.USELIB_VARS:
  533. _vars |= ccroot.USELIB_VARS[x]
  534. for k in _vars:
  535. x = k.lower()
  536. if x in kw:
  537. self.env.append_value(k + '_' + kw['uselib_store'], kw[x])
  538. return is_success
  539. @conf
  540. def check(self, *k, **kw):
  541. """
  542. Performs a configuration test by calling :py:func:`waflib.Configure.run_build`.
  543. For the complete list of parameters, see :py:func:`waflib.Tools.c_config.validate_c`.
  544. To force a specific compiler, pass ``compiler='c'`` or ``compiler='cxx'`` to the list of arguments
  545. Besides build targets, complete builds can be given through a build function. All files will
  546. be written to a temporary directory::
  547. def build(bld):
  548. lib_node = bld.srcnode.make_node('libdir/liblc1.c')
  549. lib_node.parent.mkdir()
  550. lib_node.write('#include <stdio.h>\\nint lib_func(void) { FILE *f = fopen("foo", "r");}\\n', 'w')
  551. bld(features='c cshlib', source=[lib_node], linkflags=conf.env.EXTRA_LDFLAGS, target='liblc')
  552. conf.check(build_fun=build, msg=msg)
  553. """
  554. self.validate_c(kw)
  555. self.start_msg(kw['msg'], **kw)
  556. ret = None
  557. try:
  558. ret = self.run_build(*k, **kw)
  559. except self.errors.ConfigurationError:
  560. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  561. if Logs.verbose > 1:
  562. raise
  563. else:
  564. self.fatal('The configuration failed')
  565. else:
  566. kw['success'] = ret
  567. ret = self.post_check(*k, **kw)
  568. if not ret:
  569. self.end_msg(kw['errmsg'], 'YELLOW', **kw)
  570. self.fatal('The configuration failed %r' % ret)
  571. else:
  572. self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
  573. return ret
  574. class test_exec(Task.Task):
  575. """
  576. A task that runs programs after they are built. See :py:func:`waflib.Tools.c_config.test_exec_fun`.
  577. """
  578. color = 'PINK'
  579. def run(self):
  580. if getattr(self.generator, 'rpath', None):
  581. if getattr(self.generator, 'define_ret', False):
  582. self.generator.bld.retval = self.generator.bld.cmd_and_log([self.inputs[0].abspath()])
  583. else:
  584. self.generator.bld.retval = self.generator.bld.exec_command([self.inputs[0].abspath()])
  585. else:
  586. env = self.env.env or {}
  587. env.update(dict(os.environ))
  588. for var in ('LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'PATH'):
  589. env[var] = self.inputs[0].parent.abspath() + os.path.pathsep + env.get(var, '')
  590. if getattr(self.generator, 'define_ret', False):
  591. self.generator.bld.retval = self.generator.bld.cmd_and_log([self.inputs[0].abspath()], env=env)
  592. else:
  593. self.generator.bld.retval = self.generator.bld.exec_command([self.inputs[0].abspath()], env=env)
  594. @feature('test_exec')
  595. @after_method('apply_link')
  596. def test_exec_fun(self):
  597. """
  598. The feature **test_exec** is used to create a task that will to execute the binary
  599. created (link task output) during the build. The exit status will be set
  600. on the build context, so only one program may have the feature *test_exec*.
  601. This is used by configuration tests::
  602. def configure(conf):
  603. conf.check(execute=True)
  604. """
  605. self.create_task('test_exec', self.link_task.outputs[0])
  606. @conf
  607. def check_cxx(self, *k, **kw):
  608. """
  609. Runs a test with a task generator of the form::
  610. conf.check(features='cxx cxxprogram', ...)
  611. """
  612. kw['compiler'] = 'cxx'
  613. return self.check(*k, **kw)
  614. @conf
  615. def check_cc(self, *k, **kw):
  616. """
  617. Runs a test with a task generator of the form::
  618. conf.check(features='c cprogram', ...)
  619. """
  620. kw['compiler'] = 'c'
  621. return self.check(*k, **kw)
  622. @conf
  623. def set_define_comment(self, key, comment):
  624. """
  625. Sets a comment that will appear in the configuration header
  626. :type key: string
  627. :type comment: string
  628. """
  629. coms = self.env.DEFINE_COMMENTS
  630. if not coms:
  631. coms = self.env.DEFINE_COMMENTS = {}
  632. coms[key] = comment or ''
  633. @conf
  634. def get_define_comment(self, key):
  635. """
  636. Returns the comment associated to a define
  637. :type key: string
  638. """
  639. coms = self.env.DEFINE_COMMENTS or {}
  640. return coms.get(key, '')
  641. @conf
  642. def define(self, key, val, quote=True, comment=''):
  643. """
  644. Stores a single define and its state into ``conf.env.DEFINES``. The value is cast to an integer (0/1).
  645. :param key: define name
  646. :type key: string
  647. :param val: value
  648. :type val: int or string
  649. :param quote: enclose strings in quotes (yes by default)
  650. :type quote: bool
  651. """
  652. assert isinstance(key, str)
  653. if not key:
  654. return
  655. if val is True:
  656. val = 1
  657. elif val in (False, None):
  658. val = 0
  659. if isinstance(val, int) or isinstance(val, float):
  660. s = '%s=%s'
  661. else:
  662. s = quote and '%s="%s"' or '%s=%s'
  663. app = s % (key, str(val))
  664. ban = key + '='
  665. lst = self.env.DEFINES
  666. for x in lst:
  667. if x.startswith(ban):
  668. lst[lst.index(x)] = app
  669. break
  670. else:
  671. self.env.append_value('DEFINES', app)
  672. self.env.append_unique(DEFKEYS, key)
  673. self.set_define_comment(key, comment)
  674. @conf
  675. def undefine(self, key, comment=''):
  676. """
  677. Removes a global define from ``conf.env.DEFINES``
  678. :param key: define name
  679. :type key: string
  680. """
  681. assert isinstance(key, str)
  682. if not key:
  683. return
  684. ban = key + '='
  685. lst = [x for x in self.env.DEFINES if not x.startswith(ban)]
  686. self.env.DEFINES = lst
  687. self.env.append_unique(DEFKEYS, key)
  688. self.set_define_comment(key, comment)
  689. @conf
  690. def define_cond(self, key, val, comment=''):
  691. """
  692. Conditionally defines a name::
  693. def configure(conf):
  694. conf.define_cond('A', True)
  695. # equivalent to:
  696. # if val: conf.define('A', 1)
  697. # else: conf.undefine('A')
  698. :param key: define name
  699. :type key: string
  700. :param val: value
  701. :type val: int or string
  702. """
  703. assert isinstance(key, str)
  704. if not key:
  705. return
  706. if val:
  707. self.define(key, 1, comment=comment)
  708. else:
  709. self.undefine(key, comment=comment)
  710. @conf
  711. def is_defined(self, key):
  712. """
  713. Indicates whether a particular define is globally set in ``conf.env.DEFINES``.
  714. :param key: define name
  715. :type key: string
  716. :return: True if the define is set
  717. :rtype: bool
  718. """
  719. assert key and isinstance(key, str)
  720. ban = key + '='
  721. for x in self.env.DEFINES:
  722. if x.startswith(ban):
  723. return True
  724. return False
  725. @conf
  726. def get_define(self, key):
  727. """
  728. Returns the value of an existing define, or None if not found
  729. :param key: define name
  730. :type key: string
  731. :rtype: string
  732. """
  733. assert key and isinstance(key, str)
  734. ban = key + '='
  735. for x in self.env.DEFINES:
  736. if x.startswith(ban):
  737. return x[len(ban):]
  738. return None
  739. @conf
  740. def have_define(self, key):
  741. """
  742. Returns a variable suitable for command-line or header use by removing invalid characters
  743. and prefixing it with ``HAVE_``
  744. :param key: define name
  745. :type key: string
  746. :return: the input key prefixed by *HAVE_* and substitute any invalid characters.
  747. :rtype: string
  748. """
  749. return (self.env.HAVE_PAT or 'HAVE_%s') % Utils.quote_define_name(key)
  750. @conf
  751. def write_config_header(self, configfile='', guard='', top=False, defines=True, headers=False, remove=True, define_prefix=''):
  752. """
  753. Writes a configuration header containing defines and includes::
  754. def configure(cnf):
  755. cnf.define('A', 1)
  756. cnf.write_config_header('config.h')
  757. This function only adds include guards (if necessary), consult
  758. :py:func:`waflib.Tools.c_config.get_config_header` for details on the body.
  759. :param configfile: path to the file to create (relative or absolute)
  760. :type configfile: string
  761. :param guard: include guard name to add, by default it is computed from the file name
  762. :type guard: string
  763. :param top: write the configuration header from the build directory (default is from the current path)
  764. :type top: bool
  765. :param defines: add the defines (yes by default)
  766. :type defines: bool
  767. :param headers: add #include in the file
  768. :type headers: bool
  769. :param remove: remove the defines after they are added (yes by default, works like in autoconf)
  770. :type remove: bool
  771. :type define_prefix: string
  772. :param define_prefix: prefix all the defines in the file with a particular prefix
  773. """
  774. if not configfile:
  775. configfile = WAF_CONFIG_H
  776. waf_guard = guard or 'W_%s_WAF' % Utils.quote_define_name(configfile)
  777. node = top and self.bldnode or self.path.get_bld()
  778. node = node.make_node(configfile)
  779. node.parent.mkdir()
  780. lst = ['/* WARNING! All changes made to this file will be lost! */\n']
  781. lst.append('#ifndef %s\n#define %s\n' % (waf_guard, waf_guard))
  782. lst.append(self.get_config_header(defines, headers, define_prefix=define_prefix))
  783. lst.append('\n#endif /* %s */\n' % waf_guard)
  784. node.write('\n'.join(lst))
  785. # config files must not be removed on "waf clean"
  786. self.env.append_unique(Build.CFG_FILES, [node.abspath()])
  787. if remove:
  788. for key in self.env[DEFKEYS]:
  789. self.undefine(key)
  790. self.env[DEFKEYS] = []
  791. @conf
  792. def get_config_header(self, defines=True, headers=False, define_prefix=''):
  793. """
  794. Creates the contents of a ``config.h`` file from the defines and includes
  795. set in conf.env.define_key / conf.env.include_key. No include guards are added.
  796. A prelude will be added from the variable env.WAF_CONFIG_H_PRELUDE if provided. This
  797. can be used to insert complex macros or include guards::
  798. def configure(conf):
  799. conf.env.WAF_CONFIG_H_PRELUDE = '#include <unistd.h>\\n'
  800. conf.write_config_header('config.h')
  801. :param defines: write the defines values
  802. :type defines: bool
  803. :param headers: write include entries for each element in self.env.INCKEYS
  804. :type headers: bool
  805. :type define_prefix: string
  806. :param define_prefix: prefix all the defines with a particular prefix
  807. :return: the contents of a ``config.h`` file
  808. :rtype: string
  809. """
  810. lst = []
  811. if self.env.WAF_CONFIG_H_PRELUDE:
  812. lst.append(self.env.WAF_CONFIG_H_PRELUDE)
  813. if headers:
  814. for x in self.env[INCKEYS]:
  815. lst.append('#include <%s>' % x)
  816. if defines:
  817. tbl = {}
  818. for k in self.env.DEFINES:
  819. a, _, b = k.partition('=')
  820. tbl[a] = b
  821. for k in self.env[DEFKEYS]:
  822. caption = self.get_define_comment(k)
  823. if caption:
  824. caption = ' /* %s */' % caption
  825. try:
  826. txt = '#define %s%s %s%s' % (define_prefix, k, tbl[k], caption)
  827. except KeyError:
  828. txt = '/* #undef %s%s */%s' % (define_prefix, k, caption)
  829. lst.append(txt)
  830. return "\n".join(lst)
  831. @conf
  832. def cc_add_flags(conf):
  833. """
  834. Adds CFLAGS / CPPFLAGS from os.environ to conf.env
  835. """
  836. conf.add_os_flags('CPPFLAGS', dup=False)
  837. conf.add_os_flags('CFLAGS', dup=False)
  838. @conf
  839. def cxx_add_flags(conf):
  840. """
  841. Adds CXXFLAGS / CPPFLAGS from os.environ to conf.env
  842. """
  843. conf.add_os_flags('CPPFLAGS', dup=False)
  844. conf.add_os_flags('CXXFLAGS', dup=False)
  845. @conf
  846. def link_add_flags(conf):
  847. """
  848. Adds LINKFLAGS / LDFLAGS from os.environ to conf.env
  849. """
  850. conf.add_os_flags('LINKFLAGS', dup=False)
  851. conf.add_os_flags('LDFLAGS', dup=False)
  852. @conf
  853. def cc_load_tools(conf):
  854. """
  855. Loads the Waf c extensions
  856. """
  857. if not conf.env.DEST_OS:
  858. conf.env.DEST_OS = Utils.unversioned_sys_platform()
  859. conf.load('c')
  860. @conf
  861. def cxx_load_tools(conf):
  862. """
  863. Loads the Waf c++ extensions
  864. """
  865. if not conf.env.DEST_OS:
  866. conf.env.DEST_OS = Utils.unversioned_sys_platform()
  867. conf.load('cxx')
  868. @conf
  869. def get_cc_version(conf, cc, gcc=False, icc=False, clang=False):
  870. """
  871. Runs the preprocessor to determine the gcc/icc/clang version
  872. The variables CC_VERSION, DEST_OS, DEST_BINFMT and DEST_CPU will be set in *conf.env*
  873. :raise: :py:class:`waflib.Errors.ConfigurationError`
  874. """
  875. cmd = cc + ['-dM', '-E', '-']
  876. env = conf.env.env or None
  877. try:
  878. out, err = conf.cmd_and_log(cmd, output=0, input='\n'.encode(), env=env)
  879. except Errors.WafError:
  880. conf.fatal('Could not determine the compiler version %r' % cmd)
  881. if gcc:
  882. if out.find('__INTEL_COMPILER') >= 0:
  883. conf.fatal('The intel compiler pretends to be gcc')
  884. if out.find('__GNUC__') < 0 and out.find('__clang__') < 0:
  885. conf.fatal('Could not determine the compiler type')
  886. if icc and out.find('__INTEL_COMPILER') < 0:
  887. conf.fatal('Not icc/icpc')
  888. if clang and out.find('__clang__') < 0:
  889. conf.fatal('Not clang/clang++')
  890. if not clang and out.find('__clang__') >= 0:
  891. conf.fatal('Could not find gcc/g++ (only Clang), if renamed try eg: CC=gcc48 CXX=g++48 waf configure')
  892. k = {}
  893. if icc or gcc or clang:
  894. out = out.splitlines()
  895. for line in out:
  896. lst = shlex.split(line)
  897. if len(lst)>2:
  898. key = lst[1]
  899. val = lst[2]
  900. k[key] = val
  901. def isD(var):
  902. return var in k
  903. # Some documentation is available at http://predef.sourceforge.net
  904. # The names given to DEST_OS must match what Utils.unversioned_sys_platform() returns.
  905. if not conf.env.DEST_OS:
  906. conf.env.DEST_OS = ''
  907. for i in MACRO_TO_DESTOS:
  908. if isD(i):
  909. conf.env.DEST_OS = MACRO_TO_DESTOS[i]
  910. break
  911. else:
  912. if isD('__APPLE__') and isD('__MACH__'):
  913. conf.env.DEST_OS = 'darwin'
  914. elif isD('__unix__'): # unix must be tested last as it's a generic fallback
  915. conf.env.DEST_OS = 'generic'
  916. if isD('__ELF__'):
  917. conf.env.DEST_BINFMT = 'elf'
  918. elif isD('__WINNT__') or isD('__CYGWIN__') or isD('_WIN32'):
  919. conf.env.DEST_BINFMT = 'pe'
  920. if not conf.env.IMPLIBDIR:
  921. conf.env.IMPLIBDIR = conf.env.LIBDIR # for .lib or .dll.a files
  922. conf.env.LIBDIR = conf.env.BINDIR
  923. elif isD('__APPLE__'):
  924. conf.env.DEST_BINFMT = 'mac-o'
  925. if not conf.env.DEST_BINFMT:
  926. # Infer the binary format from the os name.
  927. conf.env.DEST_BINFMT = Utils.destos_to_binfmt(conf.env.DEST_OS)
  928. for i in MACRO_TO_DEST_CPU:
  929. if isD(i):
  930. conf.env.DEST_CPU = MACRO_TO_DEST_CPU[i]
  931. break
  932. Logs.debug('ccroot: dest platform: ' + ' '.join([conf.env[x] or '?' for x in ('DEST_OS', 'DEST_BINFMT', 'DEST_CPU')]))
  933. if icc:
  934. ver = k['__INTEL_COMPILER']
  935. conf.env.CC_VERSION = (ver[:-2], ver[-2], ver[-1])
  936. else:
  937. if isD('__clang__') and isD('__clang_major__'):
  938. conf.env.CC_VERSION = (k['__clang_major__'], k['__clang_minor__'], k['__clang_patchlevel__'])
  939. else:
  940. # older clang versions and gcc
  941. conf.env.CC_VERSION = (k['__GNUC__'], k['__GNUC_MINOR__'], k.get('__GNUC_PATCHLEVEL__', '0'))
  942. return k
  943. @conf
  944. def get_xlc_version(conf, cc):
  945. """
  946. Returns the Aix compiler version
  947. :raise: :py:class:`waflib.Errors.ConfigurationError`
  948. """
  949. cmd = cc + ['-qversion']
  950. try:
  951. out, err = conf.cmd_and_log(cmd, output=0)
  952. except Errors.WafError:
  953. conf.fatal('Could not find xlc %r' % cmd)
  954. # the intention is to catch the 8.0 in "IBM XL C/C++ Enterprise Edition V8.0 for AIX..."
  955. for v in (r"IBM XL C/C\+\+.* V(?P<major>\d*)\.(?P<minor>\d*)",):
  956. version_re = re.compile(v, re.I).search
  957. match = version_re(out or err)
  958. if match:
  959. k = match.groupdict()
  960. conf.env.CC_VERSION = (k['major'], k['minor'])
  961. break
  962. else:
  963. conf.fatal('Could not determine the XLC version.')
  964. @conf
  965. def get_suncc_version(conf, cc):
  966. """
  967. Returns the Sun compiler version
  968. :raise: :py:class:`waflib.Errors.ConfigurationError`
  969. """
  970. cmd = cc + ['-V']
  971. try:
  972. out, err = conf.cmd_and_log(cmd, output=0)
  973. except Errors.WafError as e:
  974. # Older versions of the compiler exit with non-zero status when reporting their version
  975. if not (hasattr(e, 'returncode') and hasattr(e, 'stdout') and hasattr(e, 'stderr')):
  976. conf.fatal('Could not find suncc %r' % cmd)
  977. out = e.stdout
  978. err = e.stderr
  979. version = (out or err)
  980. version = version.splitlines()[0]
  981. # cc: Sun C 5.10 SunOS_i386 2009/06/03
  982. # cc: Studio 12.5 Sun C++ 5.14 SunOS_sparc Beta 2015/11/17
  983. # cc: WorkShop Compilers 5.0 98/12/15 C 5.0
  984. version_re = re.compile(r'cc: (studio.*?|\s+)?(sun\s+(c\+\+|c)|(WorkShop\s+Compilers))?\s+(?P<major>\d*)\.(?P<minor>\d*)', re.I).search
  985. match = version_re(version)
  986. if match:
  987. k = match.groupdict()
  988. conf.env.CC_VERSION = (k['major'], k['minor'])
  989. else:
  990. conf.fatal('Could not determine the suncc version.')
  991. # ============ the --as-needed flag should added during the configuration, not at runtime =========
  992. @conf
  993. def add_as_needed(self):
  994. """
  995. Adds ``--as-needed`` to the *LINKFLAGS*
  996. On some platforms, it is a default flag. In some cases (e.g., in NS-3) it is necessary to explicitly disable this feature with `-Wl,--no-as-needed` flag.
  997. """
  998. if self.env.DEST_BINFMT == 'elf' and 'gcc' in (self.env.CXX_NAME, self.env.CC_NAME):
  999. self.env.append_unique('LINKFLAGS', '-Wl,--as-needed')
  1000. # ============ parallel configuration
  1001. class cfgtask(Task.Task):
  1002. """
  1003. A task that executes build configuration tests (calls conf.check)
  1004. Make sure to use locks if concurrent access to the same conf.env data is necessary.
  1005. """
  1006. def __init__(self, *k, **kw):
  1007. Task.Task.__init__(self, *k, **kw)
  1008. self.run_after = set()
  1009. def display(self):
  1010. return ''
  1011. def runnable_status(self):
  1012. for x in self.run_after:
  1013. if not x.hasrun:
  1014. return Task.ASK_LATER
  1015. return Task.RUN_ME
  1016. def uid(self):
  1017. return Utils.SIG_NIL
  1018. def signature(self):
  1019. return Utils.SIG_NIL
  1020. def run(self):
  1021. conf = self.conf
  1022. bld = Build.BuildContext(top_dir=conf.srcnode.abspath(), out_dir=conf.bldnode.abspath())
  1023. bld.env = conf.env
  1024. bld.init_dirs()
  1025. bld.in_msg = 1 # suppress top-level start_msg
  1026. bld.logger = self.logger
  1027. bld.multicheck_task = self
  1028. args = self.args
  1029. try:
  1030. if 'func' in args:
  1031. bld.test(build_fun=args['func'],
  1032. msg=args.get('msg', ''),
  1033. okmsg=args.get('okmsg', ''),
  1034. errmsg=args.get('errmsg', ''),
  1035. )
  1036. else:
  1037. args['multicheck_mandatory'] = args.get('mandatory', True)
  1038. args['mandatory'] = True
  1039. try:
  1040. bld.check(**args)
  1041. finally:
  1042. args['mandatory'] = args['multicheck_mandatory']
  1043. except Exception:
  1044. return 1
  1045. def process(self):
  1046. Task.Task.process(self)
  1047. if 'msg' in self.args:
  1048. with self.generator.bld.multicheck_lock:
  1049. self.conf.start_msg(self.args['msg'])
  1050. if self.hasrun == Task.NOT_RUN:
  1051. self.conf.end_msg('test cancelled', 'YELLOW')
  1052. elif self.hasrun != Task.SUCCESS:
  1053. self.conf.end_msg(self.args.get('errmsg', 'no'), 'YELLOW')
  1054. else:
  1055. self.conf.end_msg(self.args.get('okmsg', 'yes'), 'GREEN')
  1056. @conf
  1057. def multicheck(self, *k, **kw):
  1058. """
  1059. Runs configuration tests in parallel; results are printed sequentially at the end of the build
  1060. but each test must provide its own msg value to display a line::
  1061. def test_build(ctx):
  1062. ctx.in_msg = True # suppress console outputs
  1063. ctx.check_large_file(mandatory=False)
  1064. conf.multicheck(
  1065. {'header_name':'stdio.h', 'msg':'... stdio', 'uselib_store':'STDIO', 'global_define':False},
  1066. {'header_name':'xyztabcd.h', 'msg':'... optional xyztabcd.h', 'mandatory': False},
  1067. {'header_name':'stdlib.h', 'msg':'... stdlib', 'okmsg': 'aye', 'errmsg': 'nope'},
  1068. {'func': test_build, 'msg':'... testing an arbitrary build function', 'okmsg':'ok'},
  1069. msg = 'Checking for headers in parallel',
  1070. mandatory = True, # mandatory tests raise an error at the end
  1071. run_all_tests = True, # try running all tests
  1072. )
  1073. The configuration tests may modify the values in conf.env in any order, and the define
  1074. values can affect configuration tests being executed. It is hence recommended
  1075. to provide `uselib_store` values with `global_define=False` to prevent such issues.
  1076. """
  1077. self.start_msg(kw.get('msg', 'Executing %d configuration tests' % len(k)), **kw)
  1078. # Force a copy so that threads append to the same list at least
  1079. # no order is guaranteed, but the values should not disappear at least
  1080. for var in ('DEFINES', DEFKEYS):
  1081. self.env.append_value(var, [])
  1082. self.env.DEFINE_COMMENTS = self.env.DEFINE_COMMENTS or {}
  1083. # define a task object that will execute our tests
  1084. class par(object):
  1085. def __init__(self):
  1086. self.keep = False
  1087. self.task_sigs = {}
  1088. self.progress_bar = 0
  1089. def total(self):
  1090. return len(tasks)
  1091. def to_log(self, *k, **kw):
  1092. return
  1093. bld = par()
  1094. bld.keep = kw.get('run_all_tests', True)
  1095. bld.imp_sigs = {}
  1096. tasks = []
  1097. id_to_task = {}
  1098. for dct in k:
  1099. x = Task.classes['cfgtask'](bld=bld, env=None)
  1100. tasks.append(x)
  1101. x.args = dct
  1102. x.bld = bld
  1103. x.conf = self
  1104. x.args = dct
  1105. # bind a logger that will keep the info in memory
  1106. x.logger = Logs.make_mem_logger(str(id(x)), self.logger)
  1107. if 'id' in dct:
  1108. id_to_task[dct['id']] = x
  1109. # second pass to set dependencies with after_test/before_test
  1110. for x in tasks:
  1111. for key in Utils.to_list(x.args.get('before_tests', [])):
  1112. tsk = id_to_task[key]
  1113. if not tsk:
  1114. raise ValueError('No test named %r' % key)
  1115. tsk.run_after.add(x)
  1116. for key in Utils.to_list(x.args.get('after_tests', [])):
  1117. tsk = id_to_task[key]
  1118. if not tsk:
  1119. raise ValueError('No test named %r' % key)
  1120. x.run_after.add(tsk)
  1121. def it():
  1122. yield tasks
  1123. while 1:
  1124. yield []
  1125. bld.producer = p = Runner.Parallel(bld, Options.options.jobs)
  1126. bld.multicheck_lock = Utils.threading.Lock()
  1127. p.biter = it()
  1128. self.end_msg('started')
  1129. p.start()
  1130. # flush the logs in order into the config.log
  1131. for x in tasks:
  1132. x.logger.memhandler.flush()
  1133. self.start_msg('-> processing test results')
  1134. if p.error:
  1135. for x in p.error:
  1136. if getattr(x, 'err_msg', None):
  1137. self.to_log(x.err_msg)
  1138. self.end_msg('fail', color='RED')
  1139. raise Errors.WafError('There is an error in the library, read config.log for more information')
  1140. failure_count = 0
  1141. for x in tasks:
  1142. if x.hasrun not in (Task.SUCCESS, Task.NOT_RUN):
  1143. failure_count += 1
  1144. if failure_count:
  1145. self.end_msg(kw.get('errmsg', '%s test failed' % failure_count), color='YELLOW', **kw)
  1146. else:
  1147. self.end_msg('all ok', **kw)
  1148. for x in tasks:
  1149. if x.hasrun != Task.SUCCESS:
  1150. if x.args.get('mandatory', True):
  1151. self.fatal(kw.get('fatalmsg') or 'One of the tests has failed, read config.log for more information')
  1152. @conf
  1153. def check_gcc_o_space(self, mode='c'):
  1154. if int(self.env.CC_VERSION[0]) > 4:
  1155. # this is for old compilers
  1156. return
  1157. self.env.stash()
  1158. if mode == 'c':
  1159. self.env.CCLNK_TGT_F = ['-o', '']
  1160. elif mode == 'cxx':
  1161. self.env.CXXLNK_TGT_F = ['-o', '']
  1162. features = '%s %sshlib' % (mode, mode)
  1163. try:
  1164. self.check(msg='Checking if the -o link must be split from arguments', fragment=SNIP_EMPTY_PROGRAM, features=features)
  1165. except self.errors.ConfigurationError:
  1166. self.env.revert()
  1167. else:
  1168. self.env.commit()