Subject: Re: posix_spawn facility
From: "gs-cygwin.com--- via Cygwin" <[email-masked]>
To: Bruno Haible <[email-masked]>
Cc: [email-masked]
Date: Thu, 20 Apr 2023 16:00:07 -0400
List-Id: General Cygwin discussions and problem reports <cygwin.cygwin.com>

On Thu, Apr 20, 2023 at 09:31:38PM +0200, Bruno Haible wrote:
> Glenn wrote:
> > > > https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-startupinfoexa
> > > > 
> > > > and the PROC_THREAD_ATTRIBUTE_HANDLE_LIST argument described in
> > > > 
> > > > https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-updateprocthreadattribute
> > > ...
> > Excellent (very technical) article on the subject:
> > 
> > Programmatically controlling which handles are inherited by new processes in Win32
> > https://devblogs.microsoft.com/oldnewthing/20111216-00/?p=8873
> 
> It's nice to see an example for PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
> 
> But the article exaggerates a problem:
>   "But all this inheritability fiddling still had a fatal flaw: What
>    if two threads within the same process both call CreateProcess but
>    disagree on which handles they want to be inherited?"
> The answer, overlooked in the article, is to use DuplicateHandle
> and set the inheritability of the duplicate to true. Concurrently
> running posix_spawn invocations in other threads will not see the
> duplicates, since they only see HANDLEs that are assigned to file
> descriptors, not HANDLEs that merely reside in some data structure
> in memory.

It might not be an issue if everything -- and I mean everything -- goes
through posix_spawn() to create processes.

The article is from 2011 and about Windows.  If a third-party dll
running in another thread calls CreateProcess() and does not explicitly
restrict the inherited handles using the techiques in the article, then
there is still that race that might leak additional handles into the
other process.

In the case of cygwin, the cygwin layer could/should be able to
centralize and control process creation, avoiding the race.
Even if there were any steps that need to be protected, wrapping
in a CriticalSection (or mutex) would probably be sufficient.

Cheers, Glenn

-- 
Problem reports:      https://cygwin.com/problems.html
FAQ:                  https://cygwin.com/faq/
Documentation:        https://cygwin.com/docs.html
Unsubscribe info:     https://cygwin.com/ml/#unsubscribe-simple