conformtest.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. #!/usr/bin/python3
  2. # Check header contents against the given standard.
  3. # Copyright (C) 2018-2019 Free Software Foundation, Inc.
  4. # This file is part of the GNU C Library.
  5. #
  6. # The GNU C Library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # The GNU C Library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with the GNU C Library; if not, see
  18. # <http://www.gnu.org/licenses/>.
  19. import argparse
  20. import fnmatch
  21. import os.path
  22. import re
  23. import subprocess
  24. import sys
  25. import tempfile
  26. import glibcconform
  27. class CompileSubTest(object):
  28. """A compilation subtest."""
  29. def __init__(self, name, text):
  30. """Initialize a CompileSubTest object."""
  31. self.run_early = False
  32. self.name = name
  33. self.text = text
  34. def run(self, header_tests):
  35. """Run a compilation subtest."""
  36. header_tests.compile_test(self.name, self.text)
  37. class ExecuteSubTest(object):
  38. """An execution subtest."""
  39. def __init__(self, name, text):
  40. """Initialize an ExecuteSubTest object."""
  41. self.run_early = False
  42. self.name = name
  43. self.text = text
  44. def run(self, header_tests):
  45. """Run an execution subtest."""
  46. header_tests.execute_test(self.name, self.text)
  47. class ElementTest(object):
  48. """Test for an element of a structure or union type."""
  49. def __init__(self, dummy, type_name, member_type, member_name, *rest):
  50. """Initialize an ElementTest object."""
  51. self.type_name = type_name
  52. self.member_type = member_type
  53. self.member_name = member_name
  54. self.rest = ' '.join(rest)
  55. self.allow_name = self.member_name
  56. def gen_subtests(self):
  57. """Generate subtests for an ElementTest."""
  58. text = ('%(type_name)s a_%(num)d;\n'
  59. '%(type_name)s b_%(num)d;\n'
  60. 'extern void xyzzy_%(num)d '
  61. '(__typeof__ (&b_%(num)d.%(member_name)s), '
  62. '__typeof__ (&a_%(num)d.%(member_name)s), unsigned);\n'
  63. 'void foobarbaz_%(num)d (void) {\n'
  64. 'xyzzy_%(num)d (&a_%(num)d.%(member_name)s, '
  65. '&b_%(num)d.%(member_name)s, '
  66. 'sizeof (a_%(num)d.%(member_name)s));\n'
  67. '}\n'
  68. % vars(self))
  69. self.subtests.append(CompileSubTest(
  70. 'Availability of member %s' % self.member_name,
  71. text))
  72. text = ('%(type_name)s a2_%(num)d;\n'
  73. 'extern %(member_type)s b2_%(num)d%(rest)s;\n'
  74. 'extern __typeof__ (a2_%(num)d.%(member_name)s) b2_%(num)d;\n'
  75. % vars(self))
  76. self.subtests.append(CompileSubTest(
  77. 'Type of member %s' % self.member_name,
  78. text))
  79. class ConstantTest(object):
  80. """Test for a macro or constant."""
  81. def __init__(self, symbol_type, symbol, extra1=None, extra2=None,
  82. extra3=None):
  83. """Initialize a ConstantTest object."""
  84. self.symbol_type = symbol_type
  85. self.symbol = symbol
  86. # A comparison operation may be specified without a type.
  87. if extra2 is not None and extra3 is None:
  88. self.c_type = None
  89. self.op = extra1
  90. self.value = extra2
  91. else:
  92. self.c_type = extra1
  93. self.op = extra2
  94. self.value = extra3
  95. self.allow_name = self.symbol
  96. def gen_subtests(self):
  97. """Generate subtests for a ConstantTest."""
  98. if 'macro' in self.symbol_type:
  99. text = ('#ifndef %(symbol)s\n'
  100. '# error "Macro %(symbol)s not defined"\n'
  101. '#endif\n'
  102. % vars(self))
  103. self.subtests.append(CompileSubTest(
  104. 'Availability of macro %s' % self.symbol,
  105. text))
  106. if 'constant' in self.symbol_type:
  107. text = ('__typeof__ (%(symbol)s) a_%(num)d = %(symbol)s;\n'
  108. % vars(self))
  109. self.subtests.append(CompileSubTest(
  110. 'Availability of constant %s' % self.symbol,
  111. text))
  112. if self.symbol_type == 'macro-int-constant':
  113. sym_bits_def_neg = ''.join(
  114. '# if %s & (1LL << %d)\n'
  115. '# define conformtest_%d_bit_%d 0LL\n'
  116. '# else\n'
  117. '# define conformtest_%d_bit_%d (1LL << %d)\n'
  118. '# endif\n'
  119. % (self.symbol, i, self.num, i, self.num, i, i)
  120. for i in range(63))
  121. sym_bits_or_neg = '|'.join('conformtest_%d_bit_%d' % (self.num, i)
  122. for i in range(63))
  123. sym_bits_def_pos = ''.join(
  124. '# if %s & (1ULL << %d)\n'
  125. '# define conformtest_%d_bit_%d (1ULL << %d)\n'
  126. '# else\n'
  127. '# define conformtest_%d_bit_%d 0ULL\n'
  128. '# endif\n'
  129. % (self.symbol, i, self.num, i, i, self.num, i)
  130. for i in range(64))
  131. sym_bits_or_pos = '|'.join('conformtest_%d_bit_%d' % (self.num, i)
  132. for i in range(64))
  133. text = ('#if %s < 0\n'
  134. '# define conformtest_%d_negative 1\n'
  135. '%s'
  136. '# define conformtest_%d_value ~(%s)\n'
  137. '#else\n'
  138. '# define conformtest_%d_negative 0\n'
  139. '%s'
  140. '# define conformtest_%d_value (%s)\n'
  141. '#endif\n'
  142. '_Static_assert (((%s < 0) == conformtest_%d_negative) '
  143. '&& (%s == conformtest_%d_value), '
  144. '"value match inside and outside #if");\n'
  145. % (self.symbol, self.num, sym_bits_def_neg, self.num,
  146. sym_bits_or_neg, self.num, sym_bits_def_pos, self.num,
  147. sym_bits_or_pos, self.symbol, self.num, self.symbol,
  148. self.num))
  149. self.subtests.append(CompileSubTest(
  150. '#if usability of symbol %s'% self.symbol,
  151. text))
  152. if self.c_type is not None:
  153. if self.c_type.startswith('promoted:'):
  154. c_type = self.c_type[len('promoted:'):]
  155. text = ('__typeof__ ((%s) 0 + (%s) 0) a2_%d;\n'
  156. % (c_type, c_type, self.num))
  157. else:
  158. text = '__typeof__ ((%s) 0) a2_%d;\n' % (self.c_type, self.num)
  159. text += 'extern __typeof__ (%s) a2_%d;\n' % (self.symbol, self.num)
  160. self.subtests.append(CompileSubTest(
  161. 'Type of symbol %s' % self.symbol,
  162. text))
  163. if self.op is not None:
  164. text = ('_Static_assert (%(symbol)s %(op)s %(value)s, '
  165. '"value constraint");\n'
  166. % vars(self))
  167. self.subtests.append(CompileSubTest(
  168. 'Value of symbol %s' % self.symbol,
  169. text))
  170. class SymbolTest(object):
  171. """Test for a symbol (not a compile-time constant)."""
  172. def __init__(self, dummy, symbol, value=None):
  173. """Initialize a SymbolTest object."""
  174. self.symbol = symbol
  175. self.value = value
  176. self.allow_name = self.symbol
  177. def gen_subtests(self):
  178. """Generate subtests for a SymbolTest."""
  179. text = ('void foobarbaz_%(num)d (void) {\n'
  180. '__typeof__ (%(symbol)s) a_%(num)d = %(symbol)s;\n'
  181. '}\n'
  182. % vars(self))
  183. self.subtests.append(CompileSubTest(
  184. 'Availability of symbol %s' % self.symbol,
  185. text))
  186. if self.value is not None:
  187. text = ('int main (void) { return %(symbol)s != %(symbol)s; }\n'
  188. % vars(self))
  189. self.subtests.append(ExecuteSubTest(
  190. 'Value of symbol %s' % self.symbol,
  191. text))
  192. class TypeTest(object):
  193. """Test for a type name."""
  194. def __init__(self, dummy, type_name):
  195. """Initialize a TypeTest object."""
  196. self.type_name = type_name
  197. if type_name.startswith('struct '):
  198. self.allow_name = type_name[len('struct '):]
  199. self.maybe_opaque = False
  200. elif type_name.startswith('union '):
  201. self.allow_name = type_name[len('union '):]
  202. self.maybe_opaque = False
  203. else:
  204. self.allow_name = type_name
  205. self.maybe_opaque = True
  206. def gen_subtests(self):
  207. """Generate subtests for a TypeTest."""
  208. text = ('%s %sa_%d;\n'
  209. % (self.type_name, '*' if self.maybe_opaque else '', self.num))
  210. self.subtests.append(CompileSubTest(
  211. 'Availability of type %s' % self.type_name,
  212. text))
  213. class TagTest(object):
  214. """Test for a tag name."""
  215. def __init__(self, dummy, type_name):
  216. """Initialize a TagTest object."""
  217. self.type_name = type_name
  218. if type_name.startswith('struct '):
  219. self.allow_name = type_name[len('struct '):]
  220. elif type_name.startswith('union '):
  221. self.allow_name = type_name[len('union '):]
  222. else:
  223. raise ValueError('unexpected kind of tag: %s' % type_name)
  224. def gen_subtests(self):
  225. """Generate subtests for a TagTest."""
  226. # If the tag is not declared, these function prototypes have
  227. # incompatible types.
  228. text = ('void foo_%(num)d (%(type_name)s *);\n'
  229. 'void foo_%(num)d (%(type_name)s *);\n'
  230. % vars(self))
  231. self.subtests.append(CompileSubTest(
  232. 'Availability of tag %s' % self.type_name,
  233. text))
  234. class FunctionTest(object):
  235. """Test for a function."""
  236. def __init__(self, dummy, return_type, function_name, *args):
  237. """Initialize a FunctionTest object."""
  238. self.function_name_full = function_name
  239. self.args = ' '.join(args)
  240. if function_name.startswith('(*'):
  241. # Function returning a pointer to function.
  242. self.return_type = '%s (*' % return_type
  243. self.function_name = function_name[len('(*'):]
  244. else:
  245. self.return_type = return_type
  246. self.function_name = function_name
  247. self.allow_name = self.function_name
  248. def gen_subtests(self):
  249. """Generate subtests for a FunctionTest."""
  250. text = ('%(return_type)s (*foobarbaz_%(num)d) %(args)s '
  251. '= %(function_name)s;\n'
  252. % vars(self))
  253. self.subtests.append(CompileSubTest(
  254. 'Availability of function %s' % self.function_name,
  255. text))
  256. text = ('extern %(return_type)s (*foobarbaz2_%(num)d) %(args)s;\n'
  257. 'extern __typeof__ (&%(function_name)s) foobarbaz2_%(num)d;\n'
  258. % vars(self))
  259. self.subtests.append(CompileSubTest(
  260. 'Type of function %s' % self.function_name,
  261. text))
  262. class VariableTest(object):
  263. """Test for a variable."""
  264. def __init__(self, dummy, var_type, var_name, *rest):
  265. """Initialize a VariableTest object."""
  266. self.var_type = var_type
  267. self.var_name = var_name
  268. self.rest = ' '.join(rest)
  269. self.allow_name = var_name
  270. def gen_subtests(self):
  271. """Generate subtests for a VariableTest."""
  272. text = ('typedef %(var_type)s xyzzy_%(num)d%(rest)s;\n'
  273. 'xyzzy_%(num)d *foobarbaz_%(num)d = &%(var_name)s;\n'
  274. % vars(self))
  275. self.subtests.append(CompileSubTest(
  276. 'Availability of variable %s' % self.var_name,
  277. text))
  278. text = ('extern %(var_type)s %(var_name)s%(rest)s;\n'
  279. % vars(self))
  280. self.subtests.append(CompileSubTest(
  281. 'Type of variable %s' % self.var_name,
  282. text))
  283. class MacroFunctionTest(object):
  284. """Test for a possibly macro-only function."""
  285. def __init__(self, dummy, return_type, function_name, *args):
  286. """Initialize a MacroFunctionTest object."""
  287. self.return_type = return_type
  288. self.function_name = function_name
  289. self.args = ' '.join(args)
  290. self.allow_name = function_name
  291. def gen_subtests(self):
  292. """Generate subtests for a MacroFunctionTest."""
  293. text = ('#ifndef %(function_name)s\n'
  294. '%(return_type)s (*foobarbaz_%(num)d) %(args)s '
  295. '= %(function_name)s;\n'
  296. '#endif\n'
  297. % vars(self))
  298. self.subtests.append(CompileSubTest(
  299. 'Availability of macro %s' % self.function_name,
  300. text))
  301. text = ('#ifndef %(function_name)s\n'
  302. 'extern %(return_type)s (*foobarbaz2_%(num)d) %(args)s;\n'
  303. 'extern __typeof__ (&%(function_name)s) foobarbaz2_%(num)d;\n'
  304. '#endif\n'
  305. % vars(self))
  306. self.subtests.append(CompileSubTest(
  307. 'Type of macro %s' % self.function_name,
  308. text))
  309. class MacroStrTest(object):
  310. """Test for a string-valued macro."""
  311. def __init__(self, dummy, macro_name, value):
  312. """Initialize a MacroStrTest object."""
  313. self.macro_name = macro_name
  314. self.value = value
  315. self.allow_name = macro_name
  316. def gen_subtests(self):
  317. """Generate subtests for a MacroStrTest."""
  318. text = ('#ifndef %(macro_name)s\n'
  319. '# error "Macro %(macro_name)s not defined"\n'
  320. '#endif\n'
  321. % vars(self))
  322. self.subtests.append(CompileSubTest(
  323. 'Availability of macro %s' % self.macro_name,
  324. text))
  325. # We can't include <string.h> here.
  326. text = ('extern int (strcmp)(const char *, const char *);\n'
  327. 'int main (void) { return (strcmp) (%(macro_name)s, '
  328. '%(value)s) != 0; }\n'
  329. % vars(self))
  330. self.subtests.append(ExecuteSubTest(
  331. 'Value of macro %s' % self.macro_name,
  332. text))
  333. class HeaderTests(object):
  334. """The set of tests run for a header."""
  335. def __init__(self, header, standard, cc, flags, cross, xfail):
  336. """Initialize a HeaderTests object."""
  337. self.header = header
  338. self.standard = standard
  339. self.cc = cc
  340. self.flags = flags
  341. self.cross = cross
  342. self.xfail_str = xfail
  343. self.cflags_namespace = ('%s -fno-builtin %s -D_ISOMAC'
  344. % (flags, glibcconform.CFLAGS[standard]))
  345. # When compiling the conformance test programs, use of
  346. # __attribute__ in headers is disabled because of attributes
  347. # that affect the types of functions as seen by typeof.
  348. self.cflags = "%s '-D__attribute__(x)='" % self.cflags_namespace
  349. self.tests = []
  350. self.allow = set()
  351. self.allow_fnmatch = set()
  352. self.headers_handled = set()
  353. self.num_tests = 0
  354. self.total = 0
  355. self.skipped = 0
  356. self.errors = 0
  357. self.xerrors = 0
  358. def add_allow(self, name, pattern_ok):
  359. """Add an identifier as an allowed token for this header.
  360. If pattern_ok, fnmatch patterns are OK as well as
  361. identifiers.
  362. """
  363. if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', name):
  364. self.allow.add(name)
  365. elif pattern_ok:
  366. self.allow_fnmatch.add(name)
  367. else:
  368. raise ValueError('bad identifier: %s' % name)
  369. def check_token(self, bad_tokens, token):
  370. """Check whether an identifier token is allowed, and record it in
  371. bad_tokens if not.
  372. """
  373. if token.startswith('_'):
  374. return
  375. if token in glibcconform.KEYWORDS[self.standard]:
  376. return
  377. if token in self.allow:
  378. return
  379. for pattern in self.allow_fnmatch:
  380. if fnmatch.fnmatch(token, pattern):
  381. return
  382. bad_tokens.add(token)
  383. def handle_test_line(self, line, allow):
  384. """Handle a single line in the test data.
  385. If allow is true, the header is one specified in allow-header
  386. and so tests are marked as allowed for namespace purposes but
  387. otherwise ignored.
  388. """
  389. orig_line = line
  390. xfail = False
  391. if line.startswith('xfail-'):
  392. xfail = True
  393. line = line[len('xfail-'):]
  394. else:
  395. match = re.match(r'xfail\[(.*?)\]-(.*)', line)
  396. if match:
  397. xfail_cond = match.group(1)
  398. line = match.group(2)
  399. # "xfail[cond]-" or "xfail[cond1|cond2|...]-" means a
  400. # failure of the test is allowed if any of the listed
  401. # conditions are in the --xfail command-line option
  402. # argument.
  403. if self.xfail_str and re.search(r'\b(%s)\b' % xfail_cond,
  404. self.xfail_str):
  405. xfail = True
  406. optional = False
  407. if line.startswith('optional-'):
  408. optional = True
  409. line = line[len('optional-'):]
  410. # Tokens in test data are space-separated, except for {...}
  411. # tokens that may contain spaces.
  412. tokens = []
  413. while line:
  414. match = re.match(r'\{(.*?)\}(.*)', line)
  415. if match:
  416. tokens.append(match.group(1))
  417. line = match.group(2)
  418. else:
  419. match = re.match(r'([^ ]*)(.*)', line)
  420. tokens.append(match.group(1))
  421. line = match.group(2)
  422. line = line.strip()
  423. if tokens[0] == 'allow-header':
  424. if len(tokens) != 2 or xfail or optional:
  425. raise ValueError('bad allow-header line: %s' % orig_line)
  426. if tokens[1] not in self.headers_handled:
  427. self.load_tests(tokens[1], True)
  428. return
  429. if tokens[0] == 'allow':
  430. if len(tokens) != 2 or xfail or optional:
  431. raise ValueError('bad allow line: %s' % orig_line)
  432. self.add_allow(tokens[1], True)
  433. return
  434. test_classes = {'element': ElementTest,
  435. 'macro': ConstantTest,
  436. 'constant': ConstantTest,
  437. 'macro-constant': ConstantTest,
  438. 'macro-int-constant': ConstantTest,
  439. 'symbol': SymbolTest,
  440. 'type': TypeTest,
  441. 'tag': TagTest,
  442. 'function': FunctionTest,
  443. 'variable': VariableTest,
  444. 'macro-function': MacroFunctionTest,
  445. 'macro-str': MacroStrTest}
  446. test = test_classes[tokens[0]](*tokens)
  447. test.xfail = xfail
  448. test.optional = optional
  449. test.num = self.num_tests
  450. test.subtests = []
  451. self.num_tests += 1
  452. self.add_allow(test.allow_name, False)
  453. if not allow:
  454. test.gen_subtests()
  455. self.tests.append(test)
  456. def load_tests(self, header, allow):
  457. """Load tests of a header.
  458. If allow is true, the header is one specified in allow-header
  459. and so tests are marked as allowed for namespace purposes but
  460. otherwise ignored.
  461. """
  462. self.headers_handled.add(header)
  463. header_s = header.replace('/', '_')
  464. temp_file = os.path.join(self.temp_dir, 'header-data-%s' % header_s)
  465. cmd = ('%s -E -D%s -std=c99 -x c data/%s-data > %s'
  466. % (self.cc, self.standard, header, temp_file))
  467. subprocess.check_call(cmd, shell=True)
  468. with open(temp_file, 'r') as tests:
  469. for line in tests:
  470. line = line.strip()
  471. if line == '' or line.startswith('#'):
  472. continue
  473. self.handle_test_line(line, allow)
  474. def note_error(self, name, xfail):
  475. """Note a failing test."""
  476. if xfail:
  477. print('XFAIL: %s' % name)
  478. self.xerrors += 1
  479. else:
  480. print('FAIL: %s' % name)
  481. self.errors += 1
  482. sys.stdout.flush()
  483. def note_skip(self, name):
  484. """Note a skipped test."""
  485. print('SKIP: %s' % name)
  486. self.skipped += 1
  487. sys.stdout.flush()
  488. def compile_test(self, name, text):
  489. """Run a compilation test; return True if it passes."""
  490. self.total += 1
  491. if self.group_ignore:
  492. return False
  493. optional = self.group_optional
  494. self.group_optional = False
  495. if self.group_skip:
  496. self.note_skip(name)
  497. return False
  498. c_file = os.path.join(self.temp_dir, 'test.c')
  499. o_file = os.path.join(self.temp_dir, 'test.o')
  500. with open(c_file, 'w') as c_file_out:
  501. c_file_out.write('#include <%s>\n%s' % (self.header, text))
  502. cmd = ('%s %s -c %s -o %s' % (self.cc, self.cflags, c_file, o_file))
  503. try:
  504. subprocess.check_call(cmd, shell=True)
  505. except subprocess.CalledProcessError:
  506. if optional:
  507. print('MISSING: %s' % name)
  508. sys.stdout.flush()
  509. self.group_ignore = True
  510. else:
  511. self.note_error(name, self.group_xfail)
  512. self.group_skip = True
  513. return False
  514. print('PASS: %s' % name)
  515. sys.stdout.flush()
  516. return True
  517. def execute_test(self, name, text):
  518. """Run an execution test."""
  519. self.total += 1
  520. if self.group_ignore:
  521. return False
  522. if self.group_skip:
  523. self.note_skip(name)
  524. return
  525. c_file = os.path.join(self.temp_dir, 'test.c')
  526. exe_file = os.path.join(self.temp_dir, 'test')
  527. with open(c_file, 'w') as c_file_out:
  528. c_file_out.write('#include <%s>\n%s' % (self.header, text))
  529. cmd = ('%s %s %s -o %s' % (self.cc, self.cflags, c_file, exe_file))
  530. try:
  531. subprocess.check_call(cmd, shell=True)
  532. except subprocess.CalledProcessError:
  533. self.note_error(name, self.group_xfail)
  534. return
  535. if self.cross:
  536. self.note_skip(name)
  537. return
  538. try:
  539. subprocess.check_call(exe_file, shell=True)
  540. except subprocess.CalledProcessError:
  541. self.note_error(name, self.group_xfail)
  542. return
  543. print('PASS: %s' % name)
  544. sys.stdout.flush()
  545. def check_namespace(self, name):
  546. """Check the namespace of a header."""
  547. c_file = os.path.join(self.temp_dir, 'namespace.c')
  548. out_file = os.path.join(self.temp_dir, 'namespace-out')
  549. with open(c_file, 'w') as c_file_out:
  550. c_file_out.write('#include <%s>\n' % self.header)
  551. cmd = ('%s %s -E %s -P -Wp,-dN > %s'
  552. % (self.cc, self.cflags_namespace, c_file, out_file))
  553. subprocess.check_call(cmd, shell=True)
  554. bad_tokens = set()
  555. with open(out_file, 'r') as content:
  556. for line in content:
  557. line = line.strip()
  558. if not line:
  559. continue
  560. if re.match(r'# [1-9]', line):
  561. continue
  562. match = re.match(r'#define (.*)', line)
  563. if match:
  564. self.check_token(bad_tokens, match.group(1))
  565. continue
  566. match = re.match(r'#undef (.*)', line)
  567. if match:
  568. bad_tokens.discard(match.group(1))
  569. continue
  570. # Tokenize the line and check identifiers found. The
  571. # handling of strings does not allow for escaped
  572. # quotes, no allowance is made for character
  573. # constants, and hex floats may be wrongly split into
  574. # tokens including identifiers, but this is sufficient
  575. # in practice and matches the old perl script.
  576. line = re.sub(r'"[^"]*"', '', line)
  577. line = line.strip()
  578. for token in re.split(r'[^A-Za-z0-9_]+', line):
  579. if re.match(r'[A-Za-z_]', token):
  580. self.check_token(bad_tokens, token)
  581. if bad_tokens:
  582. for token in sorted(bad_tokens):
  583. print(' Namespace violation: "%s"' % token)
  584. self.note_error(name, False)
  585. else:
  586. print('PASS: %s' % name)
  587. sys.stdout.flush()
  588. def run(self):
  589. """Load and run tests of a header."""
  590. with tempfile.TemporaryDirectory() as self.temp_dir:
  591. self.load_tests(self.header, False)
  592. self.group_optional = False
  593. self.group_xfail = False
  594. self.group_ignore = False
  595. self.group_skip = False
  596. available = self.compile_test('Availability of <%s>' % self.header,
  597. '')
  598. if available:
  599. # As an optimization, try running all non-optional,
  600. # non-XFAILed compilation tests in a single execution
  601. # of the compiler.
  602. combined_list = []
  603. for test in self.tests:
  604. if not test.optional and not test.xfail:
  605. for subtest in test.subtests:
  606. if isinstance(subtest, CompileSubTest):
  607. combined_list.append(subtest.text)
  608. subtest.run_early = True
  609. combined_ok = self.compile_test('Combined <%s> test'
  610. % self.header,
  611. '\n'.join(combined_list))
  612. # Now run the other tests, or all tests if the
  613. # combined test failed.
  614. for test in self.tests:
  615. # A test may run more than one subtest. If the
  616. # initial subtest for an optional symbol fails,
  617. # others are not run at all; if the initial
  618. # subtest for an optional symbol succeeds, others
  619. # are run and are not considered optional; if the
  620. # initial subtest for a required symbol fails,
  621. # others are skipped.
  622. self.group_optional = test.optional
  623. self.group_xfail = test.xfail
  624. self.group_ignore = False
  625. self.group_skip = False
  626. for subtest in test.subtests:
  627. if combined_ok and subtest.run_early:
  628. self.total += 1
  629. print('PASSCOMBINED: %s' % subtest.name)
  630. sys.stdout.flush()
  631. else:
  632. subtest.run(self)
  633. namespace_name = 'Namespace of <%s>' % self.header
  634. if available:
  635. self.check_namespace(namespace_name)
  636. else:
  637. self.note_skip(namespace_name)
  638. print('-' * 76)
  639. print(' Total number of tests : %4d' % self.total)
  640. print(' Number of failed tests : %4d' % self.errors)
  641. print(' Number of xfailed tests : %4d' % self.xerrors)
  642. print(' Number of skipped tests : %4d' % self.skipped)
  643. sys.exit(1 if self.errors else 0)
  644. def main():
  645. """The main entry point."""
  646. parser = argparse.ArgumentParser(description='Check header contents.')
  647. parser.add_argument('--header', metavar='HEADER',
  648. help='name of header')
  649. parser.add_argument('--standard', metavar='STD',
  650. help='standard to use when processing header')
  651. parser.add_argument('--cc', metavar='CC',
  652. help='C compiler to use')
  653. parser.add_argument('--flags', metavar='CFLAGS',
  654. help='Compiler flags to use with CC')
  655. parser.add_argument('--cross', action='store_true',
  656. help='Do not run compiled test programs')
  657. parser.add_argument('--xfail', metavar='COND',
  658. help='Name of condition for XFAILs')
  659. args = parser.parse_args()
  660. tests = HeaderTests(args.header, args.standard, args.cc, args.flags,
  661. args.cross, args.xfail)
  662. tests.run()
  663. if __name__ == '__main__':
  664. main()