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 kIsWindows = platform.system() == 'Windows'
18 # Don't use close_fds on Windows.
19 kUseCloseFDs = not kIsWindows
21 # Use temporary files to replace /dev/null on Windows.
22 kAvoidDevNull = kIsWindows
24 def executeCommand(command, cwd=None, env=None):
25 p = subprocess.Popen(command, cwd=cwd,
26 stdin=subprocess.PIPE,
27 stdout=subprocess.PIPE,
28 stderr=subprocess.PIPE,
30 out,err = p.communicate()
33 # Detect Ctrl-C in subprocess.
34 if exitCode == -signal.SIGINT:
35 raise KeyboardInterrupt
37 return out, err, exitCode
39 def executeShCmd(cmd, cfg, cwd, results):
40 if isinstance(cmd, ShUtil.Seq):
42 res = executeShCmd(cmd.lhs, cfg, cwd, results)
43 return executeShCmd(cmd.rhs, cfg, cwd, results)
46 raise NotImplementedError,"unsupported test command: '&'"
49 res = executeShCmd(cmd.lhs, cfg, cwd, results)
51 res = executeShCmd(cmd.rhs, cfg, cwd, results)
54 res = executeShCmd(cmd.lhs, cfg, cwd, results)
59 res = executeShCmd(cmd.rhs, cfg, cwd, results)
62 raise ValueError,'Unknown shell command: %r' % cmd.op
64 assert isinstance(cmd, ShUtil.Pipeline)
66 input = subprocess.PIPE
69 # To avoid deadlock, we use a single stderr stream for piped
70 # output. This is null until we have seen some output using
72 for i,j in enumerate(cmd.commands):
73 # Apply the redirections, we use (N,) as a sentinal to indicate stdin,
74 # stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or
75 # from a file are represented with a list [file, mode, file-object]
76 # where file-object is initially None.
77 redirects = [(0,), (1,), (2,)]
80 redirects[2] = [r[1], 'w', None]
81 elif r[0] == ('>>',2):
82 redirects[2] = [r[1], 'a', None]
83 elif r[0] == ('>&',2) and r[1] in '012':
84 redirects[2] = redirects[int(r[1])]
85 elif r[0] == ('>&',) or r[0] == ('&>',):
86 redirects[1] = redirects[2] = [r[1], 'w', None]
88 redirects[1] = [r[1], 'w', None]
90 redirects[1] = [r[1], 'a', None]
92 redirects[0] = [r[1], 'r', None]
94 raise NotImplementedError,"Unsupported redirect: %r" % (r,)
96 # Map from the final redirections to something subprocess can handle.
98 for index,r in enumerate(redirects):
103 raise NotImplementedError,"Unsupported redirect for stdin"
105 result = subprocess.PIPE
107 result = subprocess.STDOUT
110 raise NotImplementedError,"Unsupported redirect on stdout"
111 result = subprocess.PIPE
114 if kAvoidDevNull and r[0] == '/dev/null':
115 r[2] = tempfile.TemporaryFile(mode=r[1])
117 r[2] = open(r[0], r[1])
118 # Workaround a Win32 and/or subprocess bug when appending.
120 # FIXME: Actually, this is probably an instance of PR6753.
123 opened_files.append(r[2])
125 final_redirects.append(result)
127 stdin, stdout, stderr = final_redirects
129 # If stderr wants to come from stdout, but stdout isn't a pipe, then put
130 # stderr on a pipe and treat it as stdout.
131 if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE):
132 stderr = subprocess.PIPE
133 stderrIsStdout = True
135 stderrIsStdout = False
137 # Don't allow stderr on a PIPE except for the last
138 # process, this could deadlock.
140 # FIXME: This is slow, but so is deadlock.
141 if stderr == subprocess.PIPE and j != cmd.commands[-1]:
142 stderr = tempfile.TemporaryFile(mode='w+b')
143 stderrTempFiles.append((i, stderr))
145 # Resolve the executable path ourselves.
147 args[0] = Util.which(args[0], cfg.environment['PATH'])
149 raise InternalShellError(j, '%r: command not found' % j.args[0])
151 procs.append(subprocess.Popen(args, cwd=cwd,
155 env = cfg.environment,
156 close_fds = kUseCloseFDs))
158 # Immediately close stdin for any process taking stdin from us.
159 if stdin == subprocess.PIPE:
160 procs[-1].stdin.close()
161 procs[-1].stdin = None
163 # Update the current stdin source.
164 if stdout == subprocess.PIPE:
165 input = procs[-1].stdout
167 input = procs[-1].stderr
169 input = subprocess.PIPE
171 # FIXME: There is probably still deadlock potential here. Yawn.
172 procData = [None] * len(procs)
173 procData[-1] = procs[-1].communicate()
175 for i in range(len(procs) - 1):
176 if procs[i].stdout is not None:
177 out = procs[i].stdout.read()
180 if procs[i].stderr is not None:
181 err = procs[i].stderr.read()
184 procData[i] = (out,err)
186 # Read stderr out of the temp files.
187 for i,f in stderrTempFiles:
189 procData[i] = (procData[i][0], f.read())
192 for i,(out,err) in enumerate(procData):
193 res = procs[i].wait()
194 # Detect Ctrl-C in subprocess.
195 if res == -signal.SIGINT:
196 raise KeyboardInterrupt
198 results.append((cmd.commands[i], out, err, res))
200 # Python treats the exit code as a signed char.
202 exitCode = min(exitCode, res)
204 exitCode = max(exitCode, res)
208 # Explicitly close any redirected files.
209 for f in opened_files:
213 exitCode = not exitCode
217 def executeScriptInternal(test, litConfig, tmpBase, commands, cwd):
218 ln = ' &&\n'.join(commands)
220 cmd = ShUtil.ShParser(ln, litConfig.isWindows).parse()
222 return (Test.FAIL, "shell parser error on: %r" % ln)
226 exitCode = executeShCmd(cmd, test.config, cwd, results)
227 except InternalShellError,e:
233 for i,(cmd, cmd_out,cmd_err,res) in enumerate(results):
234 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
235 out += 'Command %d Result: %r\n' % (i, res)
236 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
237 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
239 return out, err, exitCode
241 def executeTclScriptInternal(test, litConfig, tmpBase, commands, cwd):
245 # Given the unfortunate way LLVM's test are written, the line gets
246 # backslash substitution done twice.
247 ln = TclUtil.TclLexer(ln).lex_unquoted(process_all = True)
250 tokens = list(TclUtil.TclLexer(ln).lex())
252 return (Test.FAIL, "Tcl lexer error on: %r" % ln)
254 # Validate there are no control tokens.
256 if not isinstance(t, str):
258 "Invalid test line: %r containing %r" % (ln, t))
261 cmds.append(TclUtil.TclExecCommand(tokens).parse_pipeline())
263 return (Test.FAIL, "Tcl 'exec' parse error on: %r" % ln)
265 if litConfig.useValgrind:
266 for pipeline in cmds:
267 if pipeline.commands:
268 # Only valgrind the first command in each pipeline, to avoid
269 # valgrinding things like grep, not, and FileCheck.
270 cmd = pipeline.commands[0]
271 cmd.args = litConfig.valgrindArgs + cmd.args
275 cmd = ShUtil.Seq(cmd, '&&', c)
277 # FIXME: This is lame, we shouldn't need bash. See PR5240.
278 bashPath = litConfig.getBashPath()
279 if litConfig.useTclAsSh and bashPath:
280 script = tmpBase + '.script'
284 print >>f, 'set -o pipefail'
285 cmd.toShell(f, pipefail = True)
289 print >>sys.stdout, cmd
290 print >>sys.stdout, open(script).read()
294 command = [litConfig.getBashPath(), script]
295 out,err,exitCode = executeCommand(command, cwd=cwd,
296 env=test.config.environment)
298 # Tcl commands fail on standard error output.
301 out = 'Command has output on stderr!\n\n' + out
303 return out,err,exitCode
307 exitCode = executeShCmd(cmd, test.config, cwd, results)
308 except InternalShellError,e:
309 results.append((e.command, '', e.message + '\n', 255))
314 # Tcl commands fail on standard error output.
315 if [True for _,_,err,res in results if err]:
317 out += 'Command has output on stderr!\n\n'
319 for i,(cmd, cmd_out, cmd_err, res) in enumerate(results):
320 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
321 out += 'Command %d Result: %r\n' % (i, res)
322 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
323 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
325 return out, err, exitCode
327 def executeScript(test, litConfig, tmpBase, commands, cwd):
328 script = tmpBase + '.script'
329 if litConfig.isWindows:
334 if litConfig.isWindows:
335 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
337 f.write(' &&\n'.join(commands))
341 if litConfig.isWindows:
342 command = ['cmd','/c', script]
344 command = ['/bin/sh', script]
345 if litConfig.useValgrind:
346 # FIXME: Running valgrind on sh is overkill. We probably could just
347 # run on clang with no real loss.
348 command = litConfig.valgrindArgs + command
350 return executeCommand(command, cwd=cwd, env=test.config.environment)
352 def isExpectedFail(xfails, xtargets, target_triple):
353 # Check if any xfail matches this target.
355 if item == '*' or item in target_triple:
360 # If so, see if it is expected to pass on this target.
362 # FIXME: Rename XTARGET to something that makes sense, like XPASS.
363 for item in xtargets:
364 if item == '*' or item in target_triple:
369 def parseIntegratedTestScript(test, normalize_slashes):
370 """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test
371 script and extract the lines to 'RUN' as well as 'XFAIL' and 'XTARGET'
372 information. The RUN lines also will have variable substitution performed.
375 # Get the temporary location, this is always relative to the test suite
376 # root, not test source root.
378 # FIXME: This should not be here?
379 sourcepath = test.getSourcePath()
380 sourcedir = os.path.dirname(sourcepath)
381 execpath = test.getExecPath()
382 execdir,execbase = os.path.split(execpath)
383 tmpBase = os.path.join(execdir, 'Output', execbase)
384 if test.index is not None:
385 tmpBase += '_%d' % test.index
387 # Normalize slashes, if requested.
388 if normalize_slashes:
389 sourcepath = sourcepath.replace('\\', '/')
390 sourcedir = sourcedir.replace('\\', '/')
391 tmpBase = tmpBase.replace('\\', '/')
393 # We use #_MARKER_# to hide %% while we do the other substitutions.
394 substitutions = [('%%', '#_MARKER_#')]
395 substitutions.extend(test.config.substitutions)
396 substitutions.extend([('%s', sourcepath),
399 ('%t', tmpBase + '.tmp'),
400 # FIXME: Remove this once we kill DejaGNU.
401 ('%abs_tmp', tmpBase + '.tmp'),
402 ('#_MARKER_#', '%')])
404 # Collect the test lines from the script.
408 for ln in open(sourcepath):
410 # Isolate the command to run.
411 index = ln.index('RUN:')
414 # Trim trailing whitespace.
417 # Collapse lines with trailing '\\'.
418 if script and script[-1][-1] == '\\':
419 script[-1] = script[-1][:-1] + ln
423 items = ln[ln.index('XFAIL:') + 6:].split(',')
424 xfails.extend([s.strip() for s in items])
425 elif 'XTARGET:' in ln:
426 items = ln[ln.index('XTARGET:') + 8:].split(',')
427 xtargets.extend([s.strip() for s in items])
429 # Check for END. lines.
430 if ln[ln.index('END.'):].strip() == 'END.':
433 # Apply substitutions to the script.
435 # Apply substitutions
436 for a,b in substitutions:
439 # Strip the trailing newline and any extra whitespace.
441 script = map(processLine, script)
443 # Verify the script contains a run line.
445 return (Test.UNRESOLVED, "Test has no run line!")
447 if script[-1][-1] == '\\':
448 return (Test.UNRESOLVED, "Test has unterminated run lines (with '\\')")
450 isXFail = isExpectedFail(xfails, xtargets, test.suite.config.target_triple)
451 return script,isXFail,tmpBase,execdir
453 def formatTestOutput(status, out, err, exitCode, script):
454 output = StringIO.StringIO()
455 print >>output, "Script:"
457 print >>output, '\n'.join(script)
459 print >>output, "Exit Code: %r" % exitCode
460 print >>output, "Command Output (stdout):"
464 print >>output, "Command Output (stderr):"
468 return (status, output.getvalue())
470 def executeTclTest(test, litConfig):
471 if test.config.unsupported:
472 return (Test.UNSUPPORTED, 'Test is unsupported')
474 # Parse the test script, normalizing slashes in substitutions on Windows
475 # (since otherwise Tcl style lexing will treat them as escapes).
476 res = parseIntegratedTestScript(test, normalize_slashes=kIsWindows)
480 script, isXFail, tmpBase, execdir = res
482 if litConfig.noExecute:
483 return (Test.PASS, '')
485 # Create the output directory if it does not already exist.
486 Util.mkdir_p(os.path.dirname(tmpBase))
488 res = executeTclScriptInternal(test, litConfig, tmpBase, script, execdir)
492 out,err,exitCode = res
495 status = (Test.XPASS, Test.XFAIL)[ok]
498 status = (Test.FAIL, Test.PASS)[ok]
503 return formatTestOutput(status, out, err, exitCode, script)
505 def executeShTest(test, litConfig, useExternalSh):
506 if test.config.unsupported:
507 return (Test.UNSUPPORTED, 'Test is unsupported')
509 res = parseIntegratedTestScript(test)
513 script, isXFail, tmpBase, execdir = res
515 if litConfig.noExecute:
516 return (Test.PASS, '')
518 # Create the output directory if it does not already exist.
519 Util.mkdir_p(os.path.dirname(tmpBase))
522 res = executeScript(test, litConfig, tmpBase, script, execdir)
524 res = executeScriptInternal(test, litConfig, tmpBase, script, execdir)
528 out,err,exitCode = res
531 status = (Test.XPASS, Test.XFAIL)[ok]
534 status = (Test.FAIL, Test.PASS)[ok]
539 return formatTestOutput(status, out, err, exitCode, script)