Skip to content

Conversation

@dijkstracula
Copy link

@dijkstracula dijkstracula commented Nov 20, 2025

This patch ensures that two concurrent processes can't race on creating a temporary file during socketpair initialisation.

Fixes ocaml#14372 .

Test plan: Ensure it compiles on Windows; then, pending sanity-checks from the OCaml devs, have a SAF engineer pulled in for review and see if the CI issue is resolved.

@dijkstracula
Copy link
Author

OK, MSVC compilation succeeds (it's marked as failed in CI because something is strange about the test harness missing ocamltest, but it compiles and seemingly without any warnings). Making reference to this in the OCaml issue.

UINT unique = ((UINT)GetCurrentProcessId() << 16) |
(InterlockedIncrement(&tempfile_counter) & 0xFFFF);

if (GetTempFileName(dirname, L"osp", unique, path) == 0) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this will work. The GetTempFileName docs say, "[i]f uUnique is not zero, you must create the file yourself," so the following DeleteFile will fail. (All GetTempFileName seems to be doing with a nonzero uUnique is an sprintf--it doesn't even validate that the file doesn't exist.)

I'm also a little worried about only using the low 16 bits of the process ID and a 16-bit counter--for the process ID, I could see that rolling over in some not-completely-odd scenarios, and same for the counter (even if it wouldn't in semgrep). My suggestion would be to instead follow the GetTempFileName docs' advice:

Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files with the same prefix. In such cases, it is recommended that you construct unique file names based on GUIDs. You can also append the current process ID to the prefix string to reduce the likelihood of collisions in parallel operations.

(Maybe not GUIDs, but a 64-bit random number or something.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants