1 from __future__ import absolute_import
2 import os, signal, subprocess, sys
7 import lit.ShUtil as ShUtil
8 import lit.Test as Test
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 executeShCmd(cmd, cfg, cwd, results):
25 if isinstance(cmd, ShUtil.Seq):
27 res = executeShCmd(cmd.lhs, cfg, cwd, results)
28 return executeShCmd(cmd.rhs, cfg, cwd, results)
31 raise InternalShellError(cmd,"unsupported shell operator: '&'")
34 res = executeShCmd(cmd.lhs, cfg, cwd, results)
36 res = executeShCmd(cmd.rhs, cfg, cwd, results)
40 res = executeShCmd(cmd.lhs, cfg, cwd, results)
45 res = executeShCmd(cmd.rhs, cfg, cwd, results)
48 raise ValueError('Unknown shell command: %r' % cmd.op)
50 assert isinstance(cmd, ShUtil.Pipeline)
52 input = subprocess.PIPE
56 # To avoid deadlock, we use a single stderr stream for piped
57 # output. This is null until we have seen some output using
59 for i,j in enumerate(cmd.commands):
60 # Apply the redirections, we use (N,) as a sentinel to indicate stdin,
61 # stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or
62 # from a file are represented with a list [file, mode, file-object]
63 # where file-object is initially None.
64 redirects = [(0,), (1,), (2,)]
67 redirects[2] = [r[1], 'w', None]
68 elif r[0] == ('>>',2):
69 redirects[2] = [r[1], 'a', 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[1] = [r[1], 'a', None]
79 redirects[0] = [r[1], 'r', None]
81 raise InternalShellError(j,"Unsupported redirect: %r" % (r,))
83 # Map from the final redirections to something subprocess can handle.
85 for index,r in enumerate(redirects):
90 raise InternalShellError(j,"Unsupported redirect for stdin")
92 result = subprocess.PIPE
94 result = subprocess.STDOUT
97 raise InternalShellError(j,"Unsupported redirect on stdout")
98 result = subprocess.PIPE
101 if kAvoidDevNull and r[0] == '/dev/null':
102 r[2] = tempfile.TemporaryFile(mode=r[1])
104 r[2] = open(r[0], r[1])
105 # Workaround a Win32 and/or subprocess bug when appending.
107 # FIXME: Actually, this is probably an instance of PR6753.
110 opened_files.append(r[2])
112 final_redirects.append(result)
114 stdin, stdout, stderr = final_redirects
116 # If stderr wants to come from stdout, but stdout isn't a pipe, then put
117 # stderr on a pipe and treat it as stdout.
118 if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE):
119 stderr = subprocess.PIPE
120 stderrIsStdout = True
122 stderrIsStdout = False
124 # Don't allow stderr on a PIPE except for the last
125 # process, this could deadlock.
127 # FIXME: This is slow, but so is deadlock.
128 if stderr == subprocess.PIPE and j != cmd.commands[-1]:
129 stderr = tempfile.TemporaryFile(mode='w+b')
130 stderrTempFiles.append((i, stderr))
132 # Resolve the executable path ourselves.
134 executable = lit.util.which(args[0], cfg.environment['PATH'])
136 raise InternalShellError(j, '%r: command not found' % j.args[0])
138 # Replace uses of /dev/null with temporary files.
140 for i,arg in enumerate(args):
141 if arg == "/dev/null":
142 f = tempfile.NamedTemporaryFile(delete=False)
144 named_temp_files.append(f.name)
148 procs.append(subprocess.Popen(args, cwd=cwd,
149 executable = executable,
153 env = cfg.environment,
154 close_fds = kUseCloseFDs))
156 raise InternalShellError(j, 'Could not create process due to {}'.format(e))
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 # Explicitly close any redirected files. We need to do this now because we
172 # need to release any handles we may have on the temporary files (important
173 # on Win32, for example). Since we have already spawned the subprocess, our
174 # handles have already been transferred so we do not need them anymore.
175 for f in opened_files:
178 # FIXME: There is probably still deadlock potential here. Yawn.
179 procData = [None] * len(procs)
180 procData[-1] = procs[-1].communicate()
182 for i in range(len(procs) - 1):
183 if procs[i].stdout is not None:
184 out = procs[i].stdout.read()
187 if procs[i].stderr is not None:
188 err = procs[i].stderr.read()
191 procData[i] = (out,err)
193 # Read stderr out of the temp files.
194 for i,f in stderrTempFiles:
196 procData[i] = (procData[i][0], f.read())
198 def to_string(bytes):
199 if isinstance(bytes, str):
201 return bytes.encode('utf-8')
204 for i,(out,err) in enumerate(procData):
205 res = procs[i].wait()
206 # Detect Ctrl-C in subprocess.
207 if res == -signal.SIGINT:
208 raise KeyboardInterrupt
210 # Ensure the resulting output is always of string type.
212 out = to_string(out.decode('utf-8'))
216 err = to_string(err.decode('utf-8'))
220 results.append((cmd.commands[i], out, err, res))
222 # Python treats the exit code as a signed char.
226 exitCode = min(exitCode, res)
228 exitCode = max(exitCode, res)
232 # Remove any named temporary files we created.
233 for f in named_temp_files:
240 exitCode = not exitCode
244 def executeScriptInternal(test, litConfig, tmpBase, commands, cwd):
248 cmds.append(ShUtil.ShParser(ln, litConfig.isWindows,
249 test.config.pipefail).parse())
251 return lit.Test.Result(Test.FAIL, "shell parser error on: %r" % ln)
255 cmd = ShUtil.Seq(cmd, '&&', c)
259 exitCode = executeShCmd(cmd, test.config, cwd, results)
260 except InternalShellError:
261 e = sys.exc_info()[1]
263 results.append((e.command, '', e.message, exitCode))
266 for i,(cmd, cmd_out,cmd_err,res) in enumerate(results):
267 out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args))
268 out += 'Command %d Result: %r\n' % (i, res)
269 out += 'Command %d Output:\n%s\n\n' % (i, cmd_out)
270 out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err)
272 return out, err, exitCode
274 def executeScript(test, litConfig, tmpBase, commands, cwd):
275 bashPath = litConfig.getBashPath();
276 isWin32CMDEXE = (litConfig.isWindows and not bashPath)
277 script = tmpBase + '.script'
283 if litConfig.isWindows and not isWin32CMDEXE:
284 mode += 'b' # Avoid CRLFs when writing bash scripts.
285 f = open(script, mode)
287 f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
289 if test.config.pipefail:
290 f.write('set -o pipefail;')
291 f.write('{ ' + '; } &&\n{ '.join(commands) + '; }')
296 command = ['cmd','/c', script]
299 command = [bashPath, script]
301 command = ['/bin/sh', script]
302 if litConfig.useValgrind:
303 # FIXME: Running valgrind on sh is overkill. We probably could just
304 # run on clang with no real loss.
305 command = litConfig.valgrindArgs + command
307 return lit.util.executeCommand(command, cwd=cwd,
308 env=test.config.environment)
310 def parseIntegratedTestScriptCommands(source_path):
312 parseIntegratedTestScriptCommands(source_path) -> commands
314 Parse the commands in an integrated test script file into a list of
315 (line_number, command_type, line).
318 # This code is carefully written to be dual compatible with Python 2.5+ and
319 # Python 3 without requiring input files to always have valid codings. The
320 # trick we use is to open the file in binary mode and use the regular
321 # expression library to find the commands, with it scanning strings in
322 # Python2 and bytes in Python3.
324 # Once we find a match, we do require each script line to be decodable to
325 # UTF-8, so we convert the outputs to UTF-8 before returning. This way the
326 # remaining code can work with "strings" agnostic of the executing Python
330 # Encode to UTF-8 to get binary data.
331 return str.encode('utf-8')
332 def to_string(bytes):
333 if isinstance(bytes, str):
335 return to_bytes(bytes)
337 keywords = ('RUN:', 'XFAIL:', 'REQUIRES:', 'END.')
338 keywords_re = re.compile(
339 to_bytes("(%s)(.*)\n" % ("|".join(k for k in keywords),)))
341 f = open(source_path, 'rb')
343 # Read the entire file contents.
346 # Iterate over the matches.
348 last_match_position = 0
349 for match in keywords_re.finditer(data):
350 # Compute the updated line number by counting the intervening
352 match_position = match.start()
353 line_number += data.count(to_bytes('\n'), last_match_position,
355 last_match_position = match_position
357 # Convert the keyword and line to UTF-8 strings and yield the
358 # command. Note that we take care to return regular strings in
359 # Python 2, to avoid other code having to differentiate between the
360 # str and unicode types.
361 keyword,ln = match.groups()
362 yield (line_number, to_string(keyword[:-1].decode('utf-8')),
363 to_string(ln.decode('utf-8')))
367 def parseIntegratedTestScript(test, normalize_slashes=False,
368 extra_substitutions=[]):
369 """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test
370 script and extract the lines to 'RUN' as well as 'XFAIL' and 'REQUIRES'
371 information. The RUN lines also will have variable substitution performed.
374 # Get the temporary location, this is always relative to the test suite
375 # root, not test source root.
377 # FIXME: This should not be here?
378 sourcepath = test.getSourcePath()
379 sourcedir = os.path.dirname(sourcepath)
380 execpath = test.getExecPath()
381 execdir,execbase = os.path.split(execpath)
382 tmpDir = os.path.join(execdir, 'Output')
383 tmpBase = os.path.join(tmpDir, execbase)
385 # Normalize slashes, if requested.
386 if normalize_slashes:
387 sourcepath = sourcepath.replace('\\', '/')
388 sourcedir = sourcedir.replace('\\', '/')
389 tmpDir = tmpDir.replace('\\', '/')
390 tmpBase = tmpBase.replace('\\', '/')
392 # We use #_MARKER_# to hide %% while we do the other substitutions.
393 substitutions = list(extra_substitutions)
394 substitutions.extend([('%%', '#_MARKER_#')])
395 substitutions.extend(test.config.substitutions)
396 substitutions.extend([('%s', sourcepath),
399 ('%{pathsep}', os.pathsep),
400 ('%t', tmpBase + '.tmp'),
402 ('#_MARKER_#', '%')])
404 # "%/[STpst]" should be normalized.
405 substitutions.extend([
406 ('%/s', sourcepath.replace('\\', '/')),
407 ('%/S', sourcedir.replace('\\', '/')),
408 ('%/p', sourcedir.replace('\\', '/')),
409 ('%/t', tmpBase.replace('\\', '/') + '.tmp'),
410 ('%/T', tmpDir.replace('\\', '/')),
413 # Collect the test lines from the script.
416 for line_number, command_type, ln in \
417 parseIntegratedTestScriptCommands(sourcepath):
418 if command_type == 'RUN':
419 # Trim trailing whitespace.
422 # Substitute line number expressions
423 ln = re.sub('%\(line\)', str(line_number), ln)
424 def replace_line_number(match):
425 if match.group(1) == '+':
426 return str(line_number + int(match.group(2)))
427 if match.group(1) == '-':
428 return str(line_number - int(match.group(2)))
429 ln = re.sub('%\(line *([\+-]) *(\d+)\)', replace_line_number, ln)
431 # Collapse lines with trailing '\\'.
432 if script and script[-1][-1] == '\\':
433 script[-1] = script[-1][:-1] + ln
436 elif command_type == 'XFAIL':
437 test.xfails.extend([s.strip() for s in ln.split(',')])
438 elif command_type == 'REQUIRES':
439 requires.extend([s.strip() for s in ln.split(',')])
440 elif command_type == 'END':
441 # END commands are only honored if the rest of the line is empty.
445 raise ValueError("unknown script command type: %r" % (
448 # Apply substitutions to the script. Allow full regular
449 # expression syntax. Replace each matching occurrence of regular
450 # expression pattern a with substitution b in line ln.
452 # Apply substitutions
453 for a,b in substitutions:
455 b = b.replace("\\","\\\\")
456 ln = re.sub(a, b, ln)
458 # Strip the trailing newline and any extra whitespace.
460 script = [processLine(ln)
463 # Verify the script contains a run line.
465 return lit.Test.Result(Test.UNRESOLVED, "Test has no run line!")
467 # Check for unterminated run lines.
468 if script[-1][-1] == '\\':
469 return lit.Test.Result(Test.UNRESOLVED,
470 "Test has unterminated run lines (with '\\')")
472 # Check that we have the required features:
473 missing_required_features = [f for f in requires
474 if f not in test.config.available_features]
475 if missing_required_features:
476 msg = ', '.join(missing_required_features)
477 return lit.Test.Result(Test.UNSUPPORTED,
478 "Test requires the following features: %s" % msg)
480 return script,tmpBase,execdir
482 def executeShTest(test, litConfig, useExternalSh,
483 extra_substitutions=[]):
484 if test.config.unsupported:
485 return (Test.UNSUPPORTED, 'Test is unsupported')
487 res = parseIntegratedTestScript(test, useExternalSh, extra_substitutions)
488 if isinstance(res, lit.Test.Result):
490 if litConfig.noExecute:
491 return lit.Test.Result(Test.PASS)
493 script, tmpBase, execdir = res
495 # Create the output directory if it does not already exist.
496 lit.util.mkdir_p(os.path.dirname(tmpBase))
499 res = executeScript(test, litConfig, tmpBase, script, execdir)
501 res = executeScriptInternal(test, litConfig, tmpBase, script, execdir)
502 if isinstance(res, lit.Test.Result):
505 out,err,exitCode = res
511 # Form the output log.
512 output = """Script:\n--\n%s\n--\nExit Code: %d\n\n""" % (
513 '\n'.join(script), exitCode)
515 # Append the outputs, if present.
517 output += """Command Output (stdout):\n--\n%s\n--\n""" % (out,)
519 output += """Command Output (stderr):\n--\n%s\n--\n""" % (err,)
521 return lit.Test.Result(status, output)