From a695b9e572026ee0e214bb0fdd6d09db91d7a351 Mon Sep 17 00:00:00 2001 From: Jake Lamberson Date: Thu, 12 Dec 2024 11:17:58 -0500 Subject: [PATCH] Fix FFI cache race condition The race condition exists in the following circumstance: 1. PyVEX process 1 parses ffi and opens a new cache file but has not written to it 2. PyVEX process 2 goes to parse ffi, sees the existing (empty) cache file, opens it, then fails when it attempts to read an empty file This commit makes cache writing atomic, preventing the race condition. --- pyvex/native.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyvex/native.py b/pyvex/native.py index 34e47c08..ac3b41d4 100644 --- a/pyvex/native.py +++ b/pyvex/native.py @@ -46,8 +46,11 @@ def _parse_ffi_str(): "_declarations": ffi._parser._declarations, "_int_constants": ffi._parser._int_constants, } - with open(cache_location, "wb") as f: + # atomically write cache + temp_file = tempfile.NamedTemporaryFile(delete=False) + with open(temp_file.name, "wb") as f: f.write(pickle.dumps(cache)) + os.replace(temp_file.name, cache_location) def _find_c_lib():