When opening a temporary file without O_CLOEXEC we risk leaking the
file descriptor if another thread calls (fork and then) exec while we
have the fd open. Fix this by consistently passing O_CLOEXEC everywhere
where we open a file for internal use (and not to return it to the user,
in which case the API defines whether or not the close-on-exec flag
shall be set on the returned fd).
Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
Signed-off-by: Sergey Bugaev <bugaevc@gmail.com>
Message-Id: <
20230419160207.65988-4-bugaevc@gmail.com>
char *buf = NULL;
if (strchr (cat_name, '/') != NULL || nlspath == NULL)
- fd = __open_nocancel (cat_name, O_RDONLY);
+ fd = __open_nocancel (cat_name, O_RDONLY | O_CLOEXEC);
else
{
const char *run_nlspath = nlspath;
if (bufact != 0)
{
- fd = __open_nocancel (buf, O_RDONLY);
+ fd = __open_nocancel (buf, O_RDONLY | O_CLOEXEC);
if (fd >= 0)
break;
}
*cp++ = '/';
__stpcpy (__stpcpy (cp, GLRO(dl_profile)), ".profile");
- fd = __open64_nocancel (filename, O_RDWR|O_CREAT|O_NOFOLLOW, DEFFILEMODE);
+ fd = __open64_nocancel (filename, O_RDWR | O_CREAT | O_NOFOLLOW
+ | O_CLOEXEC, DEFFILEMODE);
if (fd == -1)
{
char buf[400];
size_t len = strlen (env);
char buf[len + 20];
__snprintf (buf, sizeof (buf), "%s.%u", env, __getpid ());
- fd = __open_nocancel (buf, O_CREAT|O_TRUNC|O_WRONLY|O_NOFOLLOW, 0666);
+ fd = __open_nocancel (buf, O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW
+ | O_CLOEXEC, 0666);
}
if (fd == -1)
{
- fd = __open_nocancel ("gmon.out", O_CREAT|O_TRUNC|O_WRONLY|O_NOFOLLOW,
- 0666);
+ fd = __open_nocancel ("gmon.out", O_CREAT | O_TRUNC | O_WRONLY
+ | O_NOFOLLOW | O_CLOEXEC, 0666);
if (fd < 0)
{
char buf[300];
return -1;
/* See whether the cache file exists. */
- fd = __open_nocancel (GCONV_MODULES_CACHE, O_RDONLY, 0);
+ fd = __open_nocancel (GCONV_MODULES_CACHE, O_RDONLY | O_CLOEXEC, 0);
if (__builtin_expect (fd, 0) == -1)
/* Not available. */
return -1;
int fd;
/* Open WTMP file. */
- fd = __open_nocancel (file, O_WRONLY | O_LARGEFILE);
+ fd = __open_nocancel (file, O_WRONLY | O_LARGEFILE | O_CLOEXEC);
if (fd < 0)
return -1;
__sem_open (const char *name, int oflag, ...)
{
int fd;
+ int open_flags;
sem_t *result;
/* Check that shared futexes are supported. */
/* If the semaphore object has to exist simply open it. */
if ((oflag & O_CREAT) == 0 || (oflag & O_EXCL) == 0)
{
+ open_flags = O_RDWR | O_NOFOLLOW | O_CLOEXEC;
+ open_flags |= (oflag & ~(O_CREAT|O_ACCMODE));
try_again:
- fd = __open (dirname.name,
- (oflag & ~(O_CREAT|O_ACCMODE)) | O_NOFOLLOW | O_RDWR);
+ fd = __open (dirname.name, open_flags);
if (fd == -1)
{
}
/* Open the file. Make sure we do not overwrite anything. */
- fd = __open (tmpfname, O_RDWR | O_CREAT | O_EXCL, mode);
+ open_flags = O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC;
+ fd = __open (tmpfname, open_flags, mode);
if (fd == -1)
{
if (errno == EEXIST)