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.

1238 lines
36KB

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