1 import os, signal, subprocess, sys
11 class InternalShellError(Exception):
12 def __init__(self, command, message):
13 self.command = command
14 self.message = message
16 # Don't use close_fds on Windows.
17 kUseCloseFDs = platform.system() != 'Windows'
18 def executeCommand(command, cwd=None, env=None):
19 p = subprocess.Popen(command, cwd=cwd,
20 stdin=subprocess.PIPE,
21 stdout=subprocess.PIPE,
22 stderr=subprocess.PIPE,
24 out,err = p.communicate()
27 # Detect Ctrl-C in subprocess.
28 if exitCode == -signal.SIGINT:
29 raise KeyboardInterrupt
31 return out, err, exitCode
33 def executeShCmd(cmd, cfg, cwd, results):
34 if isinstance(cmd, ShUtil.Seq):
36 res = executeShCmd(cmd.lhs, cfg, cwd, results)
37 return executeShCmd(cmd.rhs, cfg, cwd, results)
40 raise NotImplementedError,"unsupported test command: '&'"
43 res = executeShCmd(cmd.lhs, cfg, cwd, results)
45 res = executeShCmd(cmd.rhs, cfg, cwd, results)
48 res = executeShCmd(cmd.lhs, cfg, cwd, results)
53 res = executeShCmd(cmd.rhs, cfg, cwd, results)
56 raise ValueError,'Unknown shell command: %r' % cmd.op
58 assert isinstance(cmd, ShUtil.Pipeline)
60 input = subprocess.PIPE
62 # To avoid deadlock, we use a single stderr stream for piped
63 # output. This is null until we have seen some output using
65 for i,j in enumerate(cmd.commands):
66 redirects = [(0,), (1,), (2,)]
69 redirects[2] = [r[1], 'w', None]
70 elif r[0] == ('>&',2) and r[1] in '012':
71 redirects[2] = redirects[int(r[1])]
72 elif r[0] == ('>&',) or r[0] == ('&>',):
73 redirects[1] = redirects[2] = [r[1], 'w', None]
75 redirects[1] = [r[1], 'w', None]
77 redirects[0] = [r[1], 'r', None]
79 raise NotImplementedError,"Unsupported redirect: %r" % (r,)
82 for index,r in enumerate(redirects):
87 raise NotImplementedError,"Unsupported redirect for stdin"
89 result = subprocess.PIPE
91 result = subprocess.STDOUT
94 raise NotImplementedError,"Unsupported redirect on stdout"
95 result = subprocess.PIPE
98 r[2] = open(r[0], r[1])
100 final_redirects.append(result)
102 stdin, stdout, stderr = final_redirects
104 # If stderr wants to come from stdout, but stdout isn't a pipe, then put
105 # stderr on a pipe and treat it as stdout.
106 if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE):
107 stderr = subprocess.PIPE
108 stderrIsStdout = True
110 stderrIsStdout = False
112 # Don't allow stderr on a PIPE except for the last
113 # process, this could deadlock.
115 # FIXME: This is slow, but so is deadlock.
116 if stderr == subprocess.PIPE and j != cmd.commands[-1]:
117 stderr = tempfile.TemporaryFile(mode='w+b')
118 stderrTempFiles.append((i, stderr))
120 # Resolve the executable path ourselves.
122 args[0] = Util.which(args[0], cfg.environment['PATH'])
124 raise InternalShellError(j, '%r: command not found' % j.args[0])
126 procs.append(subprocess.Popen(args, cwd=cwd,
130 env = cfg.environment,
131 close_fds = kUseCloseFDs))
133 # Immediately close stdin for any process taking stdin from us.
134 if stdin == subprocess.PIPE:
135 procs[-1].stdin.close()
136 procs[-1].stdin = None
138 # Update the current stdin source.
139 if stdout == subprocess.PIPE:
140 input = procs[-1].stdout
142 input = procs[-1].stderr
144 input = subprocess.PIPE
146 # FIXME: There is probably still deadlock potential here. Yawn.
147 procData = [None] * len(procs)
148 procData[-1] = procs[-1].communicate()
150 for i in range(len(procs) - 1):
151 if procs[i].stdout is not None:
152 out = procs[i].stdout.read()
155 if procs[i].stderr is not None:
156 err = procs[i].stderr.read()
159 procData[i] = (out,err)
161 # Read stderr out of the temp files.
162 for i,f in stderrTempFiles:
164 procData[i] = (procData[i][0], f.read())
167 for i,(out,err) in enumerate(procData):
168 res = procs[i].wait()
169 # Detect Ctrl-C in subprocess.
170 if res == -signal.SIGINT:
171 raise KeyboardInterrupt
173 results.append((cmd.commands[i], out, err, res))
175 # Python treats the exit code as a signed char.
177 exitCode = min(exitCode, res)
179 exitCode = max(exitCode, res)
184 exitCode = not exitCode
188 def executeScriptInternal(test, litConfig, tmpBase, commands, cwd):
189 ln = ' &&\n'.join(commands)
191 cmd = ShUtil.ShParser(ln, litConfig.isWindows).parse()
193 return (Test.FAIL, "shell parser error on: %r" % ln)
197 exitCode = executeShCmd(cmd, test.config, cwd, results)
198 except InternalShellError,e:
204 for i,(cmd, cmd_out,cmd_err,res) in enumerate(results):
205 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
206 out += 'Command %d Result: %r\n' % (i, res)
207 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
208 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
210 return out, err, exitCode
212 def executeTclScriptInternal(test, litConfig, tmpBase, commands, cwd):
216 # Given the unfortunate way LLVM's test are written, the line gets
217 # backslash substitution done twice.
218 ln = TclUtil.TclLexer(ln).lex_unquoted(process_all = True)
221 tokens = list(TclUtil.TclLexer(ln).lex())
223 return (Test.FAIL, "Tcl lexer error on: %r" % ln)
225 # Validate there are no control tokens.
227 if not isinstance(t, str):
229 "Invalid test line: %r containing %r" % (ln, t))
232 cmds.append(TclUtil.TclExecCommand(tokens).parse_pipeline())
234 return (Test.FAIL, "Tcl 'exec' parse error on: %r" % ln)
238 cmd = ShUtil.Seq(cmd, '&&', c)
240 # FIXME: This is lame, we shouldn't need bash. See PR5240.
241 bashPath = litConfig.getBashPath()
242 if litConfig.useTclAsSh and bashPath:
243 script = tmpBase + '.script'
247 print >>f, 'set -o pipefail'
248 cmd.toShell(f, pipefail = True)
252 print >>sys.stdout, cmd
253 print >>sys.stdout, open(script).read()
257 command = [litConfig.getBashPath(), script]
258 out,err,exitCode = executeCommand(command, cwd=cwd,
259 env=test.config.environment)
261 # Tcl commands fail on standard error output.
264 out = 'Command has output on stderr!\n\n' + out
266 return out,err,exitCode
270 exitCode = executeShCmd(cmd, test.config, cwd, results)
271 except InternalShellError,e:
272 results.append((e.command, '', e.message + '\n', 255))
277 # Tcl commands fail on standard error output.
278 if [True for _,_,err,res in results if err]:
280 out += 'Command has output on stderr!\n\n'
282 for i,(cmd, cmd_out, cmd_err, res) in enumerate(results):
283 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
284 out += 'Command %d Result: %r\n' % (i, res)
285 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
286 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
288 return out, err, exitCode
290 def executeScript(test, litConfig, tmpBase, commands, cwd):
291 script = tmpBase + '.script'
292 if litConfig.isWindows:
297 if litConfig.isWindows:
298 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
300 f.write(' &&\n'.join(commands))
304 if litConfig.isWindows:
305 command = ['cmd','/c', script]
307 command = ['/bin/sh', script]
308 if litConfig.useValgrind:
309 # FIXME: Running valgrind on sh is overkill. We probably could just
310 # run on clang with no real loss.
311 valgrindArgs = ['valgrind', '-q',
312 '--tool=memcheck', '--trace-children=yes',
313 '--error-exitcode=123']
314 valgrindArgs.extend(litConfig.valgrindArgs)
316 command = valgrindArgs + command
318 return executeCommand(command, cwd=cwd, env=test.config.environment)
320 def parseIntegratedTestScript(test, xfailHasColon, requireAndAnd):
321 """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test
322 script and extract the lines to 'RUN' as well as 'XFAIL' and 'XTARGET'
323 information. The RUN lines also will have variable substitution performed.
326 # Get the temporary location, this is always relative to the test suite
327 # root, not test source root.
329 # FIXME: This should not be here?
330 sourcepath = test.getSourcePath()
331 execpath = test.getExecPath()
332 execdir,execbase = os.path.split(execpath)
333 tmpBase = os.path.join(execdir, 'Output', execbase)
335 # We use #_MARKER_# to hide %% while we do the other substitutions.
336 substitutions = [('%%', '#_MARKER_#')]
337 substitutions.extend(test.config.substitutions)
338 substitutions.extend([('%s', sourcepath),
339 ('%S', os.path.dirname(sourcepath)),
340 ('%p', os.path.dirname(sourcepath)),
341 ('%t', tmpBase + '.tmp'),
342 # FIXME: Remove this once we kill DejaGNU.
343 ('%abs_tmp', tmpBase + '.tmp'),
344 ('#_MARKER_#', '%')])
346 # Collect the test lines from the script.
350 for ln in open(sourcepath):
352 # Isolate the command to run.
353 index = ln.index('RUN:')
356 # Trim trailing whitespace.
359 # Collapse lines with trailing '\\'.
360 if script and script[-1][-1] == '\\':
361 script[-1] = script[-1][:-1] + ln
364 elif xfailHasColon and 'XFAIL:' in ln:
365 items = ln[ln.index('XFAIL:') + 6:].split(',')
366 xfails.extend([s.strip() for s in items])
367 elif not xfailHasColon and 'XFAIL' in ln:
368 items = ln[ln.index('XFAIL') + 5:].split(',')
369 xfails.extend([s.strip() for s in items])
370 elif 'XTARGET:' in ln:
371 items = ln[ln.index('XTARGET:') + 8:].split(',')
372 xtargets.extend([s.strip() for s in items])
374 # Check for END. lines.
375 if ln[ln.index('END.'):].strip() == 'END.':
378 # Apply substitutions to the script.
380 # Apply substitutions
381 for a,b in substitutions:
384 # Strip the trailing newline and any extra whitespace.
386 script = map(processLine, script)
388 # Verify the script contains a run line.
390 return (Test.UNRESOLVED, "Test has no run line!")
392 if script[-1][-1] == '\\':
393 return (Test.UNRESOLVED, "Test has unterminated run lines (with '\\')")
395 # Validate interior lines for '&&', a lovely historical artifact.
397 for i in range(len(script) - 1):
400 if not ln.endswith('&&'):
402 ("MISSING \'&&\': %s\n" +
403 "FOLLOWED BY : %s\n") % (ln, script[i + 1]))
408 return script,xfails,xtargets,tmpBase,execdir
410 def formatTestOutput(status, out, err, exitCode, script):
411 output = StringIO.StringIO()
412 print >>output, "Script:"
414 print >>output, '\n'.join(script)
416 print >>output, "Exit Code: %r" % exitCode
417 print >>output, "Command Output (stdout):"
421 print >>output, "Command Output (stderr):"
425 return (status, output.getvalue())
427 def executeTclTest(test, litConfig):
428 if test.config.unsupported:
429 return (Test.UNSUPPORTED, 'Test is unsupported')
431 res = parseIntegratedTestScript(test, True, False)
435 script, xfails, xtargets, tmpBase, execdir = res
437 if litConfig.noExecute:
438 return (Test.PASS, '')
440 # Create the output directory if it does not already exist.
441 Util.mkdir_p(os.path.dirname(tmpBase))
443 res = executeTclScriptInternal(test, litConfig, tmpBase, script, execdir)
449 if item == '*' or item in test.suite.config.target_triple:
453 # If this is XFAIL, see if it is expected to pass on this target.
455 for item in xtargets:
456 if item == '*' or item in test.suite.config.target_triple:
460 out,err,exitCode = res
463 status = (Test.XPASS, Test.XFAIL)[ok]
466 status = (Test.FAIL, Test.PASS)[ok]
471 return formatTestOutput(status, out, err, exitCode, script)
473 def executeShTest(test, litConfig, useExternalSh, requireAndAnd):
474 if test.config.unsupported:
475 return (Test.UNSUPPORTED, 'Test is unsupported')
477 res = parseIntegratedTestScript(test, False, requireAndAnd)
481 script, xfails, xtargets, tmpBase, execdir = res
483 if litConfig.noExecute:
484 return (Test.PASS, '')
486 # Create the output directory if it does not already exist.
487 Util.mkdir_p(os.path.dirname(tmpBase))
490 res = executeScript(test, litConfig, tmpBase, script, execdir)
492 res = executeScriptInternal(test, litConfig, tmpBase, script, execdir)
496 out,err,exitCode = res
499 status = (Test.XPASS, Test.XFAIL)[ok]
502 status = (Test.FAIL, Test.PASS)[ok]
507 return formatTestOutput(status, out, err, exitCode, script)