This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH 1/3] <fd_to_filename.h>: Add type safety and port to Hurd
On 2/15/20 5:16 AM, Florian Weimer wrote:
INT_STRLEN_BOUND is 11, right?
Yes, it's a bound on the string length of a printed int, and that's 11 in the
typical case of 32-bit int because the int might be negative. I didn't lose
sleep over the wasted byte, but if we want a tighter bound then we could use
INT_STRLEN_BOUND (int) - 1 instead. However, it might be better to leave it
alone so that we can use the code below.
The problem is when an application passes an invalid descriptor to some
libc function and that ends up with __fd_to_filename. We should not
make matters worse in that case.
If it's not a precondition that the descriptor is nonnegative, we can't simply
return a copy of FD_TO_FILENAME_PREFIX as that's an existing filename. Instead,
how about the following? It uses a randomish garbage filename beginning with "-"
which should be good enough, and it doesn't cost a conditional branch to handle
negative descriptors.
char *
__fd_to_filename (int descriptor, struct fd_to_filename *storage)
{
char *p = mempcpy (storage->buffer, FD_TO_FILENAME_PREFIX,
strlen (FD_TO_FILENAME_PREFIX) - 1);
/* If DESCRIPTOR is negative, arrange for the filename to not exist
by prepending any byte other than '/', '.', '\0' or an ASCII digit.
The rest of the filename will be gibberish that fits. */
*p = '-';
p += descriptor < 0;
for (int d = descriptor; p++, (d /= 10) != 0; )
continue;
*p = '\0';
for (int d = descriptor; *--p = '0' + d % 10, (d /= 10) != 0; )
continue;
return storage->buffer;
}