| 1 |
from hashlib import md5 |
| 2 |
import py, os, sys |
| 3 |
|
| 4 |
def cache_file_path(c_files, eci, cachename): |
| 5 |
"Builds a filename to cache compilation data" |
| 6 |
|
| 7 |
from rpython.translator.platform import platform |
| 8 |
from rpython.config.translationoption import CACHE_DIR |
| 9 |
cache_root = py.path.local(CACHE_DIR).ensure(dir=1) |
| 10 |
cache_dir = cache_root.join(cachename).ensure(dir=1) |
| 11 |
filecontents = [c_file.read() for c_file in c_files] |
| 12 |
key = repr((filecontents, eci, platform.key())) |
| 13 |
hash = md5(key).hexdigest() |
| 14 |
return cache_dir.join(hash) |
| 15 |
|
| 16 |
def build_executable_cache(c_files, eci, ignore_errors=False): |
| 17 |
"Builds and run a program; caches the result" |
| 18 |
|
| 19 |
from rpython.translator.platform import platform |
| 20 |
path = cache_file_path(c_files, eci, 'build_executable_cache') |
| 21 |
try: |
| 22 |
return path.read() |
| 23 |
except py.error.Error: |
| 24 |
_previous = platform.log_errors |
| 25 |
try: |
| 26 |
if ignore_errors: |
| 27 |
platform.log_errors = False |
| 28 |
result = platform.execute(platform.compile(c_files, eci)) |
| 29 |
if result.err: |
| 30 |
sys.stderr.write(result.err) |
| 31 |
finally: |
| 32 |
if ignore_errors: |
| 33 |
del platform.log_errors |
| 34 |
|
| 35 |
|
| 36 |
if platform.log_errors != _previous: |
| 37 |
platform.log_errors = _previous |
| 38 |
if not result.err: |
| 39 |
try_atomic_write(path, result.out) |
| 40 |
return result.out |
| 41 |
|
| 42 |
def try_atomic_write(path, data): |
| 43 |
path = str(path) |
| 44 |
tmppath = '%s~%d' % (path, os.getpid()) |
| 45 |
f = open(tmppath, 'wb') |
| 46 |
f.write(data) |
| 47 |
f.close() |
| 48 |
try: |
| 49 |
os.rename(tmppath, path) |
| 50 |
except OSError: |
| 51 |
try: |
| 52 |
os.unlink(tmppath) |
| 53 |
except OSError: |
| 54 |
pass |
| 55 |
|
| 56 |
def try_compile_cache(c_files, eci): |
| 57 |
"Try to compile a program. Cache success, and error message on failure" |
| 58 |
|
| 59 |
from rpython.translator.platform import platform, CompilationError |
| 60 |
path = cache_file_path(c_files, eci, 'try_compile_cache') |
| 61 |
try: |
| 62 |
data = path.read() |
| 63 |
if data == 'True': |
| 64 |
return True |
| 65 |
else: |
| 66 |
raise CompilationError(data, '') |
| 67 |
except py.error.Error: |
| 68 |
pass |
| 69 |
|
| 70 |
_previous = platform.log_errors |
| 71 |
try: |
| 72 |
platform.log_errors = False |
| 73 |
platform.compile(c_files, eci) |
| 74 |
except CompilationError as e: |
| 75 |
msg = e.out + e.err |
| 76 |
if msg != 'True': |
| 77 |
try_atomic_write(path, msg) |
| 78 |
raise |
| 79 |
finally: |
| 80 |
del platform.log_errors |
| 81 |
|
| 82 |
|
| 83 |
if platform.log_errors != _previous: |
| 84 |
platform.log_errors = _previous |
| 85 |
try_atomic_write(path, "True") |
| 86 |
return True |