Skip to content
This repository was archived by the owner on Mar 26, 2024. It is now read-only.

Commit cb3e98d

Browse files
committed
Check if O_CLOEXEC is defined before using it in open()
Previously we checked if SOCK_CLOEXEC was defined before using SOCK_CLOEXEC, but we continued to check for SOCK_CLOEXEC after we switched to using O_CLOEXEC. Also use fcntl(F_GETFD) before fcntl(F_SETFD) to comport with the Standard.
1 parent d8bb4d1 commit cb3e98d

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

ext/mysql2/client.c

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -182,23 +182,31 @@ static void *nogvl_connect(void *ptr) {
182182
*/
183183
static VALUE invalidate_fd(int clientfd)
184184
{
185-
#ifdef SOCK_CLOEXEC
185+
#ifdef O_CLOEXEC
186186
/* Atomically set CLOEXEC on the new FD in case another thread forks */
187187
int sockfd = open("/dev/null", O_RDWR | O_CLOEXEC);
188-
if (sockfd < 0) {
189-
/* Maybe SOCK_CLOEXEC is defined but not available on this kernel */
190-
int sockfd = open("/dev/null", O_RDWR);
191-
fcntl(sockfd, F_SETFD, FD_CLOEXEC);
192-
}
193188
#else
194-
/* Well we don't have SOCK_CLOEXEC, so just set FD_CLOEXEC quickly */
195-
int sockfd = open("/dev/null", O_RDWR);
196-
fcntl(sockfd, F_SETFD, FD_CLOEXEC);
189+
/* Well we don't have O_CLOEXEC, trigger the fallback code below */
190+
int sockfd = -1;
197191
#endif
198192

199193
if (sockfd < 0) {
200-
/*
201-
* Cannot raise here, because one or both of the following may be true:
194+
/* Either O_CLOEXEC wasn't defined at compile time, or it was defined at
195+
* compile time, but isn't available at run-time. So we'll just be quick
196+
* about setting FD_CLOEXEC now.
197+
*/
198+
int flags;
199+
sockfd = open("/dev/null", O_RDWR);
200+
flags = fcntl(sockfd, F_GETFD);
201+
/* Do the flags dance in case there are more defined flags in the future */
202+
if (flags != -1) {
203+
flags |= FD_CLOEXEC;
204+
fcntl(sockfd, F_SETFD, flags);
205+
}
206+
}
207+
208+
if (sockfd < 0) {
209+
/* Cannot raise here, because one or both of the following may be true:
202210
* a) we have no GVL (in C Ruby)
203211
* b) are running as a GC finalizer
204212
*/

0 commit comments

Comments
 (0)