Index: src/trusted/validator/x86/testing/tf/utils.py |
diff --git a/src/trusted/validator/x86/testing/tf/utils.py b/src/trusted/validator/x86/testing/tf/utils.py |
new file mode 100644 |
index 0000000000000000000000000000000000000000..179410c9b63278e2da787ff8ab632a8cf1ea36f8 |
--- /dev/null |
+++ b/src/trusted/validator/x86/testing/tf/utils.py |
@@ -0,0 +1,68 @@ |
+# Copyright (c) 2012 The Native Client Authors. All rights reserved. |
+# Use of this source code is governed by a BSD-style license that can be |
+# found in the LICENSE file. |
+ |
+import os |
+import subprocess |
+import tempfile |
+ |
+ |
+def DataToReadableHex(data): |
+ """Convert string of bytes to string of hexes ('\xde\xad' -> 'de ad'). |
+ |
+ Args: |
+ data: String (used to represent sequence of bytes). |
+ |
+ Returns: |
+ String of space-separated hex codes. |
+ """ |
+ |
+ return ' '.join('%02x' % ord(c) for c in data) |
+ |
+ |
+def ReadableHexToData(s): |
+ """Convert string of hexes to string of bytes ('be ef' -> '\xbe\xef'). |
+ |
+ Args: |
+ s: String of space-separated two-character hex codes. |
+ |
+ Returns: |
+ String representing sequence of bytes. |
+ """ |
+ |
+ bytes = s.split() |
+ assert all(len(byte) == 2 for byte in bytes) |
+ return ''.join(chr(int(byte, 16)) for byte in bytes) |
+ |
+ |
+def CheckOutput(args, **kwargs): |
+ # reimplementation of subprocess.check_output from py 2.7 |
+ assert 'stdout' not in kwargs |
+ |
+ process = subprocess.Popen(args, stdout=subprocess.PIPE, **kwargs) |
+ output, _ = process.communicate() |
+ |
+ if process.returncode != 0: |
+ raise subprocess.CalledProcessError(process.returncode, cmd=args[0]) |
+ |
+ return output |
+ |
+ |
+# Custom context manager that allows temporary file to be reopened |
+# and deletes it on exit. |
+# NamedTemporareFile with delete=True won't do the job because |
+# it can't be reopened on Windows. |
+class TempFile(object): |
+ def __init__(self, mode='w+b'): |
+ self.file = tempfile.NamedTemporaryFile(mode=mode, delete=False) |
+ |
+ def __enter__(self): |
+ return self.file |
+ |
+ def __exit__(self, exc_type, exc_value, traceback): |
+ self.file.close() |
+ |
+ # The check is needed because gnu style compilers (AS in particular) |
+ # have habit to delete output file when there are compilation errors. |
+ if os.path.exists(self.file.name): |
+ os.remove(self.file.name) |