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.

1371 lines
41KB

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