Skip to content

Commit f098b44

Browse files
marc-hbnashif
authored andcommitted
cmake: atomic rename to fix toolchain cache creation race
While this race seems unlikely and harmless let's play it safe and implement the usual solution: temporary file + atomic rename. The race is unlikely and maybe even harmless because: - Only sanitycheck seems to invoke cmake concurrently. - Users rarely delete their ~/.cache/zephyr/ToolchainCapabilityDatabase/ - All concurrent cmake processes write the same, single byte to the same files. - Creating a single byte is at least very fast, so extremely short window for others to read an empty file. For additional background see links in issue #9992 Signed-off-by: Marc Herbert <[email protected]>
1 parent 3061c92 commit f098b44

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

cmake/extensions.cmake

+21-1
Original file line numberDiff line numberDiff line change
@@ -679,11 +679,31 @@ function(zephyr_check_compiler_flag lang option check)
679679

680680
# Populate the cache
681681
if(NOT (EXISTS ${key_path}))
682+
683+
# This is racy. As often with race conditions, this one can easily be
684+
# made worse and demonstrated with a simple delay:
685+
# execute_process(COMMAND "sleep" "5")
686+
# Delete the cache, add the sleep above and run sanitycheck with a
687+
# large number of JOBS. Once it's done look at the log.txt file
688+
# below and you will see that concurrent cmake processes created the
689+
# same files multiple times.
690+
691+
# While there are a number of reasons why this race seems both very
692+
# unlikely and harmless, let's play it safe anyway and write to a
693+
# private, temporary file first. All modern filesystems seem to
694+
# support at least one atomic rename API and cmake's file(RENAME
695+
# ...) officially leverages that.
696+
string(RANDOM LENGTH 8 tempsuffix)
697+
682698
file(
683699
WRITE
684-
${key_path}
700+
"${key_path}_tmp_${tempsuffix}"
685701
${inner_check}
686702
)
703+
file(
704+
RENAME
705+
"${key_path}_tmp_${tempsuffix}" "${key_path}"
706+
)
687707

688708
# Populate a metadata file (only intended for trouble shooting)
689709
# with information about the hash, the toolchain capability

0 commit comments

Comments
 (0)