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'
19 # Use temporary files to replace /dev/null on Windows.
20 kAvoidDevNull = platform.system() == 'Windows'
22 def executeCommand(command, cwd=None, env=None):
23 p = subprocess.Popen(command, cwd=cwd,
24 stdin=subprocess.PIPE,
25 stdout=subprocess.PIPE,
26 stderr=subprocess.PIPE,
28 out,err = p.communicate()
31 # Detect Ctrl-C in subprocess.
32 if exitCode == -signal.SIGINT:
33 raise KeyboardInterrupt
35 return out, err, exitCode
37 def executeShCmd(cmd, cfg, cwd, results):
38 if isinstance(cmd, ShUtil.Seq):
40 res = executeShCmd(cmd.lhs, cfg, cwd, results)
41 return executeShCmd(cmd.rhs, cfg, cwd, results)
44 raise NotImplementedError,"unsupported test command: '&'"
47 res = executeShCmd(cmd.lhs, cfg, cwd, results)
49 res = executeShCmd(cmd.rhs, cfg, cwd, results)
52 res = executeShCmd(cmd.lhs, cfg, cwd, results)
57 res = executeShCmd(cmd.rhs, cfg, cwd, results)
60 raise ValueError,'Unknown shell command: %r' % cmd.op
62 assert isinstance(cmd, ShUtil.Pipeline)
64 input = subprocess.PIPE
67 # To avoid deadlock, we use a single stderr stream for piped
68 # output. This is null until we have seen some output using
70 for i,j in enumerate(cmd.commands):
71 # Apply the redirections, we use (N,) as a sentinal to indicate stdin,
72 # stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or
73 # from a file are represented with a list [file, mode, file-object]
74 # where file-object is initially None.
75 redirects = [(0,), (1,), (2,)]
78 redirects[2] = [r[1], 'w', None]
79 elif r[0] == ('>>',2):
80 redirects[2] = [r[1], 'a', None]
81 elif r[0] == ('>&',2) and r[1] in '012':
82 redirects[2] = redirects[int(r[1])]
83 elif r[0] == ('>&',) or r[0] == ('&>',):
84 redirects[1] = redirects[2] = [r[1], 'w', None]
86 redirects[1] = [r[1], 'w', None]
88 redirects[1] = [r[1], 'a', None]
90 redirects[0] = [r[1], 'r', None]
92 raise NotImplementedError,"Unsupported redirect: %r" % (r,)
94 # Map from the final redirections to something subprocess can handle.
96 for index,r in enumerate(redirects):
101 raise NotImplementedError,"Unsupported redirect for stdin"
103 result = subprocess.PIPE
105 result = subprocess.STDOUT
108 raise NotImplementedError,"Unsupported redirect on stdout"
109 result = subprocess.PIPE
112 if kAvoidDevNull and r[0] == '/dev/null':
113 r[2] = tempfile.TemporaryFile(mode=r[1])
115 r[2] = open(r[0], r[1])
116 # Workaround a Win32 and/or subprocess bug when appending.
118 # FIXME: Actually, this is probably an instance of PR6753.
121 opened_files.append(r[2])
123 final_redirects.append(result)
125 stdin, stdout, stderr = final_redirects
127 # If stderr wants to come from stdout, but stdout isn't a pipe, then put
128 # stderr on a pipe and treat it as stdout.
129 if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE):
130 stderr = subprocess.PIPE
131 stderrIsStdout = True
133 stderrIsStdout = False
135 # Don't allow stderr on a PIPE except for the last
136 # process, this could deadlock.
138 # FIXME: This is slow, but so is deadlock.
139 if stderr == subprocess.PIPE and j != cmd.commands[-1]:
140 stderr = tempfile.TemporaryFile(mode='w+b')
141 stderrTempFiles.append((i, stderr))
143 # Resolve the executable path ourselves.
145 args[0] = Util.which(args[0], cfg.environment['PATH'])
147 raise InternalShellError(j, '%r: command not found' % j.args[0])
149 procs.append(subprocess.Popen(args, cwd=cwd,
153 env = cfg.environment,
154 close_fds = kUseCloseFDs))
156 # Immediately close stdin for any process taking stdin from us.
157 if stdin == subprocess.PIPE:
158 procs[-1].stdin.close()
159 procs[-1].stdin = None
161 # Update the current stdin source.
162 if stdout == subprocess.PIPE:
163 input = procs[-1].stdout
165 input = procs[-1].stderr
167 input = subprocess.PIPE
169 # FIXME: There is probably still deadlock potential here. Yawn.
170 procData = [None] * len(procs)
171 procData[-1] = procs[-1].communicate()
173 for i in range(len(procs) - 1):
174 if procs[i].stdout is not None:
175 out = procs[i].stdout.read()
178 if procs[i].stderr is not None:
179 err = procs[i].stderr.read()
182 procData[i] = (out,err)
184 # Read stderr out of the temp files.
185 for i,f in stderrTempFiles:
187 procData[i] = (procData[i][0], f.read())
190 for i,(out,err) in enumerate(procData):
191 res = procs[i].wait()
192 # Detect Ctrl-C in subprocess.
193 if res == -signal.SIGINT:
194 raise KeyboardInterrupt
196 results.append((cmd.commands[i], out, err, res))
198 # Python treats the exit code as a signed char.
200 exitCode = min(exitCode, res)
202 exitCode = max(exitCode, res)
206 # Explicitly close any redirected files.
207 for f in opened_files:
211 exitCode = not exitCode
215 def executeScriptInternal(test, litConfig, tmpBase, commands, cwd):
216 ln = ' &&\n'.join(commands)
218 cmd = ShUtil.ShParser(ln, litConfig.isWindows).parse()
220 return (Test.FAIL, "shell parser error on: %r" % ln)
224 exitCode = executeShCmd(cmd, test.config, cwd, results)
225 except InternalShellError,e:
231 for i,(cmd, cmd_out,cmd_err,res) in enumerate(results):
232 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
233 out += 'Command %d Result: %r\n' % (i, res)
234 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
235 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
237 return out, err, exitCode
239 def executeTclScriptInternal(test, litConfig, tmpBase, commands, cwd):
243 # Given the unfortunate way LLVM's test are written, the line gets
244 # backslash substitution done twice.
245 ln = TclUtil.TclLexer(ln).lex_unquoted(process_all = True)
248 tokens = list(TclUtil.TclLexer(ln).lex())
250 return (Test.FAIL, "Tcl lexer error on: %r" % ln)
252 # Validate there are no control tokens.
254 if not isinstance(t, str):
256 "Invalid test line: %r containing %r" % (ln, t))
259 cmds.append(TclUtil.TclExecCommand(tokens).parse_pipeline())
261 return (Test.FAIL, "Tcl 'exec' parse error on: %r" % ln)
263 if litConfig.useValgrind:
264 for pipeline in cmds:
265 if pipeline.commands:
266 # Only valgrind the first command in each pipeline, to avoid
267 # valgrinding things like grep, not, and FileCheck.
268 cmd = pipeline.commands[0]
269 cmd.args = litConfig.valgrindArgs + cmd.args
273 cmd = ShUtil.Seq(cmd, '&&', c)
275 # FIXME: This is lame, we shouldn't need bash. See PR5240.
276 bashPath = litConfig.getBashPath()
277 if litConfig.useTclAsSh and bashPath:
278 script = tmpBase + '.script'
282 print >>f, 'set -o pipefail'
283 cmd.toShell(f, pipefail = True)
287 print >>sys.stdout, cmd
288 print >>sys.stdout, open(script).read()
292 command = [litConfig.getBashPath(), script]
293 out,err,exitCode = executeCommand(command, cwd=cwd,
294 env=test.config.environment)
296 # Tcl commands fail on standard error output.
299 out = 'Command has output on stderr!\n\n' + out
301 return out,err,exitCode
305 exitCode = executeShCmd(cmd, test.config, cwd, results)
306 except InternalShellError,e:
307 results.append((e.command, '', e.message + '\n', 255))
312 # Tcl commands fail on standard error output.
313 if [True for _,_,err,res in results if err]:
315 out += 'Command has output on stderr!\n\n'
317 for i,(cmd, cmd_out, cmd_err, res) in enumerate(results):
318 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
319 out += 'Command %d Result: %r\n' % (i, res)
320 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
321 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
323 return out, err, exitCode
325 def executeScript(test, litConfig, tmpBase, commands, cwd):
326 script = tmpBase + '.script'
327 if litConfig.isWindows:
332 if litConfig.isWindows:
333 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
335 f.write(' &&\n'.join(commands))
339 if litConfig.isWindows:
340 command = ['cmd','/c', script]
342 command = ['/bin/sh', script]
343 if litConfig.useValgrind:
344 # FIXME: Running valgrind on sh is overkill. We probably could just
345 # run on clang with no real loss.
346 command = litConfig.valgrindArgs + command
348 return executeCommand(command, cwd=cwd, env=test.config.environment)
350 def isExpectedFail(xfails, xtargets, target_triple):
351 # Check if any xfail matches this target.
353 if item == '*' or item in target_triple:
358 # If so, see if it is expected to pass on this target.
360 # FIXME: Rename XTARGET to something that makes sense, like XPASS.
361 for item in xtargets:
362 if item == '*' or item in target_triple:
367 def parseIntegratedTestScript(test):
368 """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test
369 script and extract the lines to 'RUN' as well as 'XFAIL' and 'XTARGET'
370 information. The RUN lines also will have variable substitution performed.
373 # Get the temporary location, this is always relative to the test suite
374 # root, not test source root.
376 # FIXME: This should not be here?
377 sourcepath = test.getSourcePath()
378 execpath = test.getExecPath()
379 execdir,execbase = os.path.split(execpath)
380 tmpBase = os.path.join(execdir, 'Output', execbase)
381 if test.index is not None:
382 tmpBase += '_%d' % test.index
384 # We use #_MARKER_# to hide %% while we do the other substitutions.
385 substitutions = [('%%', '#_MARKER_#')]
386 substitutions.extend(test.config.substitutions)
387 substitutions.extend([('%s', sourcepath),
388 ('%S', os.path.dirname(sourcepath)),
389 ('%p', os.path.dirname(sourcepath)),
390 ('%t', tmpBase + '.tmp'),
391 # FIXME: Remove this once we kill DejaGNU.
392 ('%abs_tmp', tmpBase + '.tmp'),
393 ('#_MARKER_#', '%')])
395 # Collect the test lines from the script.
399 for ln in open(sourcepath):
401 # Isolate the command to run.
402 index = ln.index('RUN:')
405 # Trim trailing whitespace.
408 # Collapse lines with trailing '\\'.
409 if script and script[-1][-1] == '\\':
410 script[-1] = script[-1][:-1] + ln
414 items = ln[ln.index('XFAIL:') + 6:].split(',')
415 xfails.extend([s.strip() for s in items])
416 elif 'XTARGET:' in ln:
417 items = ln[ln.index('XTARGET:') + 8:].split(',')
418 xtargets.extend([s.strip() for s in items])
420 # Check for END. lines.
421 if ln[ln.index('END.'):].strip() == 'END.':
424 # Apply substitutions to the script.
426 # Apply substitutions
427 for a,b in substitutions:
430 # Strip the trailing newline and any extra whitespace.
432 script = map(processLine, script)
434 # Verify the script contains a run line.
436 return (Test.UNRESOLVED, "Test has no run line!")
438 if script[-1][-1] == '\\':
439 return (Test.UNRESOLVED, "Test has unterminated run lines (with '\\')")
441 isXFail = isExpectedFail(xfails, xtargets, test.suite.config.target_triple)
442 return script,isXFail,tmpBase,execdir
444 def formatTestOutput(status, out, err, exitCode, script):
445 output = StringIO.StringIO()
446 print >>output, "Script:"
448 print >>output, '\n'.join(script)
450 print >>output, "Exit Code: %r" % exitCode
451 print >>output, "Command Output (stdout):"
455 print >>output, "Command Output (stderr):"
459 return (status, output.getvalue())
461 def executeTclTest(test, litConfig):
462 if test.config.unsupported:
463 return (Test.UNSUPPORTED, 'Test is unsupported')
465 res = parseIntegratedTestScript(test)
469 script, isXFail, tmpBase, execdir = res
471 if litConfig.noExecute:
472 return (Test.PASS, '')
474 # Create the output directory if it does not already exist.
475 Util.mkdir_p(os.path.dirname(tmpBase))
477 res = executeTclScriptInternal(test, litConfig, tmpBase, script, execdir)
481 out,err,exitCode = res
484 status = (Test.XPASS, Test.XFAIL)[ok]
487 status = (Test.FAIL, Test.PASS)[ok]
492 return formatTestOutput(status, out, err, exitCode, script)
494 def executeShTest(test, litConfig, useExternalSh):
495 if test.config.unsupported:
496 return (Test.UNSUPPORTED, 'Test is unsupported')
498 res = parseIntegratedTestScript(test)
502 script, isXFail, tmpBase, execdir = res
504 if litConfig.noExecute:
505 return (Test.PASS, '')
507 # Create the output directory if it does not already exist.
508 Util.mkdir_p(os.path.dirname(tmpBase))
511 res = executeScript(test, litConfig, tmpBase, script, execdir)
513 res = executeScriptInternal(test, litConfig, tmpBase, script, execdir)
517 out,err,exitCode = res
520 status = (Test.XPASS, Test.XFAIL)[ok]
523 status = (Test.FAIL, Test.PASS)[ok]
528 return formatTestOutput(status, out, err, exitCode, script)