1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 14:18:12 +00:00

LibC+Kernel: Remove global variable use from snprintf and fprintf

The global variable use in these functions is super thread-unsafe and
means that any concurrent calls to sprintf or fprintf in a process
could race with each other and end up writing unexpected results.
We can just replace the function + global variable with a lambda that
captures the relevant argument when calling printf_internal instead.
This commit is contained in:
Andrew Kaster 2022-02-08 22:33:35 -07:00 committed by Brian Gianforcaro
parent 8ec4328fcb
commit 353e72ac9b
2 changed files with 21 additions and 32 deletions

View file

@ -123,26 +123,24 @@ int sprintf(char* buffer, const char* fmt, ...)
return ret;
}
static size_t __vsnprintf_space_remaining;
ALWAYS_INLINE void sized_buffer_putch(char*& bufptr, char ch)
{
if (__vsnprintf_space_remaining) {
*bufptr++ = ch;
--__vsnprintf_space_remaining;
}
}
int snprintf(char* buffer, size_t size, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
size_t space_remaining = 0;
if (size) {
__vsnprintf_space_remaining = size - 1;
space_remaining = size - 1;
} else {
__vsnprintf_space_remaining = 0;
space_remaining = 0;
}
auto sized_buffer_putch = [&](char*& bufptr, char ch) {
if (space_remaining) {
*bufptr++ = ch;
--space_remaining;
}
};
int ret = printf_internal(sized_buffer_putch, buffer, fmt, ap);
if (__vsnprintf_space_remaining) {
if (space_remaining) {
buffer[ret] = '\0';
} else if (size > 0) {
buffer[size - 1] = '\0';