dso-ordering-test.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. #!/usr/bin/python3
  2. # Generate testcase files and Makefile fragments for DSO sorting test
  3. # Copyright (C) 2021-2026 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. """Generate testcase files and Makefile fragments for DSO sorting test
  20. This script takes a small description string language, and generates
  21. testcases for displaying the ELF dynamic linker's dependency sorting
  22. behavior, allowing verification.
  23. Testcase descriptions are semicolon-separated description strings, and
  24. this tool generates a testcase from the description, including main program,
  25. associated modules, and Makefile fragments for including into elf/Makefile.
  26. This allows automation of what otherwise would be very laborous manual
  27. construction of complex dependency cases, however it must be noted that this
  28. is only a tool to speed up testcase construction, and thus the generation
  29. features are largely mechanical in nature; inconsistencies or errors may occur
  30. if the input description was itself erroneous or have unforeseen interactions.
  31. The format of the input test description files are:
  32. # Each test description has a name, lines of description,
  33. # and an expected output specification. Comments use '#'.
  34. testname1: <test-description-line>
  35. output: <expected-output-string>
  36. # Tests can be marked to be XFAIL by using 'xfail_output' instead
  37. testname2: <test-description-line>
  38. xfail_output: <expected-output-string>
  39. # A default set of GLIBC_TUNABLES tunables can be specified, for which
  40. # all following tests will run multiple times, once for each of the
  41. # GLIBC_TUNABLES=... strings set by the 'tunable_option' command.
  42. tunable_option: <glibc-tunable-string1>
  43. tunable_option: <glibc-tunable-string2>
  44. # Test descriptions can use multiple lines, which will all be merged
  45. # together, so order is not important.
  46. testname3: <test-description-line>
  47. <test-description-line>
  48. <test-description-line>
  49. ...
  50. output: <expected-output-string>
  51. # 'testname3' will be run and compared two times, for both
  52. # GLIBC_TUNABLES=<glibc-tunable-string1> and
  53. # GLIBC_TUNABLES=<glibc-tunable-string2>. This can be cleared and reset by the
  54. # 'clear_tunables' command:
  55. clear_tunables
  56. # Multiple expected outputs can also be specified, with an associated
  57. # tunable option in (), which multiple tests will be run with each
  58. # GLIBC_TUNABLES=... option tried.
  59. testname4:
  60. <test-description-line>
  61. ...
  62. output(<glibc-tunable-string1>): <expected-output-string-1>
  63. output(<glibc-tunable-string2>): <expected-output-string-2>
  64. # Individual tunable output cases can be XFAILed, though note that
  65. # this will have the effect of XFAILing the entire 'testname4' test
  66. # in the final top-level tests.sum summary.
  67. xfail_output(<glibc-tunable-string3>): <expected-output-string-3>
  68. # When multiple outputs (with specific tunable strings) are specified,
  69. # these take priority over any active 'tunable_option' settings.
  70. # When a test is meant to be placed under 'xtests' (not run under
  71. # "make check", but only when "make xtests" is used), the testcase name can be
  72. # declared using 'xtest(<test-name>)':
  73. ...
  74. xtest(test-too-big1): <test-description>
  75. output: <expected-output-string>
  76. ...
  77. # Do note that under current elf/Makefile organization, for such a xtest case,
  78. # while the test execution is only run under 'make xtests', the associated
  79. # DSOs are always built even under 'make check'.
  80. On the description language used, an example description line string:
  81. a->b!->[cdef];c=>g=>h;{+c;%c;-c}->a
  82. Each identifier represents a shared object module, currently sequences of
  83. letters/digits are allowed, case-sensitive.
  84. All such shared objects have a constructor/destructor generated for them
  85. that emits its name followed by a '>' for constructors, and '<' followed by
  86. its name for destructors, e.g. if the name is 'obj1', then "obj1>" and "<obj1"
  87. is printed by its constructor/destructor respectively.
  88. The -> operator specifies a link time dependency, these can be chained for
  89. convenience (e.g. a->b->c->d).
  90. The => operator creates a call-reference, e.g. for a=>b, an fn_a() function
  91. is created inside module 'a', which calls fn_b() in module 'b'.
  92. These module functions emit 'name()' output in nested form,
  93. e.g. a=>b emits 'a(b())'
  94. For single character object names, square brackets [] in the description
  95. allows specifying multiple objects; e.g. a->[bcd]->e is equivalent to
  96. a->b->e;a->c->e;a->d->e
  97. The () parenthesis construct with space separated names is also allowed for
  98. specifying objects. For names with integer suffixes a range can also be used,
  99. e.g. (foo1 bar2-5), specifies DSOs foo1, bar2, bar2, bar3, bar4, bar5.
  100. A {} construct specifies the main test program, and its link dependencies
  101. are also specified using ->. Inside {}, a few ;-separated constructs are
  102. allowed:
  103. +a Loads module a using dlopen(RTLD_LAZY|RTLD_GLOBAL)
  104. ^a Loads module a using dlopen(RTLD_LAZY)
  105. %a Use dlsym() to load and call fn_a()
  106. @a Calls fn_a() directly.
  107. -a Unloads module a using dlclose()
  108. The generated main program outputs '{' '}' with all output from above
  109. constructs in between. The other output before/after {} are the ordered
  110. constructor/destructor output.
  111. If no {} construct is present, a default empty main program is linked
  112. against all objects which have no dependency linked to it. e.g. for
  113. '[ab]->c;d->e', the default main program is equivalent to '{}->[abd]'
  114. Sometimes for very complex or large testcases, besides specifying a
  115. few explicit dependencies from main{}, the above default dependency
  116. behavior is still useful to automatically have, but is turned off
  117. upon specifying a single explicit {}->dso_name.
  118. In this case, add {}->* to explicitly add this generation behavior:
  119. # Main program links to 'foo', and all other objects which have no
  120. # dependency linked to it.
  121. {}->foo,{}->*
  122. Note that '*' works not only on main{}, but can be used as the
  123. dependency target of any object. Note that it only works as a target,
  124. not a dependency source.
  125. The '!' operator after object names turns on permutation of its
  126. dependencies, e.g. while a->[bcd] only generates one set of objects,
  127. with 'a.so' built with a link line of "b.so c.so d.so", for a!->[bcd]
  128. permutations of a's dependencies creates multiple testcases with
  129. different link line orders: "b.so c.so d.so", "c.so b.so d.so",
  130. "b.so d.so c.so", etc. Note that for a <test-name> specified on
  131. the script command-line, multiple <test-name_1>, <test-name_2>, etc.
  132. tests will be generated (e.g. for a!->[bc]!->[de], eight tests with
  133. different link orders for a, b, and c will be generated)
  134. It is possible to specify the ELF soname field for an object or the
  135. main program:
  136. # DSO 'a' will be linked with the appropriate -Wl,-soname=x setting
  137. a->b->c;soname(a)=x
  138. # The the main program can also have a soname specified
  139. soname({})=y
  140. This can be used to test how ld.so behaves when objects and/or the
  141. main program have such a field set.
  142. Strings Output by Generated Testcase Programs
  143. The text output produced by a generated testcase consists of three main
  144. parts:
  145. 1. The constructors' output
  146. 2. Output from the main program
  147. 3. Destructors' output
  148. To see by example, a simple test description "a->b->c" generates a testcase
  149. that when run, outputs: "c>b>a>{}<a<b<c"
  150. Each generated DSO constructor prints its name followed by a '>' character,
  151. and the "c>b>a" part above is the full constructor output by all DSOs, the
  152. order indicating that DSO 'c', which does not depend on any other DSO, has
  153. its constructor run first, followed by 'b' and then 'a'.
  154. Destructor output for each DSO is a '<' character followed by its name,
  155. reflecting its reverse nature of constructors. In the above example, the
  156. destructor output part is "<a<b<c".
  157. The middle "{}" part is the main program. In this simple example, nothing
  158. was specified for the main program, so by default it is implicitly linked
  159. to the DSO 'a' (with no other DSOs depending on it) and only prints the
  160. brackets {} with no actions inside.
  161. To see an example with actions inside the main program, lets see an example
  162. description: c->g=>h;{+c;%c;-c}->a->h
  163. This produces a testcase, that when executed outputs:
  164. h>a>{+c[g>c>];%c();-c[<c<g];}<a<h
  165. The constructor and destructor parts display the a->h dependency as expected.
  166. Inside the main program, the "+c" action triggers a dlopen() of DSO 'c',
  167. causing another chain of constructors "g>c>" to be triggered. Here it is
  168. displayed inside [] brackets for each dlopen call. The same is done for "-c",
  169. a dlclose() of 'c'.
  170. The "%c" output is due to calling to fn_c() inside DSO 'c', this comprises
  171. of two parts: the '%' character is printed by the caller, here it is the main
  172. program. The 'c' character is printed from inside fn_c(). The '%' character
  173. indicates that this is called by a dlsym() of "fn_c". A '@' character would
  174. mean a direct call (with a symbol reference). These can all be controlled
  175. by the main test program constructs documented earlier.
  176. The output strings described here is the exact same form placed in
  177. test description files' "output: <expected output>" line.
  178. """
  179. import sys
  180. import re
  181. import os
  182. import subprocess
  183. import argparse
  184. from collections import OrderedDict
  185. import itertools
  186. # BUILD_GCC is only used under the --build option,
  187. # which builds the generated testcase, including DSOs using BUILD_GCC.
  188. # Mainly for testing purposes, especially debugging of this script,
  189. # and can be changed here to another toolchain path if needed.
  190. build_gcc = "gcc"
  191. def get_parser():
  192. parser = argparse.ArgumentParser("")
  193. parser.add_argument("description",
  194. help="Description string of DSO dependency test to be "
  195. "generated (see script source for documentation of "
  196. "description language), either specified here as "
  197. "command line argument, or by input file using "
  198. "-f/--description-file option",
  199. nargs="?", default="")
  200. parser.add_argument("test_name",
  201. help="Identifier for testcase being generated",
  202. nargs="?", default="")
  203. parser.add_argument("--objpfx",
  204. help="Path to place generated files, defaults to "
  205. "current directory if none specified",
  206. nargs="?", default="./")
  207. parser.add_argument("-m", "--output-makefile",
  208. help="File to write Makefile fragment to, defaults to "
  209. "stdout when option not present",
  210. nargs="?", default="")
  211. parser.add_argument("-f", "--description-file",
  212. help="Input file containing testcase descriptions",
  213. nargs="?", default="")
  214. parser.add_argument("--build", help="After C testcase generated, build it "
  215. "using gcc (for manual testing purposes)",
  216. action="store_true")
  217. parser.add_argument("--debug-output",
  218. help="Prints some internal data "
  219. "structures; used for debugging of this script",
  220. action="store_true")
  221. return parser
  222. # Main script starts here.
  223. cmdlineargs = get_parser().parse_args()
  224. test_name = cmdlineargs.test_name
  225. description = cmdlineargs.description
  226. objpfx = cmdlineargs.objpfx
  227. description_file = cmdlineargs.description_file
  228. output_makefile = cmdlineargs.output_makefile
  229. makefile = ""
  230. default_tunable_options = []
  231. current_input_lineno = 0
  232. def error(msg):
  233. global current_input_lineno
  234. print("Error: %s%s" % ((("Line %d, " % current_input_lineno)
  235. if current_input_lineno != 0 else ""),
  236. msg))
  237. exit(1)
  238. if(test_name or description) and description_file:
  239. error("both command-line testcase and input file specified")
  240. if test_name and not description:
  241. error("command-line testcase name without description string")
  242. # Main class type describing a testcase.
  243. class TestDescr:
  244. def __init__(self):
  245. self.objs = [] # list of all DSO objects
  246. self.deps = OrderedDict() # map of DSO object -> list of dependencies
  247. # map of DSO object -> list of call refs
  248. self.callrefs = OrderedDict()
  249. # map of DSO object -> list of permutations of dependencies
  250. self.dep_permutations = OrderedDict()
  251. # map of DSO object -> SONAME of object (if one is specified)
  252. self.soname_map = OrderedDict()
  253. # list of main program operations
  254. self.main_program = []
  255. # set if default dependencies added to main
  256. self.main_program_default_deps = True
  257. self.test_name = "" # name of testcase
  258. self.expected_outputs = OrderedDict() # expected outputs of testcase
  259. self.xfail = False # set if this is a XFAIL testcase
  260. self.xtest = False # set if this is put under 'xtests'
  261. # Add 'object -> [object, object, ...]' relations to CURR_MAP
  262. def __add_deps_internal(self, src_objs, dst_objs, curr_map):
  263. for src in src_objs:
  264. for dst in dst_objs:
  265. if not src in curr_map:
  266. curr_map[src] = []
  267. if not dst in curr_map[src]:
  268. curr_map[src].append(dst)
  269. def add_deps(self, src_objs, dst_objs):
  270. self.__add_deps_internal(src_objs, dst_objs, self.deps)
  271. def add_callrefs(self, src_objs, dst_objs):
  272. self.__add_deps_internal(src_objs, dst_objs, self.callrefs)
  273. # Process commands inside the {} construct.
  274. # Note that throughout this script, the main program object is represented
  275. # by the '#' string.
  276. def process_main_program(test_descr, mainprog_str):
  277. if mainprog_str:
  278. test_descr.main_program = mainprog_str.split(';')
  279. for s in test_descr.main_program:
  280. m = re.match(r"^([+\-%^@])([0-9a-zA-Z]+)$", s)
  281. if not m:
  282. error("'%s' is not recognized main program operation" % (s))
  283. opr = m.group(1)
  284. obj = m.group(2)
  285. if not obj in test_descr.objs:
  286. test_descr.objs.append(obj)
  287. if opr == '%' or opr == '@':
  288. test_descr.add_callrefs(['#'], [obj])
  289. # We have a main program specified, turn this off
  290. test_descr.main_program_default_deps = False
  291. # For(a1 a2 b1-12) object set descriptions, expand into an object list
  292. def expand_object_set_string(descr_str):
  293. obj_list = []
  294. descr_list = descr_str.split()
  295. for descr in descr_list:
  296. m = re.match(r"^([a-zA-Z][0-9a-zA-Z]*)(-[0-9]+)?$", descr)
  297. if not m:
  298. error("'%s' is not a valid object set description" % (descr))
  299. obj = m.group(1)
  300. idx_end = m.group(2)
  301. if not idx_end:
  302. if not obj in obj_list:
  303. obj_list.append(obj)
  304. else:
  305. idx_end = int(idx_end[1:])
  306. m = re.match(r"^([0-9a-zA-Z][a-zA-Z]*)([0-9]+)$", obj)
  307. if not m:
  308. error("object description '%s' is malformed" % (obj))
  309. obj_name = m.group(1)
  310. idx_start = int(m.group (2))
  311. if idx_start > idx_end:
  312. error("index range %s-%s invalid" % (idx_start, idx_end))
  313. for i in range(idx_start, idx_end + 1):
  314. o = obj_name + str(i)
  315. if not o in obj_list:
  316. obj_list.append(o)
  317. return obj_list
  318. # Lexer for tokens
  319. tokenspec = [ ("SONAME", r"soname\(([0-9a-zA-Z{}]+)\)=([0-9a-zA-Z]+)"),
  320. ("OBJ", r"([0-9a-zA-Z]+)"),
  321. ("DEP", r"->"),
  322. ("CALLREF", r"=>"),
  323. ("OBJSET", r"\[([0-9a-zA-Z]+)\]"),
  324. ("OBJSET2", r"\(([0-9a-zA-Z \-]+)\)"),
  325. ("OBJSET3", r"\*"),
  326. ("PROG", r"{([0-9a-zA-Z;+^\-%@]*)}"),
  327. ("PERMUTE", r"!"),
  328. ("SEMICOL", r";"),
  329. ("ERROR", r".") ]
  330. tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tokenspec)
  331. # Main line parser of description language
  332. def parse_description_string(t, descr_str):
  333. # State used when parsing dependencies
  334. curr_objs = []
  335. in_dep = False
  336. in_callref = False
  337. def clear_dep_state():
  338. nonlocal in_dep, in_callref
  339. in_dep = in_callref = False
  340. for m in re.finditer(tok_re, descr_str):
  341. kind = m.lastgroup
  342. value = m.group()
  343. if kind == "SONAME":
  344. s = re.match(r"soname\(([0-9a-zA-Z{}]+)\)=([0-9a-zA-Z]+)", value)
  345. obj = s.group(1)
  346. val = s.group(2)
  347. if obj == "{}":
  348. if '#' in t.soname_map:
  349. error("soname of main program already set")
  350. # Adjust to internal name
  351. obj = '#'
  352. else:
  353. if re.match(r"[{}]", obj):
  354. error("invalid object name '%s'" % (obj))
  355. if not obj in t.objs:
  356. error("'%s' is not name of already defined object" % (obj))
  357. if obj in t.soname_map:
  358. error("'%s' already has soname of '%s' set"
  359. % (obj, t.soname_map[obj]))
  360. t.soname_map[obj] = val
  361. elif kind == "OBJ":
  362. if in_dep:
  363. t.add_deps(curr_objs, [value])
  364. elif in_callref:
  365. t.add_callrefs(curr_objs, [value])
  366. clear_dep_state()
  367. curr_objs = [value]
  368. if not value in t.objs:
  369. t.objs.append(value)
  370. elif kind == "OBJSET":
  371. objset = value[1:len(value)-1]
  372. if in_dep:
  373. t.add_deps(curr_objs, list (objset))
  374. elif in_callref:
  375. t.add_callrefs(curr_objs, list (objset))
  376. clear_dep_state()
  377. curr_objs = list(objset)
  378. for o in list(objset):
  379. if not o in t.objs:
  380. t.objs.append(o)
  381. elif kind == "OBJSET2":
  382. descr_str = value[1:len(value)-1]
  383. descr_str.strip()
  384. objs = expand_object_set_string(descr_str)
  385. if not objs:
  386. error("empty object set '%s'" % (value))
  387. if in_dep:
  388. t.add_deps(curr_objs, objs)
  389. elif in_callref:
  390. t.add_callrefs(curr_objs, objs)
  391. clear_dep_state()
  392. curr_objs = objs
  393. for o in objs:
  394. if not o in t.objs:
  395. t.objs.append(o)
  396. elif kind == "OBJSET3":
  397. if in_dep:
  398. t.add_deps(curr_objs, ['*'])
  399. elif in_callref:
  400. t.add_callrefs(curr_objs, ['*'])
  401. else:
  402. error("non-dependence target set '*' can only be used "
  403. "as target of ->/=> operations")
  404. clear_dep_state()
  405. curr_objs = ['*']
  406. elif kind == "PERMUTE":
  407. if in_dep or in_callref:
  408. error("syntax error, permute operation invalid here")
  409. if not curr_objs:
  410. error("syntax error, no objects to permute here")
  411. for obj in curr_objs:
  412. if not obj in t.dep_permutations:
  413. # Signal this object has permuted dependencies
  414. t.dep_permutations[obj] = []
  415. elif kind == "PROG":
  416. if t.main_program:
  417. error("cannot have more than one main program")
  418. if in_dep:
  419. error("objects cannot have dependency on main program")
  420. if in_callref:
  421. # TODO: A DSO can resolve to a symbol in the main binary,
  422. # which we syntactically allow here, but haven't yet
  423. # implemented.
  424. t.add_callrefs(curr_objs, ["#"])
  425. process_main_program(t, value[1:len(value)-1])
  426. clear_dep_state()
  427. curr_objs = ["#"]
  428. elif kind == "DEP":
  429. if in_dep or in_callref:
  430. error("syntax error, multiple contiguous ->,=> operations")
  431. if '*' in curr_objs:
  432. error("non-dependence target set '*' can only be used "
  433. "as target of ->/=> operations")
  434. in_dep = True
  435. elif kind == "CALLREF":
  436. if in_dep or in_callref:
  437. error("syntax error, multiple contiguous ->,=> operations")
  438. if '*' in curr_objs:
  439. error("non-dependence target set '*' can only be used "
  440. "as target of ->/=> operations")
  441. in_callref = True
  442. elif kind == "SEMICOL":
  443. curr_objs = []
  444. clear_dep_state()
  445. else:
  446. error("unknown token '%s'" % (value))
  447. return t
  448. # Main routine to process each testcase description
  449. def process_testcase(t):
  450. global objpfx
  451. assert t.test_name
  452. base_test_name = t.test_name
  453. test_subdir = base_test_name + "-dir"
  454. testpfx = objpfx + test_subdir + "/"
  455. test_srcdir = "dso-sort-tests-src/"
  456. testpfx_src = objpfx + test_srcdir
  457. if not os.path.exists(testpfx):
  458. os.mkdir(testpfx)
  459. if not os.path.exists(testpfx_src):
  460. os.mkdir(testpfx_src)
  461. def find_objs_not_depended_on(t):
  462. objs_not_depended_on = []
  463. for obj in t.objs:
  464. skip = False
  465. for r in t.deps.items():
  466. if obj in r[1]:
  467. skip = True
  468. break
  469. if not skip:
  470. objs_not_depended_on.append(obj)
  471. return objs_not_depended_on
  472. non_dep_tgt_objs = find_objs_not_depended_on(t)
  473. for obj in t.objs:
  474. if obj in t.deps:
  475. deps = t.deps[obj]
  476. if '*' in deps:
  477. deps.remove('*')
  478. t.add_deps([obj], non_dep_tgt_objs)
  479. if obj in t.callrefs:
  480. deps = t.callrefs[obj]
  481. if '*' in deps:
  482. deps.remove('*')
  483. t.add_callrefs([obj], non_dep_tgt_objs)
  484. if "#" in t.deps:
  485. deps = t.deps["#"]
  486. if '*' in deps:
  487. deps.remove('*')
  488. t.add_deps(["#"], non_dep_tgt_objs)
  489. # If no main program was specified in dependency description, make a
  490. # default main program with deps pointing to all DSOs which are not
  491. # depended by another DSO.
  492. if t.main_program_default_deps:
  493. main_deps = non_dep_tgt_objs
  494. if not main_deps:
  495. error("no objects for default main program to point "
  496. "dependency to(all objects strongly connected?)")
  497. t.add_deps(["#"], main_deps)
  498. # Some debug output
  499. if cmdlineargs.debug_output:
  500. print("Testcase: %s" % (t.test_name))
  501. print("All objects: %s" % (t.objs))
  502. print("--- Static link dependencies ---")
  503. for r in t.deps.items():
  504. print("%s -> %s" % (r[0], r[1]))
  505. print("--- Objects whose dependencies are to be permuted ---")
  506. for r in t.dep_permutations.items():
  507. print("%s" % (r[0]))
  508. print("--- Call reference dependencies ---")
  509. for r in t.callrefs.items():
  510. print("%s => %s" % (r[0], r[1]))
  511. print("--- main program ---")
  512. print(t.main_program)
  513. # Main testcase generation routine, does Makefile fragment generation,
  514. # testcase source generation, and if --build specified builds testcase.
  515. def generate_testcase(test_descr, test_suffix):
  516. test_name = test_descr.test_name + test_suffix
  517. # Print out needed Makefile fragments for use in glibc/elf/Makefile.
  518. module_names = ""
  519. for o in test_descr.objs:
  520. rule = ("$(objpfx)" + test_subdir + "/" + test_name
  521. + "-" + o + ".os: $(objpfx)" + test_srcdir
  522. + test_name + "-" + o + ".c\n"
  523. "\t$(compile.c) $(OUTPUT_OPTION)\n")
  524. makefile.write (rule)
  525. module_names += " " + test_subdir + "/" + test_name + "-" + o
  526. makefile.write("modules-names +=%s\n" % (module_names))
  527. # Depth-first traversal, executing FN(OBJ) in post-order
  528. def dfs(t, fn):
  529. def dfs_rec(obj, fn, obj_visited):
  530. if obj in obj_visited:
  531. return
  532. obj_visited[obj] = True
  533. if obj in t.deps:
  534. for dep in t.deps[obj]:
  535. dfs_rec(dep, fn, obj_visited)
  536. fn(obj)
  537. obj_visited = {}
  538. for obj in t.objs:
  539. dfs_rec(obj, fn, obj_visited)
  540. # Generate link dependencies for all DSOs, done in a DFS fashion.
  541. # Usually this doesn't need to be this complex, just listing the direct
  542. # dependencies is enough. However to support creating circular
  543. # dependency situations, traversing it by DFS and tracking processing
  544. # status is the natural way to do it.
  545. obj_processed = {}
  546. fake_created = {}
  547. def gen_link_deps(obj):
  548. if obj in test_descr.deps:
  549. dso = test_subdir + "/" + test_name + "-" + obj + ".so"
  550. dependencies = ""
  551. for dep in test_descr.deps[obj]:
  552. if dep in obj_processed:
  553. depstr = (" $(objpfx)" + test_subdir + "/"
  554. + test_name + "-" + dep + ".so")
  555. else:
  556. # A circular dependency is satisfied by making a
  557. # fake DSO tagged with the correct SONAME
  558. depstr = (" $(objpfx)" + test_subdir + "/"
  559. + test_name + "-" + dep + ".FAKE.so")
  560. # Create empty C file and Makefile fragments for fake
  561. # object. This only needs to be done at most once for
  562. # an object name.
  563. if not dep in fake_created:
  564. f = open(testpfx_src + test_name + "-" + dep
  565. + ".FAKE.c", "w")
  566. f.write(" \n")
  567. f.close()
  568. # Generate rule to create fake object
  569. makefile.write \
  570. ("LDFLAGS-%s = -Wl,--no-as-needed "
  571. "-Wl,-soname=%s\n"
  572. % (test_name + "-" + dep + ".FAKE.so",
  573. ("$(objpfx)" + test_subdir + "/"
  574. + test_name + "-" + dep + ".so")))
  575. rule = ("$(objpfx)" + test_subdir + "/"
  576. + test_name + "-" + dep + ".FAKE.os: "
  577. "$(objpfx)" + test_srcdir
  578. + test_name + "-" + dep + ".FAKE.c\n"
  579. "\t$(compile.c) $(OUTPUT_OPTION)\n")
  580. makefile.write (rule)
  581. makefile.write \
  582. ("modules-names += %s\n"
  583. % (test_subdir + "/"
  584. + test_name + "-" + dep + ".FAKE"))
  585. fake_created[dep] = True
  586. dependencies += depstr
  587. makefile.write("$(objpfx)%s:%s\n" % (dso, dependencies))
  588. # Mark obj as processed
  589. obj_processed[obj] = True
  590. dfs(test_descr, gen_link_deps)
  591. # Print LDFLAGS-* and *-no-z-defs
  592. for o in test_descr.objs:
  593. dso = test_name + "-" + o + ".so"
  594. ldflags = "-Wl,--no-as-needed"
  595. if o in test_descr.soname_map:
  596. soname = ("$(objpfx)" + test_subdir + "/"
  597. + test_name + "-"
  598. + test_descr.soname_map[o] + ".so")
  599. ldflags += (" -Wl,-soname=" + soname)
  600. makefile.write("LDFLAGS-%s = %s\n" % (dso, ldflags))
  601. if o in test_descr.callrefs:
  602. makefile.write("%s-no-z-defs = yes\n" % (dso))
  603. # Print dependencies for main test program.
  604. depstr = ""
  605. if '#' in test_descr.deps:
  606. for o in test_descr.deps['#']:
  607. depstr += (" $(objpfx)" + test_subdir + "/"
  608. + test_name + "-" + o + ".so")
  609. makefile.write("$(objpfx)%s/%s:%s\n" % (test_subdir, test_name, depstr))
  610. ldflags = "-Wl,--no-as-needed"
  611. if '#' in test_descr.soname_map:
  612. soname = ("$(objpfx)" + test_subdir + "/"
  613. + test_name + "-"
  614. + test_descr.soname_map['#'] + ".so")
  615. ldflags += (" -Wl,-soname=" + soname)
  616. makefile.write("LDFLAGS-%s = %s\n" % (test_name, ldflags))
  617. rule = ("$(objpfx)" + test_subdir + "/" + test_name + ".o: "
  618. "$(objpfx)" + test_srcdir + test_name + ".c\n"
  619. "\t$(compile.c) $(OUTPUT_OPTION)\n")
  620. makefile.write (rule)
  621. # Ensure that all shared objects are built before running the
  622. # test, whether there link-time dependencies or not.
  623. depobjs = ["$(objpfx){}/{}-{}.so".format(test_subdir, test_name, dep)
  624. for dep in test_descr.objs]
  625. makefile.write("$(objpfx){}.out: {}\n".format(
  626. base_test_name, " ".join(depobjs)))
  627. # Add main executable to test-srcs
  628. makefile.write("test-srcs += %s/%s\n" % (test_subdir, test_name))
  629. # Add dependency on main executable of test
  630. makefile.write("$(objpfx)%s.out: $(objpfx)%s/%s\n"
  631. % (base_test_name, test_subdir, test_name))
  632. for r in test_descr.expected_outputs.items():
  633. tunable_options = []
  634. specific_tunable = r[0]
  635. xfail = r[1][1]
  636. if specific_tunable != "":
  637. tunable_options = [specific_tunable]
  638. else:
  639. tunable_options = default_tunable_options
  640. if not tunable_options:
  641. tunable_options = [""]
  642. for tunable in tunable_options:
  643. tunable_env = ""
  644. tunable_sfx = ""
  645. exp_tunable_sfx = ""
  646. if tunable:
  647. tunable_env = "GLIBC_TUNABLES=%s " % tunable
  648. tunable_sfx = "-" + tunable.replace("=","_")
  649. if specific_tunable:
  650. tunable_sfx = "-" + specific_tunable.replace("=","_")
  651. exp_tunable_sfx = tunable_sfx
  652. tunable_descr = ("(%s)" % tunable_env.strip()
  653. if tunable_env else "")
  654. # Write out fragment of shell script for this single test.
  655. test_descr.sh.write \
  656. ("${test_wrapper_env} ${run_program_env} %s\\\n"
  657. "${common_objpfx}support/test-run-command \\\n"
  658. "${common_objpfx}elf/ld.so \\\n"
  659. "--library-path $library_path:${common_objpfx}elf/%s:"
  660. "${common_objpfx}elf:${common_objpfx}.:"
  661. "${common_objpfx}dlfcn \\\n"
  662. "${common_objpfx}elf/%s/%s > \\\n"
  663. " ${common_objpfx}elf/%s/%s%s.output\n"
  664. % (tunable_env ,test_subdir,
  665. test_subdir, test_name, test_subdir, test_name,
  666. tunable_sfx))
  667. # Generate a run of each test and compare with expected out
  668. test_descr.sh.write \
  669. ("if [ $? -ne 0 ]; then\n"
  670. " echo '%sFAIL: %s%s execution test'\n"
  671. " something_failed=true\n"
  672. "else\n"
  673. " diff -wu ${common_objpfx}elf/%s/%s%s.output \\\n"
  674. " ${common_objpfx}elf/%s%s%s.exp\n"
  675. " if [ $? -ne 0 ]; then\n"
  676. " echo '%sFAIL: %s%s expected output comparison'\n"
  677. " something_failed=true\n"
  678. " fi\n"
  679. "fi\n"
  680. % (("X" if xfail else ""), test_name, tunable_descr,
  681. test_subdir, test_name, tunable_sfx,
  682. test_srcdir, base_test_name, exp_tunable_sfx,
  683. ("X" if xfail else ""), test_name, tunable_descr))
  684. # Generate C files according to dependency and calling relations from
  685. # description string.
  686. for obj in test_descr.objs:
  687. src_name = test_name + "-" + obj + ".c"
  688. f = open(testpfx_src + src_name, "w")
  689. if obj in test_descr.callrefs:
  690. called_objs = test_descr.callrefs[obj]
  691. for callee in called_objs:
  692. f.write("extern void fn_%s (void);\n" % (callee))
  693. if len(obj) == 1:
  694. f.write("extern int putchar(int);\n")
  695. f.write("static void __attribute__((constructor)) " +
  696. "init(void){putchar('%s');putchar('>');}\n" % (obj))
  697. f.write("static void __attribute__((destructor)) " +
  698. "fini(void){putchar('<');putchar('%s');}\n" % (obj))
  699. else:
  700. f.write('extern int printf(const char *, ...);\n')
  701. f.write('static void __attribute__((constructor)) ' +
  702. 'init(void){printf("%s>");}\n' % (obj))
  703. f.write('static void __attribute__((destructor)) ' +
  704. 'fini(void){printf("<%s");}\n' % (obj))
  705. if obj in test_descr.callrefs:
  706. called_objs = test_descr.callrefs[obj]
  707. if len(obj) != 1:
  708. f.write("extern int putchar(int);\n")
  709. f.write("void fn_%s (void) {\n" % (obj))
  710. if len(obj) == 1:
  711. f.write(" putchar ('%s');\n" % (obj));
  712. f.write(" putchar ('(');\n");
  713. else:
  714. f.write(' printf ("%s(");\n' % (obj));
  715. for callee in called_objs:
  716. f.write(" fn_%s ();\n" % (callee))
  717. f.write(" putchar (')');\n");
  718. f.write("}\n")
  719. else:
  720. for callref in test_descr.callrefs.items():
  721. if obj in callref[1]:
  722. if len(obj) == 1:
  723. # We need to declare printf here in this case.
  724. f.write('extern int printf(const char *, ...);\n')
  725. f.write("void fn_%s (void) {\n" % (obj))
  726. f.write(' printf ("%s()");\n' % (obj))
  727. f.write("}\n")
  728. break
  729. f.close()
  730. # Open C file for writing main program
  731. f = open(testpfx_src + test_name + ".c", "w")
  732. # if there are some operations in main(), it means we need -ldl
  733. f.write("#include <stdio.h>\n")
  734. f.write("#include <stdlib.h>\n")
  735. f.write("#include <dlfcn.h>\n")
  736. for s in test_descr.main_program:
  737. if s[0] == '@':
  738. f.write("extern void fn_%s (void);\n" % (s[1:]));
  739. f.write("int main (void) {\n")
  740. f.write(" putchar('{');\n")
  741. # Helper routine for generating sanity checking code.
  742. def put_fail_check(fail_cond, action_desc):
  743. f.write(' if (%s) { printf ("\\n%s failed: %%s\\n", '
  744. 'dlerror()); exit (1);}\n' % (fail_cond, action_desc))
  745. i = 0
  746. while i < len(test_descr.main_program):
  747. s = test_descr.main_program[i]
  748. obj = s[1:]
  749. dso = test_name + "-" + obj
  750. if s[0] == '+' or s[0] == '^':
  751. if s[0] == '+':
  752. dlopen_flags = "RTLD_LAZY|RTLD_GLOBAL"
  753. f.write(" putchar('+');\n");
  754. else:
  755. dlopen_flags = "RTLD_LAZY"
  756. f.write(" putchar(':');\n");
  757. if len(obj) == 1:
  758. f.write(" putchar('%s');\n" % (obj));
  759. else:
  760. f.write(' printf("%s");\n' % (obj));
  761. f.write(" putchar('[');\n");
  762. f.write(' void *%s = dlopen ("%s.so", %s);\n'
  763. % (obj, dso, dlopen_flags))
  764. put_fail_check("!%s" % (obj),
  765. "%s.so dlopen" % (dso))
  766. f.write(" putchar(']');\n");
  767. elif s[0] == '-':
  768. f.write(" putchar('-');\n");
  769. if len(obj) == 1:
  770. f.write(" putchar('%s');\n" % (obj));
  771. else:
  772. f.write(' printf("%s");\n' % (obj));
  773. f.write(" putchar('[');\n");
  774. put_fail_check("dlclose (%s) != 0" % (obj),
  775. "%s.so dlclose" % (dso))
  776. f.write(" putchar(']');\n");
  777. elif s[0] == '%':
  778. f.write(" putchar('%');\n");
  779. f.write(' void (*fn_%s)(void) = dlsym (%s, "fn_%s");\n'
  780. % (obj, obj, obj))
  781. put_fail_check("!fn_%s" % (obj),
  782. "dlsym(fn_%s) from %s.so" % (obj, dso))
  783. f.write(" fn_%s ();\n" % (obj))
  784. elif s[0] == '@':
  785. f.write(" putchar('@');\n");
  786. f.write(" fn_%s ();\n" % (obj))
  787. f.write(" putchar(';');\n");
  788. i += 1
  789. f.write(" putchar('}');\n")
  790. f.write(" return 0;\n")
  791. f.write("}\n")
  792. f.close()
  793. # --build option processing: build generated sources using 'build_gcc'
  794. if cmdlineargs.build:
  795. # Helper routine to run a shell command, for running GCC below
  796. def run_cmd(args):
  797. cmd = str.join(' ', args)
  798. if cmdlineargs.debug_output:
  799. print(cmd)
  800. p = subprocess.Popen(args)
  801. p.wait()
  802. if p.returncode != 0:
  803. error("error running command: %s" % (cmd))
  804. # Compile individual .os files
  805. for obj in test_descr.objs:
  806. src_name = test_name + "-" + obj + ".c"
  807. obj_name = test_name + "-" + obj + ".os"
  808. run_cmd([build_gcc, "-c", "-fPIC", testpfx_src + src_name,
  809. "-o", testpfx + obj_name])
  810. obj_processed = {}
  811. fake_created = {}
  812. # Function to create <test_name>-<obj>.so
  813. def build_dso(obj):
  814. obj_name = test_name + "-" + obj + ".os"
  815. dso_name = test_name + "-" + obj + ".so"
  816. deps = []
  817. if obj in test_descr.deps:
  818. for dep in test_descr.deps[obj]:
  819. if dep in obj_processed:
  820. deps.append(dep)
  821. else:
  822. deps.append(dep + ".FAKE")
  823. if not dep in fake_created:
  824. base_name = testpfx + test_name + "-" + dep
  825. src_base_name = (testpfx_src + test_name
  826. + "-" + dep)
  827. cmd = [build_gcc, "-Wl,--no-as-needed",
  828. ("-Wl,-soname=" + base_name + ".so"),
  829. "-shared", base_name + ".FAKE.c",
  830. "-o", src_base_name + ".FAKE.so"]
  831. run_cmd(cmd)
  832. fake_created[dep] = True
  833. dso_deps = map(lambda d: testpfx + test_name + "-" + d + ".so",
  834. deps)
  835. cmd = [build_gcc, "-shared", "-o", testpfx + dso_name,
  836. testpfx + obj_name, "-Wl,--no-as-needed"]
  837. if obj in test_descr.soname_map:
  838. soname = ("-Wl,-soname=" + testpfx + test_name + "-"
  839. + test_descr.soname_map[obj] + ".so")
  840. cmd += [soname]
  841. cmd += list(dso_deps)
  842. run_cmd(cmd)
  843. obj_processed[obj] = True
  844. # Build all DSOs, this needs to be in topological dependency order,
  845. # or link will fail
  846. dfs(test_descr, build_dso)
  847. # Build main program
  848. deps = []
  849. if '#' in test_descr.deps:
  850. deps = test_descr.deps['#']
  851. main_deps = map(lambda d: testpfx + test_name + "-" + d + ".so",
  852. deps)
  853. cmd = [build_gcc, "-Wl,--no-as-needed", "-o", testpfx + test_name,
  854. testpfx_src + test_name + ".c", "-L%s" % (os.getcwd()),
  855. "-Wl,-rpath-link=%s" % (os.getcwd())]
  856. if '#' in test_descr.soname_map:
  857. soname = ("-Wl,-soname=" + testpfx + test_name + "-"
  858. + test_descr.soname_map['#'] + ".so")
  859. cmd += [soname]
  860. cmd += list(main_deps)
  861. run_cmd(cmd)
  862. # Check if we need to enumerate permutations of dependencies
  863. need_permutation_processing = False
  864. if t.dep_permutations:
  865. # Adjust dep_permutations into map of object -> dependency permutations
  866. for r in t.dep_permutations.items():
  867. obj = r[0]
  868. if obj in t.deps and len(t.deps[obj]) > 1:
  869. deps = t.deps[obj]
  870. t.dep_permutations[obj] = list(itertools.permutations (deps))
  871. need_permutation_processing = True
  872. def enum_permutations(t, perm_list):
  873. test_subindex = 1
  874. curr_perms = []
  875. def enum_permutations_rec(t, perm_list):
  876. nonlocal test_subindex, curr_perms
  877. if len(perm_list) >= 1:
  878. curr = perm_list[0]
  879. obj = curr[0]
  880. perms = curr[1]
  881. if not perms:
  882. # This may be an empty list if no multiple dependencies to
  883. # permute were found, skip to next in this case
  884. enum_permutations_rec(t, perm_list[1:])
  885. else:
  886. for deps in perms:
  887. t.deps[obj] = deps
  888. permstr = "" if obj == "#" else obj + "_"
  889. permstr += str.join('', deps)
  890. curr_perms.append(permstr)
  891. enum_permutations_rec(t, perm_list[1:])
  892. curr_perms = curr_perms[0:len(curr_perms)-1]
  893. else:
  894. # t.deps is now instantiated with one dependency order
  895. # permutation(across all objects that have multiple
  896. # permutations), now process a testcase
  897. generate_testcase(t, ("_" + str (test_subindex)
  898. + "-" + str.join('-', curr_perms)))
  899. test_subindex += 1
  900. enum_permutations_rec(t, perm_list)
  901. # Create *.exp files with expected outputs
  902. for r in t.expected_outputs.items():
  903. sfx = ""
  904. if r[0] != "":
  905. sfx = "-" + r[0].replace("=","_")
  906. f = open(testpfx_src + t.test_name + sfx + ".exp", "w")
  907. (output, xfail) = r[1]
  908. f.write('%s' % output)
  909. f.close()
  910. # Create header part of top-level testcase shell script, to wrap execution
  911. # and output comparison together.
  912. t.sh = open(testpfx_src + t.test_name + ".sh", "w")
  913. t.sh.write("#!/bin/sh\n")
  914. t.sh.write("# Test driver for %s, generated by "
  915. "dso-ordering-test.py\n" % (t.test_name))
  916. t.sh.write("common_objpfx=$1\n")
  917. t.sh.write("test_wrapper_env=$2\n")
  918. t.sh.write("run_program_env=$3\n")
  919. # Remove the last space to allow concatenate extra paths.
  920. t.sh.write("library_path=$(echo $4)\n")
  921. t.sh.write("something_failed=false\n")
  922. # Starting part of Makefile fragment
  923. makefile.write("ifeq (yes,$(build-shared))\n")
  924. if need_permutation_processing:
  925. enum_permutations(t, list (t.dep_permutations.items()))
  926. else:
  927. # We have no permutations to enumerate, just process testcase normally
  928. generate_testcase(t, "")
  929. # If testcase is XFAIL, indicate so
  930. if t.xfail:
  931. makefile.write("test-xfail-%s = yes\n" % t.test_name)
  932. # Output end part of Makefile fragment
  933. expected_output_files = ""
  934. for r in t.expected_outputs.items():
  935. sfx = ""
  936. if r[0] != "":
  937. sfx = "-" + r[0].replace("=","_")
  938. expected_output_files += " $(objpfx)%s%s%s.exp" % (test_srcdir,
  939. t.test_name, sfx)
  940. makefile.write \
  941. ("$(objpfx)%s.out: $(objpfx)%s%s.sh%s "
  942. "$(common-objpfx)support/test-run-command\n"
  943. % (t.test_name, test_srcdir, t.test_name,
  944. expected_output_files))
  945. makefile.write("\t$(SHELL) $< $(common-objpfx) '$(test-wrapper-env)' "
  946. "'$(run-program-env)' '$(rpath-link)' > $@; $(evaluate-test)\n")
  947. makefile.write("ifeq ($(run-built-tests),yes)\n")
  948. if t.xtest:
  949. makefile.write("xtests-special += $(objpfx)%s.out\n" % (t.test_name))
  950. else:
  951. makefile.write("tests-special += $(objpfx)%s.out\n" % (t.test_name))
  952. makefile.write("endif\n")
  953. makefile.write("endif\n")
  954. # Write ending part of shell script generation
  955. t.sh.write("if $something_failed; then\n"
  956. " exit 1\n"
  957. "else\n"
  958. " echo '%sPASS: all tests for %s succeeded'\n"
  959. " exit 0\n"
  960. "fi\n" % (("X" if t.xfail else ""),
  961. t.test_name))
  962. t.sh.close()
  963. # Description file parsing
  964. def parse_description_file(filename):
  965. global default_tunable_options
  966. global current_input_lineno
  967. f = open(filename)
  968. if not f:
  969. error("cannot open description file %s" % (filename))
  970. descrfile_lines = f.readlines()
  971. t = None
  972. for line in descrfile_lines:
  973. p = re.compile(r"#.*$")
  974. line = p.sub("", line) # Filter out comments
  975. line = line.strip() # Remove excess whitespace
  976. current_input_lineno += 1
  977. m = re.match(r"^tunable_option:\s*(.*)$", line)
  978. if m:
  979. if m.group(1) == "":
  980. error("tunable option cannot be empty")
  981. default_tunable_options.append(m.group (1))
  982. continue
  983. m = re.match(r"^clear_tunables$", line)
  984. if m:
  985. default_tunable_options = []
  986. continue
  987. m = re.match(r"^([^:]+):\s*(.*)$", line)
  988. if m:
  989. lhs = m.group(1)
  990. o = re.match(r"^output(.*)$", lhs)
  991. xfail = False
  992. if not o:
  993. o = re.match(r"^xfail_output(.*)$", lhs)
  994. if o:
  995. xfail = True;
  996. if o:
  997. if not t:
  998. error("output specification without testcase description")
  999. tsstr = ""
  1000. if o.group(1):
  1001. ts = re.match(r"^\(([a-zA-Z0-9_.=]*)\)$", o.group (1))
  1002. if not ts:
  1003. error("tunable option malformed '%s'" % o.group(1))
  1004. tsstr = ts.group(1)
  1005. t.expected_outputs[tsstr] = (m.group(2), xfail)
  1006. # Any tunable option XFAILed means entire testcase
  1007. # is XFAIL/XPASS
  1008. t.xfail |= xfail
  1009. else:
  1010. if t:
  1011. # Starting a new test description, end and process
  1012. # current one.
  1013. process_testcase(t)
  1014. t = TestDescr()
  1015. x = re.match(r"^xtest\((.*)\)$", lhs)
  1016. if x:
  1017. t.xtest = True
  1018. t.test_name = x.group(1)
  1019. else:
  1020. t.test_name = lhs
  1021. descr_string = m.group(2)
  1022. parse_description_string(t, descr_string)
  1023. continue
  1024. else:
  1025. if line:
  1026. if not t:
  1027. error("no active testcase description")
  1028. parse_description_string(t, line)
  1029. # Process last completed test description
  1030. if t:
  1031. process_testcase(t)
  1032. # Setup Makefile output to file or stdout as selected
  1033. if output_makefile:
  1034. output_makefile_dir = os.path.dirname(output_makefile)
  1035. if output_makefile_dir:
  1036. os.makedirs(output_makefile_dir, exist_ok = True)
  1037. makefile = open(output_makefile, "w")
  1038. else:
  1039. makefile = open(sys.stdout.fileno (), "w")
  1040. # Finally, the main top-level calling of above parsing routines.
  1041. if description_file:
  1042. parse_description_file(description_file)
  1043. else:
  1044. t = TestDescr()
  1045. t.test_name = test_name
  1046. parse_description_string(t, description)
  1047. process_testcase(t)
  1048. # Close Makefile fragment output
  1049. makefile.close()