From 6eecc65787abd1dcbbff157e0c3be73b03a4c225 Mon Sep 17 00:00:00 2001 From: sin-ack Date: Mon, 11 Jul 2022 19:59:54 +0000 Subject: [PATCH] AK: Explicitly calculate length of char* when printing This moves out the calculation of the char* out to the formatter. Additionally, we now print (null) when a null pointer is passed. --- AK/Format.h | 5 ++++- Userland/Libraries/LibCore/ArgsParser.cpp | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/AK/Format.h b/AK/Format.h index ddd612968d..b9b69ca15b 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -395,6 +395,8 @@ template<> struct Formatter : Formatter { }; +// FIXME: Printing raw char pointers is inherently dangerous. Remove this and +// its users and prefer StringView over it. template<> struct Formatter : Formatter { ErrorOr format(FormatBuilder& builder, char const* value) @@ -403,7 +405,8 @@ struct Formatter : Formatter { Formatter formatter { *this }; return formatter.format(builder, reinterpret_cast(value)); } - return Formatter::format(builder, value); + + return Formatter::format(builder, value != nullptr ? StringView { value, __builtin_strlen(value) } : "(null)"sv); } }; template<> diff --git a/Userland/Libraries/LibCore/ArgsParser.cpp b/Userland/Libraries/LibCore/ArgsParser.cpp index 021e83924f..ead8ed0925 100644 --- a/Userland/Libraries/LibCore/ArgsParser.cpp +++ b/Userland/Libraries/LibCore/ArgsParser.cpp @@ -275,8 +275,12 @@ void ArgsParser::print_usage_markdown(FILE* file, char const* argv0) for (auto& opt : m_options) { if (opt.hide_mode != OptionHideMode::None) continue; + + // FIXME: We allow opt.value_name to be empty even if the option + // requires an argument. This should be disallowed as it will + // currently display a blank name after the option. if (opt.requires_argument) - out(file, " [{} {}]", opt.name_for_display(), opt.value_name); + out(file, " [{} {}]", opt.name_for_display(), opt.value_name ?: ""); else out(file, " [{}]", opt.name_for_display()); }