Skip to content

tinystdio: Resolve issue with tmpnam #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 37 additions & 17 deletions newlib/libc/tinystdio/mktemp.c
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,12 @@ _gettemp (char *path,
int *doopen,
int flags)
{
char *start, *trv;
char *trv;
char *end;
static char inc = 0;
static char pos = 1;

__LIBC_LOCK();

end = path + strlen(path) - suffixlen;
trv = end;
Expand All @@ -112,13 +116,35 @@ _gettemp (char *path,
if (end - trv < 6)
{
errno = EINVAL;
__LIBC_UNLOCK();
return 0;
}

start = trv + 1;
trv += pos;

for (;;)
{
/* Increment the string of letters to generate another name */
for(;;)
{
if (trv == end)
{
__LIBC_UNLOCK();
return 0;
}

if ((*trv + inc - 1) == 'z') {
*trv++ = 'a';
pos++;
inc = 1;
}
else {
*trv += inc;
inc++;
break;
}
}

/*
* Use open to check if the file exists to avoid depending on
* stat or access. Don't rely on O_EXCL working, although if it
Expand All @@ -128,39 +154,33 @@ _gettemp (char *path,
if (fd < 0) {
if (errno != EACCES) {
if (errno != ENOENT)
{
__LIBC_UNLOCK();
return 0;
}
if (doopen)
{
fd = open (path, flags | O_CREAT | O_EXCL | O_RDWR,
0600);
if (fd >= 0) {
*doopen = fd;
__LIBC_UNLOCK();
return 1;
}
if (errno != EEXIST)
{
__LIBC_UNLOCK();
return 0;
}
} else {
__LIBC_UNLOCK();
return 1;
}
}
} else
close(fd);

/* Increment the string of letters to generate another name */
trv = start;
for(;;)
{
if (trv == end)
return 0;
if (*trv == 'z')
*trv++ = 'a';
else {
++ * trv;
break;
}
}
}
/*NOTREACHED*/
__LIBC_UNLOCK();
}

int
Expand Down