From 49c7900407514b072ef5ce01ee2d737659be0b84 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 8 Oct 2022 18:44:14 +0200 Subject: [PATCH] Add %m to userspace printf %m as a format specifier is a nonstandard glibc extension, but I like it so I'm implementing it. What it does is print the value of strerror(errno), without consuming any arguments to printf(). --- apps/src/memeater.c | 2 +- libs/libc/src/printf.cpp | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/src/memeater.c b/apps/src/memeater.c index d8e87306..761eb910 100644 --- a/apps/src/memeater.c +++ b/apps/src/memeater.c @@ -15,7 +15,7 @@ int main() printf("Allocating 4 MB of memory... %p\n", allocated); sleep(1); } while ((allocated = malloc(CHUNK))); - perror("malloc"); + printf("Memory allocation failed: %m\n"); printf("Press any key to restart.\n"); return 1; } \ No newline at end of file diff --git a/libs/libc/src/printf.cpp b/libs/libc/src/printf.cpp index 740cc394..31f9750f 100644 --- a/libs/libc/src/printf.cpp +++ b/libs/libc/src/printf.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -251,6 +252,21 @@ static int internal_printf(const char* format, PutString put_string_callback, ss if (buffer_insert_index == 1024) flush_buffer(); break; } + case 'm': { + const char* str = strerror(errno); + while (strlen(str) > 1024) + { + flush_buffer(); + memcpy(buffer, str, 1024); + str += 1024; + buffer_insert_index = 1024; + } + if (buffer_insert_index + strlen(str) > 1024) flush_buffer(); + memcpy(buffer + buffer_insert_index, str, strlen(str)); + buffer_insert_index += strlen(str); + if (buffer_insert_index == 1024) flush_buffer(); + break; + } case 's': { const char* str = va_arg(ap, const char*); while (strlen(str) > 1024)