From 6baf2c42c5a3098c3ec566dcab301e6b80b0b2ae Mon Sep 17 00:00:00 2001 From: Jake Lamberson Date: Thu, 30 Jan 2025 17:02:57 -0500 Subject: [PATCH] Fix FFI cache race condition (#452) 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 | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pyvex/native.py b/pyvex/native.py index 34e47c08..4c9f211f 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: - f.write(pickle.dumps(cache)) + # atomically write cache + with tempfile.NamedTemporaryFile(delete=False) as temp_file: + temp_file.write(pickle.dumps(cache)) + temp_file_name = temp_file.name + os.replace(temp_file_name, cache_location) def _find_c_lib():